1

I am calling a web service I got data in array[]. I wanted to insert this data inside sqlite database. I have database structure same at server and sqlite as well.

Let's start with model class

public class RateList {

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

I am using volley to get data from web service. I am getting data in desire format below code is only require part of code

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

This is response I get from web service.

[
  {
    "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"
  },
  .
  .
  .
]

Now I am trying to insert RateList[] itemList this Gson data into database this is my DbHelper code.

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

When I debug my app contentValues shows key = 0 and value = 1; I don't know where I made mistake. I searched on online but there was no specific example for this.

Ashish Kudale
  • 1,230
  • 1
  • 27
  • 51

2 Answers2

1

In the insertData function, Try initiating the contentValues just once before the for loop.

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

The code seems to be fine, cross check the column names and table name. Also check contentValue object after assigning values if the values exist in the contentValue object

Hitesh
  • 331
  • 2
  • 10