将Gson数据插入Android Sqlite

时间:2016-07-27 19:46:38

标签: android sqlite gson android-volley content-values

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

让我们从模型类

开始
public class RateList {

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

我正在使用凌空从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"
  },
  .
  .
  .
]

现在我正在尝试将这个Gson数据RateList[] itemList插入数据库,这是我的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;我不知道我犯了什么错误。我在网上搜索过,但没有具体的例子。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

,则在分配值后检查contentValue对象