I have got a question. Why I have NullPointerException
during getting data from ResponseModel.
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Integer bjd.adrian.retrofitjavapost.ResponseModel.getStatusOfLogin()' on a null object reference
at bjd.adrian.retrofitjavapost.MainActivity$1.onResponse(MainActivity.java:51)
MainActivity:
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view)
{
EditText usernameET = findViewById(R.id.usernameET);
EditText passwordET = findViewById(R.id.passwordET);
String username = usernameET.getText().toString();
String password = passwordET.getText().toString();
final RequestModel requestModel = new RequestModel();
requestModel.setUsername(username);
requestModel.setPassword(password);
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.100.9/androidAppScripts/")
.addConverterFactory(GsonConverterFactory.create())
.build();
WebAPIInterface webAPIInterface = retrofit.create(WebAPIInterface.class);
webAPIInterface.login(requestModel).enqueue(new Callback<ResponseModel>() {
@Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
ResponseModel responseModel = response.body();
Log.v(TAG, "StatusOfLogin = "+responseModel.getStatusOfLogin()+" ID = "+responseModel.getId());
}
@Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Log.e(TAG, t.toString());
}
});
}
RequestModel:
public class RequestModel
{
@SerializedName("username")
private String username;
@SerializedName("password")
private String password;
//getters and setters
}
ResponseModel:
@SerializedName("statusOfLogin")
@Expose
private Integer statusOfLogin;
@SerializedName("id")
@Expose
private Integer id;
I am learning how to use retrofit. Please help me !
答案 0 :(得分:0)
我认为问题在于您的链接如下所示:
http://192.168.100.9/androidAppScripts//retrofitLogin.php
。
这是由于的串联
.baseUrl("http://192.168.100.9/androidAppScripts/")
和
@POST("/retrofitLogin.php")
。
您应删除/
或.baseUrl("http://192.168.100.9/androidAppScripts/")
中的@POST("/retrofitLogin.php")
。
我建议您创建一个常量BASE_URL
并在其中存储http://192.168.100.9/androidAppScripts
,然后使用.baseUrl(BASE_URL)
。