我在 AsyncTask 中从数据库中获取数据,如果它为空,我想 Toast 一个警告文本。我在 AsyncTask 中尝试过,但我了解到它不是在工作线程中调用的。这是我的 doInBackground 方法:
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet( "http://191.162.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");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
if ( result == null ) {
// Toast.makeText(getApplicationContext(), "You entered wrong values.", Toast.LENGTH_LONG).show();
asyncTask.cancel(true);
Intent inte=new Intent(MainActivity.this, MainActivity.class);
inte.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
inte.addCategory(Intent.CATEGORY_HOME);
startActivity(inte);
}
}
catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
我取消了任务并在我的代码中创建了一个新的 Intent 。你不关心他们。你看到了 Toast.makeText.. 行,我试过这样的,当然它会出错。我怎样才能做到这一点?如果在 AsyncTask 中没有调用,我应该如何调用?
最佳答案
doInbackground
在后台线程上调用。因此,您不能在 ui 线程以外的其他线程上更新 ui。
可以在doInbackground
中返回结果,在onPostExecute
中根据结果更新ui,或者使用runOnUithread
,这是Activity类的一个方法。
runOnUiThread(new Runnable() {
@Override
public void run() {
// toast here
}
});
或者
protected String doInBackground(Boolean... params) {
// other code
return "status"
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),"My status is"+result,Toast.LENGTH_SHORT).show();
}
编辑
正如@codeMagic 所建议的那样,将 startActivity 也移动到 onPostExecute
。此外,您不想在仍有代码要运行时取消异步任务运行
关于java - 我如何根据 protected String doInBackground 方法中 AsyncTask 的结果调用 Toast.makeText()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19297666/