java - 我如何根据 protected String doInBackground 方法中 AsyncTask 的结果调用 Toast.makeText()?

标签 java android android-asynctask

我在 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/

相关文章:

java - Android 可以通过蓝牙支持 Zeroconf/Bonjour 吗? TCP/IP 怎么样?

android - InvoiceTemplateGet 类型未定义方法 execute()

android - 如何从 Android AlarmManager 回调执行网络 Activity

java - 无法在单个函数中迭代两个 while 循环

java - 如何在 Eclipse 中使用 SonarLint

java - 使用 spring mvc 上传 jquery 文件 : 400 bad request

java - 使用 Maven 从头开始​​构建 CAS war

android - 无效的LOC header

android - 在自定义 View 类中播放 GIF

java - Android、java - 无法从 asynctask 更新变量