将转换响应转换为字符串时出现NullPointerException?

时间:2016-08-29 07:19:48

标签: android string post retrofit

这是我的改装课程

public class ApiClient {
public static final String BASE_URL = AppConstants.BASE_URL;
private static Retrofit retrofit = null;


public static Retrofit getClient() {
    if (retrofit == null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

public interface RegisterAPI {
    @POST(AppConstants.LOGIN_PAGE)
    Call<JSONObject> getLogin(@Body JSONObject loginParams);
}
}

这是改装请求

JSONObject loginParams = ((MainActivity) getActivity()).requestParams.getLoginParams(etUserName.getText().toString(), etPassword.getText().toString());
            ApiClient.RegisterAPI apiService =
                    ApiClient.getClient().create(ApiClient.RegisterAPI.class);


            Call<JSONObject> call = apiService.getLogin(loginParams);
            call.enqueue(new Callback<JSONObject>() {
                @Override
                public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                    Log.e("response", response.body().toString());
                }

                @Override
                public void onFailure(Call<JSONObject> call, Throwable t) {

                }
            });

将响应转换为字符串时,我得到空指针

java.lang.NullPointerException
at com.vfirst.ifbagro.login.LoginFragment$1.onResponse(LoginFragment.java:96)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:730)
 at android.os.Handler.dispatchMessage(Handler.java:92)
 at android.os.Looper.loop(Looper.java:137)
 at android.app.ActivityThread.main(ActivityThread.java:5214)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:525)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
 at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

尝试仅记录response.body()以首先查看它是否为空。

如果您使用的是OkHttpClient,则可以添加拦截器并记录响应,这可以保证正常工作:

public Response intercept(Chain chain) throws IOException {
    Request.Builder builder = chain.request().newBuilder();
    // Add custom headers etc with builder
    ....
    Request request = builder.build();
    Response response = chain.proceed(request);
    String body = response.body().string()
    ....

答案 1 :(得分:0)

试试这个

BufferedReader reader = null;
String output = "";

    try {
        reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
        output = reader.readLine();
    } catch (IOException e) {
            e.printStackTrace();
    }
    Toast.makeText(getActivity(), output, Toast.LENGTH_LONG).show();