如何在不重新启动活动的情况下更新SQLite数据库?

时间:2013-09-08 22:46:04

标签: java android json sqlite

我有一个应用程序,一开始从云端检索数据,以更新用户手机中的数据库。我使用AsyncTask在下载数据时显示ProgressDialog。问题是在下载数据后,只有在对话框消失后重新启动活动时,数据库才会更新。这有点难看,我想知道是否有更好的方法。

这是AsyncTask:

 class GetVersion extends AsyncTask<String, String, String> {

      @Override
      protected void onPreExecute() {
          super.onPreExecute();
          pDialog = new ProgressDialog(ListClubs.this);
          pDialog.setMessage(getString(R.string.updating));
          pDialog.setIndeterminate(false);
          pDialog.setCancelable(false);
          pDialog.show();       
      }

    /**
     * Getting product details in background thread
     * */
    protected String doInBackground(String... params) {
       HttpClient httpclient = new DefaultHttpClient();
       HttpPost updateCond = new HttpPost("http://website.com/update_db.php");
        //update database
         List<NameValuePair> nameValuePairs2 = new ArrayList<NameValuePair>();
         nameValuePairs2.add(new BasicNameValuePair("version", Integer.toString(newVersion)));
         try {

                    updateCond.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
                    HttpResponse response2 = httpclient.execute(updateCond);
                    String jsonResult2 = inputStreamToString(response2.getEntity().getContent()).toString();
                    //saving the JSONObject
                    JSONObject object2 = new JSONObject(jsonResult2);
                    JSONArray conditions = object2.getJSONArray("conditions");
                    //saving the version
                      for(int i = 0; i < conditions.length(); i++){
                        JSONObject c = conditions.getJSONObject(i);

                        int condId = c.getInt("id");
                        String condMon = c.getString("mon");

                        db.updateCond(condId, condMon);              

                  }
                    loginPrefsEditor.putBoolean("condBool", true); 
                    loginPrefsEditor.commit();      
                    Log.i("Update old version", Integer.toString(loginPreferences.getInt("oldV", -1)));

        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details

        pDialog.dismiss(); 
        restartActivity();

}    } 

这是updateCond的代码:

public int updateCond(int id, String newCond) {
       SQLiteDatabase db = this.getWritableDatabase();

       ContentValues values = new ContentValues();

       values.put(KEY_COND, newCond);

       // updating row
       return db.update(TABLE_COND, values, KEY_ID+"="+id,null );
   } 

1 个答案:

答案 0 :(得分:0)

尝试在onPostExecute中进行数据库更新。在doInbackground,您返回JSONObject而不是String,并在onPostExecute中处理此JSONObject并更新数据库。

相关问题