我有一个应用程序,一开始从云中检索数据以更新用户手机中的数据库。我使用 AsyncTask 在下载数据时显示 ProgressDialog。问题是,下载数据后,只有在对话框消失后我重新启动活动时,数据库才会更新。这有点难看,我想知道是否有更好的方法来做到这一点。
这是异步任务:
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 );
}