将 Gson 数据插入 Android Sqlite

Insert Gson Data into Android Sqlite

我正在调用 Web 服务,我在数组 [] 中获取了数据。我想将这些数据插入到 sqlite 数据库中。我在服务器和 sqlite 上也有相同的数据库结构。

让我们从模型开始 class

public class RateList {

    public int id;
    public String Name;
    public String description;
    public String amount;
    public String image;
}

我正在使用 volley 从 Web 服务获取数据。我正在获取以下代码所需格式的数据,只需要部分代码

public void onResponse(String response) {
       Log.e("response",response);
       RateList[] itemList;
       itemList = new Gson().fromJson(response, RateList[].class);
       helper.insertData(itemList);
}

这是我从网络服务得到的响应。

[
  {
    "id": "1",
    "Name": "pendrive",
    "description": "8 GB",
    "amount": "350",
    "image": "http://my_website_url/Demo/images/9.png"
  },
  {
    "id": "2",
    "Name": "headphone",
    "description": "",
    "amount": "4500",
    "image": "http://my_website_url/Demo/images/1.png"
  },
  .
  .
  .
]

现在我正在尝试将 RateList[] itemList 这个 Gson 数据插入数据库这是我的 DbHelper 代码。

public void insertData(RateList[] itemList) {

    db = getWritableDatabase();

    for (int i = 0; i < itemList.length; i++) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("id", ""+itemList[i].id);
        contentValues.put("Name", itemList[i].Name);
        contentValues.put("description", itemList[i].description);
        contentValues.put("amount", itemList[i].amount);
        contentValues.put("image", itemList[i].image);
        db.insert(tableName, null, contentValues);
    }
}

当我调试我的应用程序时,contentValues 显示 key = 0 和 value = 1;我不知道我哪里弄错了。我在网上查了一下,没有具体的例子。

在insertData函数中, 尝试在 for 循环之前仅启动一次 contentValues。

db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
    for (int i = 0; i < itemList.length; i++) {
       ...
        db.insert(tableName, null, contentValues);
    }

代码似乎没问题,请交叉检查列名称和 table 名称。如果值存在于 contentValue 对象

中,则在赋值后检查 contentValue 对象