如何 运行 两个片段,每个片段都有自己的 AsyncTasks

How to run two fragments each with their own AsyncTasks

我有一个布局,其中有 2 个选项卡,它们是通过片段实现的,即每个选项卡都有自己的片段。它们是与片段关联的每个布局中的 SwipeRefreshLayout。
还有两个异步任务对 returns JSON 数据的脚本进行 http 调用。
我实现了第一个异步任务并且它工作正常但是当我尝试执行第二个时一个应用程序不断崩溃。 Log cat 没有多大帮助,但这些是我看到的最重要的几行:

 java.lang.RuntimeException: An error occured while executing doInBackground() 

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()


这些错误发生在创建 http 请求时。知道如何解决这个问题吗?

在与 UI 线程不同的线程中,您必须创建一个句柄并为 UI 线程发送一个可运行对象。遵循代码

Handler handler = new Handler (Looper.getMainLooper());
handler.post (new Runnable () {
     @Override
     public void run () {
         // ... Update view
     }
});