改进运行时错误

时间:2015-08-04 18:29:58

标签: java android android-studio retrofit

我的改装代码出错了。我想我错过了一些东西或者没有理解某些东西(考虑到我今天已经开始编码并且在一周前就在android中进行了编码。)这是我的完整错误(在运行时的android studio中):



08-04 09:24:11.230  16349-16349/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.apurva.myapplication, PID: 16349
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.apurva.myapplication/com.example.apurva.myapplication.MainActivity}: retrofit.RetrofitError
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: retrofit.RetrofitError
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:400)
            at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
            at $Proxy0.me(Native Method)
            at com.example.apurva.myapplication.MainActivity.onCreate(MainActivity.java:19)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getAllByName(InetAddress.java:214)
            at com.squareup.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
            at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:266)
            at com.squareup.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:240)
            at com.squareup.okhttp.internal.http.RouteSelector.nextUnconnected(RouteSelector.java:156)
            at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:130)
            at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:312)
            at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:235)
            at com.squareup.okhttp.Call.getResponse(Call.java:262)
            at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:219)
            at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:192)
            at com.squareup.okhttp.Call.execute(Call.java:79)
            at retrofit.client.OkClient.execute(OkClient.java:53)
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:326)
            at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
            at $Proxy0.me(Native Method)
            at com.example.apurva.myapplication.MainActivity.onCreate(MainActivity.java:19)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)




我的android项目中的文件:

MainActivity.java



package com.example.apurva.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;



public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UserService userService;
        String token = "A";
        userService = ServiceGenerator.createService(UserService.class, UserService.BASE_URL, token);
        User user = userService.me();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}




ServiceGenerator.java



package com.example.apurva.myapplication;


import com.squareup.okhttp.OkHttpClient;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;

/**
 * Created by apurva on 4/8/15.
 */
public class ServiceGenerator {
    private ServiceGenerator() {
    }

    public static <S> S createService(Class<S> serviceClass, String baseUrl, final String token) {
        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(baseUrl)
                .setClient(new OkClient(new OkHttpClient()));

        if (token != null) {
            builder.setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Authorization", token);
                }
            });
        }

        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass);
    }
}
&#13;
&#13;
&#13;

UserService.java

&#13;
&#13;
package com.example.apurva.myapplication;

import com.squareup.okhttp.OkHttpClient;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.http.POST;

/**
 * Created by apurva on 4/8/15.
 */
public interface UserService {

        public static final String BASE_URL = "http://localhost:8000/auth";

        @POST("/convert-token")
        User me();

}
&#13;
&#13;
&#13;

非常感谢您的帮助,错误是运行时,我在构建或运行应用程序时没有任何问题。提前致谢

1 个答案:

答案 0 :(得分:1)

您获得的例外不言自明:NetworkOnMainThreadException。即您的代码在主线程中进行网络调用。例外情况也说明了它的确切位置:在MainActivity的19行代码中:

User user = userService.me();

如果您阅读Retrofit documentation,您必须知道当您调用服务方法时Retrofit将同步,即在同一个线程,并且在您的情况下,这是主线程。

要异步拨打电话,您需要传递Callback

@POST("/convert-token")
void me(Callback<User> cb);

PS我强烈建议您首先阅读Java,因为基本上您没有认识到错误的位置,这是软件开发的基本技能。