改造错误:java.lang.NullPointerException:尝试在空对象引用上调用虚方法 [英] Retrofit error: java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference
本文介绍了改造错误:java.lang.NullPointerException:尝试在空对象引用上调用虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个应用程序以允许用户注册和帐户.
I am trying to create an app to allow users to register and account.
我已经多次看到这个问题,但我无法使用相同的解决方案修复我的问题
I have seen this question asked a few times but i wasn't able to fix mine using the same solutions
我收到错误
/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app, PID: 12181
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String okhttp3.ResponseBody.string()' on a null object reference
at com.example.app.MainActivity$1.onResponse(MainActivity.java:75)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I/Process: Sending signal. PID: 12181 SIG: 9
Process 12181 terminated.
我的改造客户端是这个
public class RetrofitClient {
private static final String BASE_URL = "http://123.456.789.101:5000/api/";
private static RetrofitClient mInstance;
private Retrofit retrofit;
private RetrofitClient(){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized RetrofitClient getInstance() {
if (mInstance == null) {
mInstance = new RetrofitClient();
}
return mInstance;
}
public Api getApi(){
return retrofit.create(Api.class);
}
}
API接口是这个
public interface Api {
@FormUrlEncoded
@POST("/users/")
Call<ResponseBody> createUser(
@Field("email") String email,
@Field("password") String password
);
}
主要活动是这个
Call<ResponseBody> call = RetrofitClient
.getInstance()
.getApi()
.createUser(email, password);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String s = response.body().string();
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
响应为空,所以我假设这是 RetrofitClient 的问题,但不确定如何修复
The response is null so i am assuming it is a problem with the RetrofitClient but unsure how to fix
推荐答案
可能你的回复为空,先查一下.
maybe your response is null, first check it.
if(response.body() != null) {
String s = response.body().string();
}
这篇关于改造错误:java.lang.NullPointerException:尝试在空对象引用上调用虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文