为什么吐司没有在asynctask中显示?

时间:2018-03-08 14:12:43

标签: android

我是android的初学者,并试图在异步任务中显示吐司,为此我写了这段代码:

if (k+1) != length:
    x = k+1
    while x < len(list1):
        temp1 = list1[x]
        temp2 = final[k]
        if temp1 % temp2 == 0:
            del list1[x]
        x += 1
    k += 1
else:
    break


当我尝试使用此代码调用该异步任务时:

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


在完成GetReading reading=new GetReading(); List<ReadingModel> result= reading.Get("VQ",LineActivity.this); 祝酒后,我想首先向用户展示吐司,会发生什么?我该如何解决这个问题?谢谢大家。

2 个答案:

答案 0 :(得分:1)

Toast以及与UI有关的任何内容都无法从后台运行的任何线程触发。

将展示吐司的代码移至onProgressUpdateonPostExecute

答案 1 :(得分:0)

因为您使用<{p>}中的.get(),所有问题都会出现

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

永远不要使用.get(),因为它会杀死你的任务的异性。

相反:在onPostExecute()

中执行您想要对结果执行的操作