使用SQLite将Web服务器中的JSON值存储到数据库中

时间:2016-06-22 07:34:16

标签: android json sqlite

在我的应用中,我从JSON响应中检索了一些数据。我也可以展示它们。

       @Override
       public void onResponse(JSONArray response) {
           Log.d("Theo", response.toString());
           //I use i=1 to bypass the first JSON object which doesn't contain the object member.
           //If i set i=0,then I will get an exception.
           for(int i = 1;i<response.length();i++){


               try {

                   //Here I read the 4 objects.
                   JSONObject jsonObject = response.getJSONObject(i);

                       //I get the members array for JSON object
                       JSONArray teamMembersArray = jsonObject.getJSONArray("members");


                       for(int j=0;j<teamMembersArray.length();j++) {

                           //The model class which contains the setters/getters
                           //in order to "deserialize" the JSON objects into string objects.
                           Model m = new Model();


                           JSONObject teamObject = teamMembersArray.getJSONObject(j);
                           //I am searching if the teamLead object exists.If yes
                           //then set it to true by reading it! If not then read
                           //the next members!
                          if (teamObject.has("teamLead") && (!teamObject.isNull("teamLead")))  {
                               m.setTeamLead(teamObject.getBoolean("teamLead"));
                           }else {
                               //Default value
                               m.setTeamLead(false);

                           }
                           m.setId(teamObject.getInt("id"));
                           m.setProfileImageURL(teamObject.getString("profileImageURL"));
                           m.setFirstName(teamObject.getString("firstName"));
                           m.setLastName(teamObject.getString("lastName"));
                           m.setRole(teamObject.getString("role"));

                           //Finally I am adding the string objects into an ArrayList.
                           modelArrayList.add(m);

                           int id = Integer.parseInt(teamObject.getString("id"));
                           String fname = teamObject.getString("firstName");
                           String lname = teamObject.getString("lastName");
                           String role = teamObject.getString("role");
                           String proImage = teamObject.getString("profileImageURL");
                           saveToDB(id,fname,lname,role,proImage);
                       }
               } catch (JSONException e) {
                   e.printStackTrace();
               }

           }

saveToDB方法是

  private void saveToDB(int id,String firstName,String lastName,String role,String image){

    //myMovie.setContent(descriptionText.getText().toString());

    dba.addMembers(id,firstName,lastName,role,image);
    dba.close();

}

下一步是在SQLite的帮助下存储它们,以防没有互联网连接。所以我首先从我的回复中获取字符串(从JSON转换而来)。

  int id = Integer.parseInt(teamObject.getString("id"));
                       String fname = teamObject.getString("firstName");
                       String lname = teamObject.getString("lastName");
                       String role = teamObject.getString("role");
                       String proImage = teamObject.getString("profileImageURL");
                       saveToDB(id,fname,lname,role,proImage);

然后使用将它们传递给DatabaseHandler类的addMembers(...)方法。

public class DatabaseHandler extends SQLiteOpenHelper {
private final ArrayList<SQLiteModel> membersList = new ArrayList<>();
public DatabaseHandler(Context context) {
    super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TEST_TABLE = "CREATE TABLE " + Constants.TABLE_NAME +
            "(" + Constants.MEMBER_ID + " INTEGER PRIMARY KEY, " + Constants.FIRST_NAME +
            " TEXT, "  +  Constants.LAST_NAME + " TEXT, " + Constants.JOB_ROLE + " TEXT, " +
            Constants.PROFILE_IMAGE + " TEXT);";
    db.execSQL(CREATE_TEST_TABLE);
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + Constants.TABLE_NAME);
}
//add content to table
public void addMembers(int id,String firstName,String lastName,String role,String image) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(Constants.MEMBER_ID,id);
    values.put(Constants.FIRST_NAME, firstName);
    values.put(Constants.LAST_NAME,lastName);
    values.put(Constants.JOB_ROLE,role);
    values.put(Constants.PROFILE_IMAGE,image);





    db.insert(Constants.TABLE_NAME, null, values);

    db.close();

    Log.v("DB","heeeey!data saved");
}

//get all folders
public ArrayList<SQLiteModel> getMembersDetails() {
   //I am stuck in this part. Boolean variables are not recognized
   //in SQLite. So I have to make the getTeamLead() method from
   //Model class,to return an int. But this will mess up my
   //my recycler view.


    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(Constants.TABLE_NAME, new String[]{
            Constants.MEMBER_ID, Constants.FIRST_NAME,Constants.LAST_NAME,Constants.JOB_ROLE,Constants.PROFILE_IMAGE}, null, null, null, null, Constants.MEMBER_ID + " DESC");


    if (cursor.moveToFirst()) {
        do {

            SQLiteModel sqLiteModel = new SQLiteModel();
            sqLiteModel.setSqlId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.MEMBER_ID))));

            sqLiteModel.setSqlFirstName(cursor.getString(cursor.getColumnIndex(Constants.FIRST_NAME)));
            sqLiteModel.setSqlLastName(cursor.getString(cursor.getColumnIndex(Constants.LAST_NAME)));
            sqLiteModel.setSqlRole(cursor.getString(cursor.getColumnIndex(Constants.JOB_ROLE)));
            sqLiteModel.setSqlProfileImageURL(cursor.getString(cursor.getColumnIndex(Constants.PROFILE_IMAGE)));


            membersList.add(sqLiteModel);
        }while(cursor.moveToNext());


    }
    return membersList;
}

}

当我运行我的应用程序时,我会为每个条目获取此logcat输出,即。

06-22 07:30:22.831 17732-17732/testing.theo.androidtestproject    
E/SQLiteDatabase: 
Error inserting lastName=Corke firstName=Hannah   
profileImageURL=http://developers.mub.lu/resources/profilePlaceholder.png 
id=24 role=Designer                                                                         
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed:   
testdb.id (code 1555)

任何想法为什么会发生这种情况?

谢谢Theo。

1 个答案:

答案 0 :(得分:0)

您应该使用db.insertWithOnConflict()功能。请查看文档here