问题描述
我在AsyncTask中从数据库中获取了数据,如果为空,我想举杯警告文本.我在AsyncTask中尝试过,但我了解到它没有在工作线程中调用.这是我的doInBackground方法:
I fetched data from the database in AsyncTask and if it is null, I want to Toast a warning text. I tried in AsyncTask but i learned that it isn't called in a worker thread. Here is my doInBackground method:
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;
}
我取消了任务,并在代码中创建了一个新的意图.你不在乎他们.您会看到Toast.makeText ..行,我这样尝试过,但它当然会给出错误.我怎样才能做到这一点?如果未在AsyncTask中调用它,该如何调用?
I canceled the task and create a new intent in my code. You don't care them. You see Toast.makeText.. line, I tried like this one of course it gives error. How can i do this? If it isn't called in AsyncTask, how should i call?
推荐答案
doInbackground
在后台线程上调用.因此,您无法在ui线程以外的其他线程上更新ui.
doInbackground
is invoked on a background thread. So you cannot update ui on a different thread other than the ui thread.
您可以根据onPostExecute
中的结果更新ui在doInbackground
中返回结果,或者使用runOnUithread
作为活动类的方法.
You can return the result in doInbackground
Based on the result update ui in onPostExecute
or use runOnUithread
which is a method of activity class.
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
.另外,当您仍有代码要运行时,您也不想取消asynctask运行
As suggested by @codeMagic move you startActivity also to onPostExecute
. Also you do not want to cancel the asynctask run when you still have code to run
这篇关于如何在受保护的字符串doInBackground方法中根据AsyncTask的结果调用Toast.makeText()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!