2016-07-27 58 views
0

我打电话给一个Web服务我在数组[]中获取数据。我想在sqlite数据库中插入这些数据。我在服务器和sqlite上也有相同的数据库结构。插入Gson数据到Android 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); 
} 

这是我从Web服务获得的响应。

[ 
    { 
    "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显示键= 0和值= 1;我不知道我犯了什么错误。我在网上搜索过,但没有具体的例子。

回答

1

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

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

该代码似乎很好,交叉检查列名和表名。如果值存在于contentValue对象中,则在分配值后检查contentValue对象