我是Retrofit的新手。每当我尝试使用Android手机进行注册时,都会出现错误:java.lang.NullPointerException: Attempt to invoke response.body.getMessage()
和response.body.getError()
。
它在localhost中工作,但不在实时服务器中工作。我也可以登录但无法注册。我正在按照本教程= https://www.simplifiedcoding.net/retrofit-android-tutorial/
请帮助我!
这是我遇到错误的代码:
call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
//hiding progress dialog
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), response.body().getMessage(), Toast.LENGTH_LONG).show();
//if there is no error
if (!response.body().getError()) {
//starting profile activity
finish();
SharedPrefManager.getInstance(getApplicationContext()).userLogin(response.body().getUser());
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
}
}
这是 Result.java
public class Result {
@SerializedName("error")
private boolean error;
@SerializedName("message")
private String message;
@SerializedName("user")
private User user;
public Result(boolean error, String message, User user) {
this.error = error;
this.message = message;
this.user = user;
}
public boolean getError() {
return error;
}
public String getMessage() {
return message;
}
public User getUser() {
return user;
}
谢谢! code screen
这是我的index.php文件
$app->post('/register', function (Request $request, Response $response) {
if (isTheseParametersAvailable(array('name', 'email', 'password', 'address', 'phone'))) {
$requestData = $request->getParsedBody();
$name = $requestData['name'];
$email = $requestData['email'];
$password = $requestData['password'];
$address = $requestData['address'];
$phone = $requestData['phone'];
$db = new DbOperation();
$responseData = array();
$result = $db->registerUser($name, $email, $password, $address, $phone);
if ($result == USER_CREATED) {
$responseData['error'] = false;
$responseData['message'] = 'Registered successfully';
$responseData['user'] = $db->getUserByEmail($email);
} elseif ($result == USER_CREATION_FAILED) {
$responseData['error'] = true;
$responseData['message'] = 'Some error occurred';
} elseif ($result == USER_EXIST) {
$responseData['error'] = true;
$responseData['message'] = 'This email already exist, please login';
}
$response->getBody()->write(json_encode($responseData));
}
});
这里是 User.java
public class User {
private int id;
private String name;
private String email;
private String password;
private String address;
private String phone;
public User(String name, String email, String password, String address, String phone) {
this.name = name;
this.email = email;
this.password = password;
this.address = address;
this.phone = phone;
}
public User(int id, String name, String email, String address, String phone){
this.id = id;
this.name = name;
this.email = email;
this.address = address;
this.phone = phone;
}
public User(int id, String name, String email, String password, String address, String phone) {
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.address = address;
this.phone = phone;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPassword(){
return password;
}
public String getAddress() {
return address;
}
public String getPhone() {
return phone;
}
}
DbOperation.php 用于注册用户的功能
//Method to create a new user
function registerUser($name, $email, $pass, $address, $phone)
{
if (!$this->isUserExist($email)) {
$password = md5($pass);
$stmt = $this->con->prepare("INSERT INTO users (name, email, password, address, phone) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $name, $email, $password, $address, $phone);
if ($stmt->execute())
return USER_CREATED;
return USER_CREATION_FAILED;
}
return USER_EXIST;
}
完整的注册Java代码:
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonSignUp;
private EditText editTextName, editTextEmail, editTextPassword, editTextAddress, editTextPhone;
public static final String TAG = "ins";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
buttonSignUp = (Button) findViewById(R.id.buttonSignUp);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextAddress = (EditText) findViewById(R.id.editTextAddress);
editTextPhone = (EditText) findViewById(R.id.editTextPhone);
buttonSignUp.setOnClickListener(this);
}
private void userSignUp() {
//defining a progress dialog to show while signing up
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Signing Up...");
progressDialog.show();
String name = editTextName.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
String phone = editTextPhone.getText().toString().trim();
//building retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIUrl.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
//Defining retrofit api service
APIService service = retrofit.create(APIService.class);
//Defining the user object as we need to pass it with the call
User user = new User(name, email, password, address, phone);
//defining the call
Call<Result> call = service.createUser(
user.getName(),
user.getEmail(),
user.getPassword(),
user.getAddress(),
user.getPhone()
);
//calling the api
call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
//hiding progress dialog
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), response.body().getMessage(), Toast.LENGTH_LONG).show();
//if there is no error
if (!response.body().getError()) {
//starting profile activity
finish();
SharedPrefManager.getInstance(getApplicationContext()).userLogin(response.body().getUser());
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
}
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onClick(View view) {
if (view == buttonSignUp) {
userSignUp();
}
}
EndPoint
@Headers("Content-Type: application/json")
//The register call
@FormUrlEncoded
@POST("/service/people/register")
Call<Result> registerUser(
@Field("name") String name,
@Field("email") String email,
@Field("password") String password,
@Field("address") String address,
@Field("phone") String phone);
答案 0 :(得分:1)
从php
Web服务器得到响应时,我遇到了同样的问题。
就我而言,服务器响应是不正确的。
服务器响应类型必须等于Android
一。
在您的情况下,有3个成员-Boolean
错误,String
消息和User
用户。
也许User
类格式与服务器响应不相等。
///////请尝试此/////
public void onResponse(Call<Result> call, Response<Result> response) {
//hiding progress dialog
progressDialog.dismiss();
//if there is no error
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), response.body().getMessage(), Toast.LENGTH_LONG).show();
//starting profile activity
finish();
SharedPrefManager.getInstance(getApplicationContext()).userLogin(response.body().getUser());
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
}
}
答案 1 :(得分:0)
如果声明更改为:
if (response.body()!=null) {
//starting profile activity
finish();
SharedPrefManager.getInstance(getApplicationContext()).userLogin(response.body().getUser());
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
}
因为如果状态代码!= 200,则正文返回null