Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i call Toast.makeText() according to result of AsyncTask in protected String doInBackground method?

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;
    }

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?

like image 890
elfoz Avatar asked Jan 16 '26 21:01

elfoz


1 Answers

doInbackground is invoked on a background thread. So you cannot update ui on a different thread other than the ui thread.

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
                    }
                });

Or

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(); 
}

Edit

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

like image 160
Raghunandan Avatar answered Jan 19 '26 18:01

Raghunandan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!