回收器视图在编辑项目后未更新项目

问题描述 投票:0回答:1

在我的 Android 应用程序中,我有一个 RecyclerView,其中包含来自名为

Apiario
的类的对象列表。在列表的每一项中,我都提供了删除该项目或编辑其变量之一的选项。我还可以选择将新项目添加到列表中。当用户选择编辑项目时,新活动将以表单开始,以便他可以输入新值。

当我删除一个项目时,一切都会按预期工作,并且该项目确实从 ArrayList 中删除了。

当我添加一个项目时,一切都会按预期工作。

问题是当我尝试更新项目时。尽管在表单活动中对象已正确更新,但一旦我返回到带有 RecyclerView 的视图,更改就不存在了。

Recycler查看活动

public class AnualDeclarationActivity extends AppCompatActivity implements ApiarioAdapter.ApiarioClickListener {

    private ApiarioAdapter apiarioAdapter;

    private ArrayList<Apiario> apiList;
    private static final int EDIT_APIARIO_REQUEST_CODE = 1;
    private static final int ADD_APIARIO_REQUEST_CODE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_anual_declaration);

        RecyclerView recyclerView = findViewById(R.id.recyclerViewApiarios);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        this.apiList = new ArrayList<>();

        DatabaseReference mDatabaseQuery = 
        FirebaseDatabase.getInstance().getReference("apiario");

        Query query = mDatabaseQuery.orderByChild("estado").equalTo("Aceite");

        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for(DataSnapshot dataSnapshot : snapshot.getChildren()){

                    Apiario apiario = dataSnapshot.getValue(Apiario.class);
                    apiList.add(apiario);
                }

                apiarioAdapter = new ApiarioAdapter(apiList, AnualDeclarationActivity.this);
                recyclerView.setAdapter(apiarioAdapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

        ImageButton btnAddApiario = findViewById(R.id.btnAddApiario);
        btnAddApiario.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AnualDeclarationActivity.this, AddApiarioActivity.class);
                startActivityForResult(intent, ADD_APIARIO_REQUEST_CODE);
            }
        });
    }

    @Override
    public void onEditClick(Apiario apiario) {
        Intent intent = new Intent(this, EditApiarioActivity.class);
        intent.putExtra("apiario", apiario);
        startActivityForResult(intent, EDIT_APIARIO_REQUEST_CODE);
    }

    @Override
    public void onDeleteClick(Apiario apiario) {
        showDeleteConfirmationDialog(apiario);
    }

    private void showDeleteConfirmationDialog(final Apiario apiario) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Delete Apiario");
        builder.setMessage("Are you sure you want to delete this Apiario?");

        builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                deleteApiario(apiario);
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });

        builder.create().show();
    }

    private void deleteApiario(Apiario apiario) {
        apiList.remove(apiario);
        apiarioAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ADD_APIARIO_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            Apiario newApiario = data.getParcelableExtra("newApiario");
            apiList.add(newApiario);
            apiarioAdapter.notifyDataSetChanged();
        }

        if (requestCode == EDIT_APIARIO_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            Apiario modifiedApiario = data.getParcelableExtra("modifiedApiario");
            int position = findPositionOfApiarioInList(modifiedApiario);
            if (position != -1) {
                apiList.set(position, modifiedApiario);
                apiarioAdapter.notifyItemChanged(position);
            }
        }
    }

    private int findPositionOfApiarioInList(Apiario apiario) {
        for (int i = 0; i < apiList.size(); i++) {
            if (apiList.get(i).getNomeApiario().equals(apiario.getNomeApiario())) {
                return i;
            }
        }
        return -1;
    }
}

适配器

public class ApiarioAdapter extends RecyclerView.Adapter<ApiarioAdapter.ApiarioViewHolder> {

    private List<Apiario> apiarios;
    private ApiarioClickListener listener;

    public interface ApiarioClickListener {
        void onEditClick(Apiario apiario);
        void onDeleteClick(Apiario apiario);
    }

    public ApiarioAdapter(List<Apiario> apiarios, ApiarioClickListener listener) {
        this.apiarios = apiarios;
        this.listener = listener;
    }

    public class ApiarioViewHolder extends RecyclerView.ViewHolder {
        TextView textName;
        TextView textColmeias;

        Button btnEdit;
        Button btnDelete;

        public ApiarioViewHolder(@NonNull View itemView) {
            super(itemView);
            textName = itemView.findViewById(R.id.textName);
            textColmeias =itemView.findViewById(R.id.textColmeias);


            btnEdit = itemView.findViewById(R.id.btnEdit);
            btnDelete = itemView.findViewById(R.id.btnDelete);
        }
    }

    @NonNull
    @Override
    public ApiarioViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.apiario_item, parent, false);
        return new ApiarioViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ApiarioViewHolder holder, int position) {
        final Apiario apiario = apiarios.get(position);

        holder.textName.setText("Nome: " + apiario.getNomeApiario());
        holder.textColmeias.setText("Colmeias: " + apiario.getNumColmeias());

        holder.btnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Apiario selectedApiario = apiarios.get(holder.getAdapterPosition());
                openEditApiarioActivity(view.getContext(), selectedApiario);
            }
        });

        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onDeleteClick(apiario);
            }
        });
    }

    private void openEditApiarioActivity(Context context, Apiario apiario) {
        Intent intent = new Intent(context, EditApiarioActivity.class);
        intent.putExtra("apiario", apiario);
        context.startActivity(intent);
    }

    @Override
    public int getItemCount() {
        return apiarios.size();
    }
}

编辑 Apiario 活动

public class EditApiarioActivity extends AppCompatActivity {

    private EditText editTextNumColmeias;
    private Button btnSubmit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_apiario);

        editTextNumColmeias = findViewById(R.id.edtNumColmeias);
        btnSubmit = findViewById(R.id.btnSubmit);

        Apiario apiario = getIntent().getParcelableExtra("apiario");

        if (apiario != null) {
            editTextNumColmeias.setText(String.valueOf(apiario.getNumColmeias()));
        }

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int modifiedNumColmeias = Integer.parseInt(editTextNumColmeias.getText().toString());

                if (apiario != null) {
                    apiario.setNumColmeias(modifiedNumColmeias);
                    Intent resultIntent = new Intent();
                    resultIntent.putExtra("modifiedApiario", apiario);
                    setResult(RESULT_OK, resultIntent);
                    finish();
                }
            }
        });
    }
}

我尝试在代码中放置日志,这就是我发现的:

  • 当我点击EditApiarioActivity上的提交按钮后,方法
    onActivityResult
    没有被调用。
  • 选定的 Apiario 已正确传递到 EditApiarioActivity
  • EditApiarioActivity 正确更新对象,但当应用程序返回到 RecyclerViewActivity 时,更改不会反映出来

我做错了什么?我找不到问题。

java android android-recyclerview android-adapter
1个回答
0
投票

问题出在您的 Adapter 类中。

holder.btnEdit.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
          Apiario selectedApiario = apiarios.get(holder.getAdapterPosition());
          openEditApiarioActivity(view.getContext(), selectedApiario);
      }
});

你忘了调用监听器

listener.onEditClick(apiario);

因此,当您单击编辑时,它将运行此块:

    private void openEditApiarioActivity(Context context, Apiario apiario) {
        Intent intent = new Intent(context, EditApiarioActivity.class);
        intent.putExtra("apiario", apiario);
        context.startActivity(intent);
    }

你看,这只是startActivity,而不是startActivityForResult

© www.soinside.com 2019 - 2024. All rights reserved.