如果我的結果字符串爲空,我想取消asyncTask。 (我在登錄活動中從用戶那裏獲得用戶名和密碼,如果數據庫中不存在該用戶名和密碼,則asyncTask必須取消並準備開始相同的任務。)我閱讀並應用了一些內容,但他們沒有不會跑。這是我的AsyncTask:如果取數據的結果爲空,如何停止AsyncTask?
class ProductConnect extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
@Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://191.165.2.235/getProducts.php?login=1&user_name="+UserName+"&user_pass="+Password);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
if(reader.readLine() == null){
asyncTask.cancel(true);
}
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
if (isCancelled()) break;
}
result = sb.toString();
Log.d("test", result);
}
catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
@Override
protected void onPostExecute(String result) {
Intent passValue=new Intent(MainActivity.this, second.class);
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
names.add(t);
latitude=json_data.getString("lat");
lats.add(latitude);
longtitude=json_data.getString("lon");
longts.add(longtitude);
}
passValue.putStringArrayListExtra("latitudes", (ArrayList<String>) lats);
passValue.putStringArrayListExtra("veri", (ArrayList<String>) names);
passValue.putStringArrayListExtra("longtitudes", (ArrayList<String>) longts);
startActivity(passValue);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Lütfen Bekleyiniz");
pd.setMessage("Authenticating..");
pd.show();
}
}
我應該如何遵循一種方式?我應該使用哪些方法?
http://stackoverflow.com/questions/16538714/stop-asynctask-doinbackground-method/16538887。檢查這個 – Raghunandan
我試過這樣的解決方案,但它不運行或我忽略了一些東西。 – elfoz