retrofit2异常:无法启动活动ComponentInfo

时间:2017-08-15 19:17:22

标签: android retrofit retrofit2

您好iam使用retrofit 2下载并解析JSON文件到模型类 在我的代码中,但我给了一堆关于它的例外这里是我的错误相关代码:

Retrofit retrofit = new Retrofit.Builder().baseUrl("http://services.hanselandpetal.com").addConverterFactory(GsonConverterFactory.create())
            .build();

    getFlowers getFlowers = retrofit.create(getFlowers.class);
    Call<Flowers> call = getFlowers.all();

        Response <Flowers> response = call.execute();

这是我的界面

public interface FlowerAPI {
@GET("feeds/flowers.json")
Call<List<Flower>> getAllFlowers();

}

这些是异常堆栈:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uefi.retet/com.example.uefi.retet.MainActivity}: android.os.NetworkOnMainThreadException
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
               Caused by: android.os.NetworkOnMainThreadException
                  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                  at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
                  at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您正在通过调用call.execute()在MainThread上进行网络调用,而不是使用call.enqueue(callback)它在工作线程上执行网络调用,并通过MainThread上的回调回复响应。

了解更多信息:https://square.github.io/retrofit/2.x/retrofit/retrofit2/Call.html