如何将2个存储json对象从Web服务存储到sqlite android

时间:2016-08-30 06:03:08

标签: android json sqlite

[{"id":"33020002","uname":"sanjeevani eye and fracture care"},{"id":"33020036","uname":"arogya niketan hospital"},{"id":"33020044","uname":"arihant hospital"},{"id":"33020050","uname":"kamlesh netralaya"},{"id":"33020059","uname":"LIFELINE HOSPITAL AND MATERNITY CENTRE"},{"id":"33020063","uname":"KUNDLA MEMORIAL HOSPITAL"}]

希望将以上数据存储在sqlite json datawebservice .net提供

1 个答案:

答案 0 :(得分:0)

       Try this:

           [{"id":"33020002","uname":"sanjeevani eye and fracture care"},
{"id":"33020036","uname":"arogya niketan hospital"},
{"id":"33020044","uname":"arihant hospital"},
{"id":"33020050","uname":"kamlesh netralaya"},
{"id":"33020059","uname":"LIFELINE HOSPITAL AND MATERNITY CENTRE"},
{"id":"33020063","uname":"KUNDLA MEMORIAL HOSPITAL"}]
 final NoolDataBaseHelper dbs = new NoolDataBaseHelper(NoolReaderDashboard.this);
 JsonArrayRequest jreq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject jo = response.getJSONObject(i);
                            String Id= jo.getString("id");
                            String Uname = jo.getString("uname");
                            dbs.Value(Id, Uname);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }


                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });

    MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}

//In DatabaseHelper class

     private static final String TABLE_Values= "category";      //categroy 
     private static final String CATKEY_ID = "id";
     private static final String CATKEY_NAMES = "name";

      public void onCreate(SQLiteDatabase db) {
    String CREATE_Categorytable = "CREATE TABLE " + TABLE_Values + "(" + KEY_ID + " INTEGER PRIMARY KEY," + CATKEY_ID + " TEXT," + CATKEY_NAMES + " TEXT" + ")";
    db.execSQL(CREATE_Categorytable);
    }

     public void Value(String id, String Uname) {

    // TODO Auto-generated method stub

    bookname = bookname.trim();


    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(CATKEY_ID, id);
        values.put(CATKEY_NAMES,Uname);

        // Inserting Row

        db.insert(TABLE_Values, null, values);
        Log.d("inserted success", TABLE_Values);
        db.close(); // Closing database connection

    } catch (Exception e) {
        e.printStackTrace();
    }

}