简体   繁体   English

RecyclerView 不更新

[英]RecyclerView not update

My MainActivity has a recyclerview that will receive the products.我的 MainActivity 有一个 recyclerview 将接收产品。 In the floatActionButton of MainActivity and I call AddActivity which has the fields to add the product, including a recycler where I insert inputs to compose the price.在 MainActivity 的 floatActionButton 中,我调用 AddActivity ,它具有添加产品的字段,包括一个回收器,我在其中插入输入以构成价格。 the problem is exactly in the AddActivity recyclerView问题正是在 AddActivity recyclerView

I have a simple recyclerView and the adapter below where I do the CRUD before saving to the database, and everything works except the update, where I update the item through the adapter but the view in the list does not update the data.我有一个简单的 recyclerView 和下面的适配器,在保存到数据库之前我在其中执行 CRUD,除了更新之外一切正常,我通过适配器更新项目但列表中的视图不更新数据。 If you click on the same item to edit it again it shows the values that have already been updated and not those shown in the list.如果您单击同一项目再次对其进行编辑,则它会显示已更新的值,而不是列表中显示的值。

Below my adapter:在我的适配器下面:

public class InsumoAdapter extends RecyclerView.Adapter<InsumoAdapter.InsumoViewHolder>{

   
    private final Context context;
    private List<Insumo> insumos;


    public InsumoAdapter(Context context, List<Insumo> insumos) {
        this.context = context;
        this.insumos = insumos;
    }

    @Override
    public InsumoAdapter.InsumoViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.card_teste, viewGroup, false);
        InsumoAdapter.InsumoViewHolder holder = new InsumoAdapter.InsumoViewHolder(view);
        return holder;
    }

    public static class InsumoViewHolder extends RecyclerView.ViewHolder{
        public TextView tNome, tVlrCusto;
        ImageButton btnDelete;
        CardView cardView;
        public InsumoViewHolder(View view){
            super(view);
            tNome = (TextView) view.findViewById(R.id.txtNomeProd);
            tVlrCusto = (TextView) view.findViewById(R.id.txtValorProd);
            btnDelete = (ImageButton) view.findViewById(R.id.imgBtnDel);
            cardView = (CardView) view.findViewById(R.id.cardProduto);
        }
    }

    @Override
    public void onBindViewHolder(final InsumoViewHolder holder, final int position) {
        if(insumos.size() != 0){
            final Insumo p = insumos.get(position);
            holder.tNome.setText(p.getNomeInsumo());
            holder.tVlrCusto.setText(p.getValor().toString());

            holder.cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "Clicou no Card para Editar na posição "+position,Toast.LENGTH_SHORT).show();
                    Bundle bundle = new Bundle();
                    //bundle.putString("nome", p.getNomeInsumo());
                    //bundle.putDouble("valor", p.getValor());
                    bundle.putInt("position", position);
                    Intent intent = new Intent(context, UpdateActivity.class);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                    //update(p, position);
                }
            });

            holder.btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "Clicou no Card para Excluir na posição "+position,Toast.LENGTH_SHORT).show();
                    delete(position);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return this.insumos != null ? this.insumos.size() : 0;
    }


    private void excluirInsumo(Context context, final int i){
        String titulo = "Excluir";
        String msg = "Deseja excluir este item?";
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle(titulo);
        alertDialog.setMessage(msg);
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Sim",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //deleta("Pproduto",produtos.get(i).get_id());
                        AddActivity addActivity = new AddActivity();
                        //addActivity.deleta(i);

                        dialog.dismiss();
                    }
                });
        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Não",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }

    private void delete(int position){
        insumos.remove(position);
        notifyItemRemoved(position);
    }

    public void update(Insumo insumo, int position){
        insumos.set(position, insumo);
        //notifyItemChanged(position);
        notifyDataSetChanged();
    }

    public void insere(Insumo insumo){
        insumos.add(insumo);
        notifyDataSetChanged();
    }


It's like not going back to onBindViewHolder to update the data.这就像不回到 onBindViewHolder 来更新数据一样。 Could someone give me a light?有人可以给我一盏灯吗? If you need something, but you can't find any way.如果你需要一些东西,但你找不到任何方法。

Editing-----编辑-----

AddActivity添加活动

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

        edtNome = (TextInputEditText) findViewById(R.id.edtNome);
        valorCusto = (TextView) findViewById(R.id.txtValorCustoAdd);
        valorVenda = (TextView) findViewById(R.id.txtValorVendaAdd);
        valorPerc = (TextView) findViewById(R.id.txtValorPercAdd);
        addItem = (FloatingActionButton) findViewById(R.id.fltBtnAddItem);
        addFoto = (FloatingActionButton) findViewById(R.id.fltBtnAddFoto);
        salvar = (FloatingActionButton) findViewById(R.id.fltBtnSalvar);
        imgFoto = (ImageView) findViewById(R.id.imgFoto);
        recyclerView = (RecyclerView) findViewById(R.id.recy);

        edtNome.setTextIsSelectable(true);

        valorCusto.setText(valor.toString());
        valorPerc.setText("0");

        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setHasFixedSize(true);

        InsumoAdapter insumoAdapter = new InsumoAdapter(getApplicationContext(), insumos);

        recyclerView.setAdapter(insumoAdapter);
        insumoAdapter.notifyDataSetChanged();

        addItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplication(), InsertActivity.class);
                startActivity(intent);
            }
        });

        salvar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Produto produto = new Produto();
                produto.setpNome(edtNome.getText().toString());
                produto.setpValorCusto(somaValor(insumos));
                if(foto == 0){
                    produto.setPfoto(R.drawable.noimage);
                }else{
                    produto.setPfoto(foto);
                }
            }
        });
    }

