-1

I'm beginner in android and trying to show toast in the async task, for that purpose I wrote this code:

public class GetReading {
    public GetReading() {
    }

    public List<ReadingModel> Get(String TokenKey, Context adapter) throws ExecutionException, InterruptedException {
        GetReadingTask params = new GetReadingTask(TokenKey, adapter);
        List List_result = (List)(new GetReading.AsyncRead()).execute(new GetReadingTask[]{params}).get();
        return List_result;
    }

    private class AsyncRead extends AsyncTask<GetReadingTask, Void, List<ReadingModel>> {
        ir.behineh.wepapiinterface.GETREADINGINTERFACE.ReadingModel.List x;

        private AsyncRead() {
        }

        protected List<ReadingModel> doInBackground(GetReadingTask... getReadingTasks) {
            final Context pos = getReadingTasks[0].adapter;
            Handler handler = new Handler(pos.getMainLooper());
            handler.post(new Runnable() {
                public void run() {
                    Toast.makeText(pos, "Created a server socket", 1).show();
                }
            });
            ir.behineh.wepapiinterface.GETREADINGINTERFACE.GetReading taskService = (ir.behineh.wepapiinterface.GETREADINGINTERFACE.GetReading)ServiceGenerator.createService(ir.behineh.wepapiinterface.GETREADINGINTERFACE.GetReading.class);
            Call tasks = taskService.getReadings("application/x-www-form-urlencoded", "application/json", "bearer " + getReadingTasks[0].TokenKey);

            try {
                this.x = (ir.behineh.wepapiinterface.GETREADINGINTERFACE.ReadingModel.List)tasks.execute().body();
            } catch (IOException var7) {
                var7.printStackTrace();
            }

            return this.x;
        }
    }
}


and when i try to call that async task with this code:

GetReading reading=new GetReading();
        List<ReadingModel> result= reading.Get("VQ",LineActivity.this);


after finishing doinbackground get the toast, but i want to show toast first to user, what happen? how can i solve that problem? thanks all.

Arnab
  • 4,216
  • 2
  • 28
  • 50
  • Possible duplicate of [How do we use runOnUiThread in Android?](https://stackoverflow.com/questions/11140285/how-do-we-use-runonuithread-in-android) – Lance Toth Mar 08 '18 at 14:15

2 Answers2

1

Toasts as well as anything that has to do with the UI cannot be fired from any thread that runs in the background.

Move your code for displaying the toast to either onProgressUpdate or on onPostExecute.

0

All your troubles arise because you use the .get() in

execute(new GetReadingTask[]{params}).get();

Never use .get() as it kills the asynchonity of your task.

Instead: do the things you want to do with the result in onPostExecute().

greenapps
  • 11,154
  • 2
  • 16
  • 19