我的Android應用程序有一個AsyncTask
從我的服務器獲取數據。當我從數據庫中拉出幾行時,它的速度非常快,我不需要在獲取新數據時加載動畫。如何在AsyncTask中顯示ProgressDialog?
當我拉從數據庫2,3k行,可能會慢下來,所以我決定用一些指標(加載動畫),這樣,用戶就知道數據在後臺收集。我得到了一個活動Fill_in_phone
,我撥打asyncTask
,名稱爲GetOcitanja
。
我對AsynTask
代碼:
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class GetOcitanja extends AsyncTask<Object, Void, String> {
Activity _context;
String _str_mesg;
String _str_naslov;
public ProgressDialog progress;
public GetOcitanja(Activity context, String str_naslov, String str_message){
this._context = context;
this._str_naslov = str_naslov;
this._str_mesg = str_message;
}
@Override
protected void onPreExecute() {
//super.onPreExecute();
progress = ProgressDialog.show(_context, _str_naslov,
_str_mesg, true);
progress.show();
}
@Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
progress.dismiss();
}
@Override
protected String doInBackground(Object... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(Config.url_get_ocitanja_async_taks);
String odg="";
try {
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
odg = EntityUtils.toString(entity, HTTP.UTF_8);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return odg;
}
正如你所看到的,我把2秒睡眠時間來模擬一個大的數據集。我把這種AsyncTask
在我Fill_in_Data
活動:
GetOcitanja asyncTask=new GetOcitanja(Fill_in_phone.this, "a","b");
asyncTask.execute();
String response="";
try {
response= asyncTask.get();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
}
我跟着幾個解決方案,從SO和沒有任何幫助。我做錯了什麼?
http://stackoverflow.com/a/9814882/5202007 – Tauqir
遵循這些例子,沒有任何幫助。我應該用線程替換AsyncTask嗎? – KuKeC
'我在這裏調用asyncTask GetOcitanja'。請完整顯示你是如何做到的。 – greenapps