java - 回收器 View 仅在再次启动 Activity 后才显示更新的列表

标签 java android sqlite android-recyclerview

我已经从 sqlite 填充了 recyclerview。当单击删除按钮时,行将从 sqlite 中删除,当单击编辑按钮时,值从 sqlite 更新,但 recyclerview 在删除或编辑后不显示更新的列表。仅在再次启动 Activity 后,回收器 View 才会显示更新的列表。我的问题是如何在从回收器 View 中删除或更新项目后立即更新回收器 View 而不刷新。

我使用recyclerview的 fragment 代码:

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);

    }
}

}

最佳答案

删除更新后,您还需要更新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中的产品对象:

   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();

关于java - 回收器 View 仅在再次启动 Activity 后才显示更新的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61886625/

相关文章:

java - 根据o2对应的getter设置o1的所有setter

c# - 在采样率为 48000 的 MP3 中获得采样率为 44100 的帧。Mp3FileReader 不支持采样率更改

Java 类加载 - 哪个类加载器和/或类导致加载?

java - 连接 Neo4j 时出现异常

java - Android Smack 客户端下线

java - 按钮android,文本位置

mysql - 在该脚本中创建数据库后如何传递 sqlite 查询..?

vb.net - 摆脱App.exe.config

java - 委托(delegate)其参数的构造函数

android - 未找到引用 android.target.classpath