回收站视图仅在再次启动活动后才显示更新列表

Posted

技术标签:

【中文标题】回收站视图仅在再次启动活动后才显示更新列表【英文标题】:Recycler view show updated list only after launching activity once again 【发布时间】:2020-09-05 06:09:55 【问题描述】:

我已经从 sqlite 填充了 recyclerview。当单击删除按钮时,行将从 sqlite 中删除,当单击从 sqlite 更新的编辑按钮值时,recyclerview 在删除或编辑后不显示更新的列表。。我的问题是如何在不刷新的情况下从 recyclerview 删除或更新项目后立即更新 recycler 视图。

我使用recyclerview的片段代码:

List<Product> productList = new ArrayList<>();
RecyclerView recyclerView;
SQLiteDatabase mDatabase;
public static ProductAdapter adapter;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) 
    saveViewModel = ViewModelProviders.of(this).get(SaveViewModel.class);
    View root = inflater.inflate(R.layout.fragment_save, container, false);
    /* final TextView textView = root.findViewById(R.id.text_gallery);*/

    recyclerView = root.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    mDatabase = getActivity().openOrCreateDatabase(Add_Activity.DATABASE_NAME, MODE_PRIVATE, null);
    showDataFromDatabase();
    saveViewModel.getText().observe(getActivity(), new Observer<String>() 
        @Override
        public void onChanged(@Nullable String s) 
            /* textView.setText(s);*/
        
    );
    return root;


private void showDataFromDatabase() 
    //we used rawQuery(sql, selectionargs) for fetching all the fields
    Cursor cursorproduct = mDatabase.rawQuery(" SELECT * FROM items", null);

    //if the cursor has some data
    if (cursorproduct.moveToFirst()) 
        //looping through all the records
        do 
            //pushing each record in the field list
            productList.add(new Product(
                    cursorproduct.getInt(0),
                    cursorproduct.getString(1),
                    cursorproduct.getString(2),
                    cursorproduct.getString(3),
                    cursorproduct.getString(4),
                    cursorproduct.getString(5),
            ));
         while (cursorproduct.moveToNext());
    
    if (productList.isEmpty()) 
        Toast.makeText(getActivity(), "No items Found in database", Toast.LENGTH_SHORT).show();
    

    //closing the cursor
    cursorproduct.close();
    //creating the adapter object
    adapter = new ProductAdapter(getActivity(), R.layout.show_field_items, productList, mDatabase);
    //adding the adapter to listview
    recyclerView.setAdapter(adapter);
    adapter.reloadEmployeesFromDatabase();  //this method is in prdouctadapter
    adapter.notifyDataSetChanged();

查看模型类:

public class Product 

private int id;
private String date;
private String category;
private String fsub_category;
private String fname;
private String fphone;

public Product(int id, String date, String category, String fsub_category, String fname, String fphone) 
    this.id = id;
    this.date = date;
    this.category = category;
    this.fsub_category =fsub_category;
    this.fname = fname;
    this.fphone = fphone;



public int getId() 
    return id;


public String getFname() 
    return fname;


public String getFcategory() 
    return category;


public String getFsub_category() 
    return fsub_category;


public String getFphone() 
    return fphone;


public String getFdate() 
    return date;

产品适配器类:

public ProductAdapter(Context mCtx, int custom_list_item, List<Product> productList, SQLiteDatabase mDatabase) 
    this.mCtx = mCtx;
    this.custom_list_item = custom_list_item;
    this.mDatabase = mDatabase;
    this.productList = productList;


@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
    //inflating and returning our view holder
    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.show_field_items, null);
    return new ProductViewHolder(view);


@Override
public void onBindViewHolder(ProductViewHolder holder, int position) 
    //getting the product of the specified position
    final Product product = productList.get(position);

    //binding the data with the viewholder views
    holder.Category.setText(product.getFcategory());
    holder.Date.setText(product.getFdate());
    holder.Area.setText(product.getFcategoty());

    holder.editbtn.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            updateEmployee(product);
        
    );
    holder.deletebtn.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(final View view) 
            AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
            builder.setTitle("Are you sure?");
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() 
                @Override
                public void onClick(DialogInterface dialogInterface, int i) 
                    String sql = "DELETE FROM items WHERE id = ?";
                    mDatabase.execSQL(sql, new Integer[]product.getId());
                    Snackbar.make(view, "Deleted" + product.getFcategory(), Snackbar.LENGTH_SHORT).show();
                    Toast.makeText(mCtx, "Deleted successfully!", Toast.LENGTH_SHORT).show();
                    reloadEmployeesFromDatabase(); //Reload List
                
            );
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
                @Override
                public void onClick(DialogInterface dialogInterface, int i) 
                
            );
            AlertDialog dialog = builder.create();
            dialog.show();
        
    );


public void reloadEmployeesFromDatabase() 
    Cursor cursorproduct1 = mDatabase.rawQuery("SELECT * FROM items", null);
    if (cursorproduct1.moveToFirst()) 
        productList.clear();
        do 
            productList.add(new Product(
                    cursorproduct1.getInt(0),
                    cursorproduct1.getString(1),
                    cursorproduct1.getString(2),
                    cursorproduct1.getString(3),
                    cursorproduct1.getString(4),
                    cursorproduct1.getString(5)

            ));
         while (cursorproduct1.moveToNext());
    
    cursorproduct1.close();
    notifyDataSetChanged();



private void updateEmployee(final Product product) 
    final AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);

    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.update_form, null);
    builder.setView(view);

    category = view.findViewById(R.id.spiner);
    final EditText editsubcat= view.findViewById(R.id.editsubcategory);
    final EditText editFname = view.findViewById(R.id.editFarmerName);
    final EditText editphno = view.findViewById(R.id.editFarmerphno);
    String cat = category.getSelectedItem().toString().trim();

    editsubcat.setText(product.getFsub_category());
    editFname.setText(product.getFname());
    editphno.setText(product.getFphone());

    final AlertDialog dialog = builder.create();
    dialog.show();

    // CREATE METHOD FOR EDIT THE FORM
    view.findViewById(R.id.buttonUpdateEmployee).setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            String Crop = category.getSelectedItem().toString().trim();
            String Sub_Category = editsubcat.getText().toString().trim();
            String Farmer_Name = editFname.getText().toString().trim();
            String Farmer_phone_No = editphno.getText().toString().trim();

     /*       if (Crop.isEmpty()) 
                editTextName.setError("Name can't be blank");
                editTextName.requestFocus();
                return;
            

            if (Sub_Category.isEmpty()) 
                editUsername.setError("Salary can't be blank");
                editUsername.requestFocus();
                return;
            //Name, Email, UserName, PhoneNo*/

            String sql = "UPDATE items \n" +
                    "SET Category = ?, \n" +
                    "Sub_Category = ?,\n" +
                    "Farmer_Name = ?,\n" +
                    "Farmer_phone_No= ? \n" +
                    "WHERE id = ?;\n";

            mDatabase.execSQL(sql, new String[]Crop,Sub_Category, Farmer_Name, Farmer_phone_No, String.valueOf(product.getId()));
            Toast.makeText(mCtx, "data Updated", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
            List<Product> pro = productList;
            productList.clear();
            productList.addAll(pro);

        
    );

    notifyDataSetChanged();

 /*  notifyItemRangeChanged(0, productList.size());*/



  /*    public void updateList(List<Product> itemList)
    
        this.productList.clear();
        this.productList.addAll(itemList);
        notifyDataSetChanged();
    */
  /* private void updateList(List<Product> products) 

        this.productList.clear();
        this.productList.addAll(products);
        productAdapter.notifyDataSetChanged();


*/
@Override
public int getItemCount() 
    return productList.size();


public void setData(List<Product> items) 
    productList = items;



class ProductViewHolder extends RecyclerView.ViewHolder 

    TextView Date, Category, Area;

    Button editbtn, deletebtn;
    public ProductViewHolder(View itemView) 
        super(itemView);

        Category = itemView.findViewById(R.id.f_category);
        Date = itemView.findViewById(R.id.f_date);
        Area = itemView.findViewById(R.id.f_area);

    

【问题讨论】:

在您调用 reloadEmployeesFromDatabase(); 后点击器监听器上的删除按钮;做 adapter.notifyDataSetchanged() 或者你可以试试 adapter.notifyItemRemoved(position); 【参考方案1】:

删除更新后,您需要更新productList 以及:

holder.deletebtn.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(final View view) 
            AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
            builder.setTitle("Are you sure?");
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() 
                @Override
                public void onClick(DialogInterface dialogInterface, int i) 
                    String sql = "DELETE FROM items WHERE id = ?";
                    mDatabase.execSQL(sql, new Integer[]product.getId());
                    Snackbar.make(view, "Deleted" + product.getFcategory(), Snackbar.LENGTH_SHORT).show();
                    Toast.makeText(mCtx, "Deleted successfully!", Toast.LENGTH_SHORT).show();
                    //reloadEmployeesFromDatabase(); //Reload List
                     productList.remove(product); //like that after notify adapter
                     notifyDataSetchanged();

                
            );
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
                @Override
                public void onClick(DialogInterface dialogInterface, int i) 
                
            );
            AlertDialog dialog = builder.create();
            dialog.show();
        
    );

在更新中,您需要更新 productList 中的产品 obj:

   String Crop = category.getSelectedItem().toString().trim();
    String Sub_Category = editsubcat.getText().toString().trim();
    String Farmer_Name = editFname.getText().toString().trim();
    String Farmer_phone_No = editphno.getText().toString().trim();

 // afer updating in  sqlite db  and also need to create setter in model
 productList.get(position).setFcategory(Crop);
  ..........
//after pudating all feild like that just notify data set 
 notifyDataSetchanged();

【讨论】:

删除功能很好用,但编辑后如何更新数据 位置变红表示无法解析位置 在updateEmployee(product,position)中传递位置;并将其用于函数中。 非常感谢 :)

以上是关于回收站视图仅在再次启动活动后才显示更新列表的主要内容,如果未能解决你的问题,请参考以下文章

为recyclerview更新帖子的评论数

Android 回收站视图更新

在不重新加载活动的情况下更新回收站视图中的内容

如何在第一个活动中更新回收站视图,同时更改其他活动中的数据?

如何在 RecyclerView 中选择和取消选择项目?如何仅在回收站视图中突出显示所选项目?

仅第一次调用 LiveData onChanged 方法