gpt4 book ai didi

android - 如何取消处于运行状态的AsyncTask。

转载 作者:行者123 更新时间:2023-11-29 18:04:52 24 4
gpt4 key购买 nike

我想在json请求带有空值时取消AsyncTask,并显示 Toast 消息。

private class PostTask extends AsyncTask<String, Integer, String>
{
//Before running code in the separate thread
@Override
protected void onPreExecute()
{

progressDialog = new ProgressDialog(login.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("please wait...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
//The code to be executed in a background thread.
@Override
protected String doInBackground(String... params)
{
String url=params[0];
Parser parse = new Parser();
try{
String email = textinput.getText().toString();
String pass = password.getText().toString();
JSONObject JsonString = parse.getJSONFromUrl(url,email,pass);

//String email = JsonString.getString("email");
Constants.ID = JsonString.getString("id");

}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (NullPointerException e){

publishProgress(1);
//Toast.makeText(login.this, "Invalid credentials", Toast.LENGTH_LONG).show();
}
return "All Done!";
}
//Update the progress
@Override
protected void onProgressUpdate(Integer... values)
{
//set the current progress of the progress dialog
// progressDialog.setProgress(values[0]);
//Toast.makeText(login.this, "Invalid credentials", Toast.LENGTH_LONG).show();
}
//after executing the code in the thread
@Override
protected void onPostExecute(String result) {

super.onPostExecute(result);
startActivity(new Intent("com.example.mysampleapp.DASHBOARDTAB"));
progressDialog.dismiss();
}
}

如果我在 JSON 请求中得到 null 并在我调用 的同一 Activity 中显示消息,是否有任何取消方法可以取消 async 任务>异步任务?

最佳答案

如果 JSON 为空,则尝试返回错误代码,例如:

   catch (NullPointerException e){

publishProgress(1);
return "Error";
}

然后在 onPostExecute() 中:

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

if(result.equals("Error")) {
//Error
} else {
startActivity(new Intent("com.example.mysampleapp.DASHBOARDTAB"));
progressDialog.dismiss();
}
}

关于android - 如何取消处于运行状态的AsyncTask。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13952200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com