Activity of insumo's insert insumo的插入活动

update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insumo = new Insumo();
                insumo.setNomeInsumo(nome.getText().toString());
                Log.d(TAG, getClass()+" insumo.getNome = "+insumo.getNomeInsumo());
                insumo.setValor(Double.parseDouble(valor.getText().toString()));
                Log.d(TAG, getClass()+" insumo.getValor = "+insumo.getValor());
                AddActivity addActivity = new AddActivity();
                //addActivity.update(insumo, pos);
                InsumoAdapter insumoAdapter = new InsumoAdapter(getBaseContext(), addActivity.lista());
                insumoAdapter.update(insumo, pos);
                insumoAdapter.notifyDataSetChanged();
                finish();
            }
        });

MainAcitvity主要活动

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

        recyclerView = (RecyclerView) findViewById(R.id.recyclerTeste);
        FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.fltBtnAdd);

        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setHasFixedSize(true);

        ProdutoAdapter produtoAdapter = new ProdutoAdapter(getBaseContext(), produtos);

        recyclerView.setAdapter(produtoAdapter);
        produtoAdapter.notifyDataSetChanged();


        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
            }
        });

Instead of creating a new Adapter, just use the current adapter instance and use it for update and notifyDataSetChanged.无需创建新的 Adapter,只需使用当前的适配器实例并将其用于更新和 notifyDataSetChanged。

public InsumoAdapter insumoAdapter;

// Inside onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
    ....
    insumoAdapter = new InsumoAdapter(getApplicationContext(), insumos);
    ....
}

// Inside Update onClick
update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    ....
    insumoAdapter.update(insumo, pos)
    insumoAdapter.notifyDataSetChanged()
}

The problem is;问题是; you're creating a new instance of adapter instead of using the adapter attached to your recyclerView .您正在创建一个新的适配器实例,而不是使用附加到您的recyclerView的适配器。 Please use the same instance of adapter that's attached to your recyclerView.请使用附加到您的 recyclerView 的相同适配器实例。

In your Activity where your recyclerView is instantiated, use a member reference to contain your reference.在您的 recyclerView 实例化的 Activity 中,使用成员引用来包含您的引用。 ie mInsumoAdaptermInsumoAdapter

Then when you create your first adapter instance and attach it to your recyclerView, assign it to mInsumoAdapter .然后,当您创建第一个适配器实例并将其附加到您的 recyclerView 时,将其分配给mInsumoAdapter

Finally use the same reference to call your update method.最后使用相同的引用来调用您的update方法。

mInsumoAdapter.update(insumo, pos);

For sharing references between activities and services, you can create a common sharing class like this:对于活动和服务之间的共享引用,您可以像这样创建一个公共共享 class:

public class ReferenceUtil {
    private static InsumoAdapter insumoAdapter;

    public static InsumoAdapter getMainAdapter(){
        return insumoAdapter;
    }

    public static void setMainAdapter(InsumoAdapter adapter) {
        insumoAdapter = adapter;
    }
}

Then use ReferenceUtil.setMainAdapter(adapter);然后使用ReferenceUtil.setMainAdapter(adapter); when you click on your FAB, and on your next activity use ReferenceUtil.getMainAdapter();当您单击您的 FAB 并在您的下一个活动中使用ReferenceUtil.getMainAdapter(); to obtain your attached reference and update that for your recyclerView to get updated on runtime.获取您附加的参考并更新您的 recyclerView 以在运行时更新。

Remember to set the static insumoAdapter in ReferenceUtil to null when you return back to your previous activity because it could lead to a memory leak in your application.当您返回之前的活动时,请记住将ReferenceUtil中的 static insumoAdapter设置为 null,因为这可能会导致您的应用程序中出现 memory 泄漏。

Try with using notifyDataSetChnaged() in the activity from where you are passing the list to the adapter or you could do it after updating it.尝试在将列表传递给适配器的活动中使用 notifyDataSetChnaged() ,或者您可以在更新它之后执行此操作。 something like this,像这样的东西,

RecyclerView.setAdapter(this,list);
notifyDataSetChanged();

or或者

InsumoAdapter.update(list,pos);
notifyDataSetChanged();

You could try use this way for all the CRUD operations.您可以尝试将这种方式用于所有 CRUD 操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM