更新 SQLite 数据库 Android RecyclerView 迭代

Posted

技术标签:

【中文标题】更新 SQLite 数据库 Android RecyclerView 迭代【英文标题】:Update SQLite Database Android RecyclerView Iterate 【发布时间】:2020-06-02 22:30:48 【问题描述】:

我有一项名为购物车(购物车)的活动。我使用 SQLite 来存储项目并在 RecyclerView 中显示数据。我的问题是当我需要增加或减少数量时,因为我的代码采用默认数量(1)并且增加等于 2 并且减少了 0。我需要更新我的数据库我知道,但我真的不明白怎么做。我看到 Sqlexec 和 ContentValues 有 2 个替代方案,但我真的不知道如何实现它。如果有人可以帮助我,我将非常感激。我把我的适配器类和数据库放在这里。

public class cartItemRecyclerView extends RecyclerView.Adapter<cartItemRecyclerView.ViewHolder>

ArrayList<items> itemsList;
Context context;

interface IImageButtonListener
    void onImageButtonClick(View view,int pos,boolean isDecrease);


public cartItemRecyclerView(Context context, ArrayList<items> itemsList)
    this.context = context;
    this.itemsList = itemsList;


public cartItemRecyclerView(ArrayList<items> item) 
    this.itemsList = item;


@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Inflate the custom layout
    View contactView = inflater.inflate(R.layout.list_cart_item_view,parent,false);

    // Return a new holder instance
    ViewHolder viewHolder = new ViewHolder(contactView);

    return viewHolder;


@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) 

    // Get the data model based on position
    items itm = itemsList.get(position);

    // Set item views based on your view and data model

    holder.nameC.setText(itm.getlName());
    holder.iconC.setImageResource(itm.getlImageId());
    holder.priceC.setText(itm.getlPrice()+ "");
    holder.quantityC.setText(itm.getQuantity()+"");

    holder.setListener(new IImageButtonListener() 
        @Override
        public void onImageButtonClick(View view, int pos, boolean isDecrease) 
            if(isDecrease)
                int i = itemsList.get(pos).getQuantity();
                i++;
                // Update in database
                holder.quantityC.setText(i+"");

            
            else 
                int i = itemsList.get(pos).getQuantity();
                i--;
                // Update in database
                holder.quantityC.setText(i+"");
            

        
    );



@Override
public int getItemCount() 
    return itemsList.size();


public class ViewHolder extends RecyclerView.ViewHolder
    public TextView nameC, priceC, quantityC;
    public ImageView increaseC, decreaseC, iconC;
    IImageButtonListener listener;

    public void setListener(IImageButtonListener listener)
        this.listener = listener;
    

    public ViewHolder(View itemView)
        super(itemView);

        nameC = itemView.findViewById(R.id.name_item_cart);
        priceC = itemView.findViewById(R.id.price_item_cart);
        quantityC = itemView.findViewById(R.id.textview_quantity_items);
        increaseC = itemView.findViewById(R.id.image_increase_quantity);
        decreaseC = itemView.findViewById(R.id.image_decrease_quantity);
        iconC = itemView.findViewById(R.id.icon_item_cart);

        // Event
        increaseC.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                listener.onImageButtonClick(v, getAdapterPosition(),true);
            
        );

        decreaseC.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                listener.onImageButtonClick(v, getAdapterPosition(),false);
            
        );
    
 

这是 DB SQLite 代码。

public class DatabaseHelper extends SQLiteOpenHelper 

public static final String DATABASE_NAME = "favorites.db";
public static final String TABLE_NAME_CART = "cart_table";

public static final String COL_1 = "IMAGE";
public static final String COL_2 = "NAME";
public static final String COL_3 = "PRICE";
public static final String COL_4 = "DETAILS";
public static final String COL_5 = "MODEL";
public static final String COL_6 = "IMAGEE";
public static final String COL_7 = "IMAGEEE";
public static final String COL_8 = "QUANTITY";

public DatabaseHelper(Context context) 
    super(context, DATABASE_NAME, null, 1);


private static DatabaseHelper sDatabaseHelper;

public static DatabaseHelper getInstance(Context context) 
    if (sDatabaseHelper == null) 
        sDatabaseHelper = new DatabaseHelper(context);
    
    return sDatabaseHelper;


@Override
public void onCreate(SQLiteDatabase db) 

    db.execSQL("CREATE TABLE " + TABLE_NAME_CART + " (" + COL_1 + " INTEGER, " + COL_2 + " VARCHAR, " + COL_3 + " INTEGER, " + COL_4 + " VARCHAR, " + COL_5 + " VARCHAR, " + COL_6 + " INTEGER, " + COL_7 + " INTEGER, " + COL_8 + " INTEGER);");



@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_CART);
    onCreate(db);


// Insert Data in cart table
public boolean insertDataCart(items items) 
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_1, items.getlImageId());
    contentValues.put(COL_2, items.getlName());
    contentValues.put(COL_3, items.getlPrice());
    contentValues.put(COL_4, items.getlDetails());
    contentValues.put(COL_5, items.getlModel());
    contentValues.put(COL_6, items.getlImageId1());
    contentValues.put(COL_7, items.getlImageId2());
    contentValues.put(COL_8, items.getQuantity());

    long result = db.insert(TABLE_NAME_CART, null, contentValues);

    if (result == -1) 
        return false;
     else 
        return true;
    



// See Data Cart
public ArrayList<items> getAllDataCart() 
    ArrayList<items> favItem = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME_CART, null);

    while (res.moveToNext()) 
        int img = res.getInt(0);
        String name = res.getString(1);
        int price = res.getInt(2);
        String details = res.getString(3);
        String model = res.getString(4);
        int img1 = res.getInt(5);
        int img2 = res.getInt(6);
        int quantity = res.getInt(7);
        items newItems = new items(name, price, img, img1, img2, details, model,quantity);
        favItem.add(newItems);
    
    return favItem;

这里我使用 RecyclerView

 public class cart extends AppCompatActivity 

private DatabaseHelper favoriteDbHelper;
private ArrayList<items> item;
private cartItemRecyclerView cartItemRecyclerView;
private RecyclerView recyclerView;

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

    recyclerView = (RecyclerView) findViewById(R.id.cart_recycler);

    favoriteDbHelper = new DatabaseHelper(this);
    item = favoriteDbHelper.getAllDataCart();

    cartItemRecyclerView = new cartItemRecyclerView(item,favoriteDbHelper,this);
    recyclerView.setAdapter(cartItemRecyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

【问题讨论】:

【参考方案1】:

你可以试试这个。

添加到数据库助手

    public boolean updateDataCard(int id, int quantity) 

    ContentValues val = new ContentValues();

    val.put(COL_8, quantity);

    int result =  db.update(TABLE_NAME_CART, val, "IMAGE=" + id, null);
    if (result == -1) 
     return false;
     else 
     return true;
    

您必须传递您的数据库对象。可以使用 with 构造方法。

ArrayList<items> itemsList;
Context context;
YourDBObject db;

interface IImageButtonListener
 void onImageButtonClick(View view,int pos,boolean isDecrease);
 

 public cartItemRecyclerView(Context context, ArrayList<items> 
  itemsList,YourDBObject db)
     this.context = context;
     this.itemsList = itemsList;
     this.db = db;

然后你就可以打电话了。

   if(isDecrease)
            int i = itemsList.get(pos).getQuantity();
            int id = itemsList.get(pos).getImageId();
            i++;
            // Update in database
            if(i <= 2)
            db.updateDataCard(id,i)
            holder.quantityC.setText(i+"");
              
        
        else 
            int i = itemsList.get(pos).getQuantity();
            int id = itemsList.get(pos).getImageId();
            i--;
            // Update in database
            if( i < 2 && i >= 0 )
               db.updateDataCard(id,i)
               holder.quantityC.setText(i+"");
            

希望能帮到你。

【讨论】:

现在的问题是,他只迭代,数量是1,他迭代2和0,如果我让数量在2上,我退出活动,我再次进入,当我按 + 和 - 他分别按 3 和 1,她按,我怎么能阻止呢? 如何在主要活动中提取数据?您应该将用于执行此操作的对象传递给构造函数类。对不起,我的英语不好。 我把班级放在了问题中。 可以添加if控件。 好的,但是如果和在哪里呢?

以上是关于更新 SQLite 数据库 Android RecyclerView 迭代的主要内容,如果未能解决你的问题,请参考以下文章

Android 使用Room操作数据库进行数据库版本的升级和迁移

在 android 中将 SQLite 数据从平板电脑更新到手机

Android:在 RecyclerView 中拖放项目时如何有效更新 SQLite 数据库?

更新 blob 后,Android sqlite 无法读取

Android版本更新时对SQLite数据库升级或者降级遇到的问题

当我在 Android 应用程序中更新我的 Sqlite 数据库时,如何向用户发送通知?