我将我的服务器端发送JSON data到数据库中,之后我显示在listview. 但是,虽然在服务器端更改或我的 json 数据会增加,但它不会反映或更改我的数据库,实际上在更改我的 JSON 后,我希望我的数据库也像旧 + 新一样更新。它必须将新的也保存在数据库中,同时任何数据也添加到服务器端。
这是我的 JSON 部分:
{
  "post": [
    {
      "id": 249,
      "title": "Career",
      "content": "Last ten days ,work is not going well",
      "count": 0
    },
    {
      "id": 248,
      "title": "Career",
      "content": "Last ten days ,work is not going well",
      "count": 0
    },
]
}
这个JSON值必须存储在数据库中,如果下次在网站上添加一些东西,我的json也会增加,我的数据库也想添加那个数据,现在没有添加那个数据,只有一次它的获取和显示。
这是我的 Mainactivity.java
@Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_item); 
        mDbHelper=new GinfyDbAdapter(MainActivity.this);
        mDbHelper.open();
         Cursor projectsCursor = mDbHelper.fetchAllProjects();
         if(projectsCursor.getCount()>0)
           {
           fillData(projectsCursor);
           Log.i("filling", "...");
           }
           else
           {
                new GetDataAsyncTask().execute();
           }
        btnGetSelected = (Button) findViewById(R.id.btnget);
        btnGetSelected.setOnClickListener(this);
    }
    private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
        protected void onPreExecute() {
            Dialog.setMessage("Loading.....");
            Dialog.show();
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Dialog.dismiss();
            mDbHelper=new GinfyDbAdapter(MainActivity.this); // initialize mDbHelper before.
            mDbHelper.open();
            Cursor projectsCursor = mDbHelper.fetchAllProjects();
            if(projectsCursor.getCount()>0)
            {
            fillData(projectsCursor);
            }
        }
        @Override
        protected Void doInBackground(Void... params) {
            getData();
            return null;
        }
    }
    public void getData() {
          try
          {
      HttpClient httpclient = new DefaultHttpClient();
      httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      HttpGet request = new HttpGet("http://192.168.1.18:3001/api/v1/posts.json");
      // HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");     
      HttpResponse response = httpclient.execute(request);
      HttpEntity resEntity = response.getEntity();
      String _response=EntityUtils.toString(resEntity); // content will be consume only once
       Log.i("................",_response);
      httpclient.getConnectionManager().shutdown();
      JSONObject jsonObject = new JSONObject(_response);
      JSONArray contacts = jsonObject.getJSONArray("post");//(url);
          for(int i = 0; i < contacts.length(); i++){
              JSONObject c = contacts.getJSONObject(i);
              String id = c.getString("id");
              String title = c.getString("title");
              String  content = c.getString("content");
              String  count = c.getString("count");
              mDbHelper=new GinfyDbAdapter(MainActivity.this);
              mDbHelper.open();
              mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
      }
  } catch (Exception e) {
      e.printStackTrace();
  }
    }
    @SuppressLint("NewApi")
     @SuppressWarnings("deprecation")
       private void fillData(Cursor projectsCursor) {
           //mDbHelper.open();   
           if(projectsCursor!=null)
           {
           String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
           int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
            dataAdapter  = new SimpleCursorAdapter(
             this, R.layout.activity_row, 
             projectsCursor, 
             from, 
             to,
             0);
            setListAdapter(dataAdapter);
           }else
           {
               Log.i("...........","null");
           }
       }
在这里我也提到了我的 dpclass。
private static final String DATABASE_NAME = "test";
    private static final String DATABASE_TABLE_PROJ = "projects";
    private static final int DATABASE_VERSION = 3;
    public static final String CATEGORY_COLUMN_ID = "_id";
    public static final String CATEGORY_COLUMN_TITLE = "title";
    public static final String CATEGORY_COLUMN_CONTENT = "content";
    public static final String CATEGORY_COLUMN_COUNT = "count";
    private static final String TAG = "GinfyDbAdapter";
    private DatabaseHelper mDbHelper;
    private static SQLiteDatabase mDb;
    private final Context mCtx;
    public void saveCategoryRecord(String id, String title, String content, String count) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(CATEGORY_COLUMN_ID, id);
        contentValues.put(CATEGORY_COLUMN_TITLE, title);
        contentValues.put(CATEGORY_COLUMN_CONTENT, content);
        contentValues.put(CATEGORY_COLUMN_COUNT, count);
        mDb.insert(DATABASE_NAME, null, contentValues);
        }
    public Cursor getTimeRecordList() {
        return mDb.rawQuery("select * from " + DATABASE_NAME, null);
        }
    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        private static final String DATABASE_CREATE_PROJ =
                "create table " + DATABASE_TABLE_PROJ + " ("
                + CATEGORY_COLUMN_ID + " integer primary key , "
                + CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String DATABASE_CREATE_PROJ = "CREATE TABLE " +  DATABASE_TABLE_PROJ + "( "
                + CATEGORY_COLUMN_ID + " integer primary key, "
                + CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer   );" ;
                db.execSQL(DATABASE_CREATE_PROJ);     
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_TABLE_PROJ);
        onCreate(db);
    }
}
    public void saveCategoryRecord(Category category) {
         ContentValues values = new ContentValues();
         values.put(CATEGORY_COLUMN_TITLE , category.getTitle());
         values.put(CATEGORY_COLUMN_CONTENT, category.getContent()); 
         values.put(CATEGORY_COLUMN_COUNT, category.getCount());   
         // Inserting Row
         mDb.insert(DATABASE_TABLE_PROJ, null, values);
         mDb.close(); // Closing database connection
    }
    public Cursor fetchAllProjects() {
        // TODO Auto-generated method stub
        return mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID, CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, null, null, null, null, null);
    }
    public GinfyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }
     public GinfyDbAdapter open() throws SQLException {
            mDbHelper = new DatabaseHelper(mCtx);
            mDb = mDbHelper.getWritableDatabase();
            return this;
        }
     public boolean updateProject(long _id, String title, String content, String count) {
            ContentValues args = new ContentValues();
            args.put(CATEGORY_COLUMN_TITLE, title );
            args.put(CATEGORY_COLUMN_CONTENT, content );
            args.put(CATEGORY_COLUMN_COUNT, count );
            return mDb.update(DATABASE_TABLE_PROJ, args, CATEGORY_COLUMN_ID + "=" + _id,  null) > 0;
        }
}
我的问题是:它第一次获取我的 JSON 数据并保存在 db 中,下次启动它时没有获取新添加的 json 数据部分,我希望旧的和新的 JSON 数据应该存储在 db 中。