0

I am new to Retrofit. Whenever i am trying to sign up using android phone it is giving an error: java.lang.NullPointerException: Attempt to invoke response.body.getMessage() and response.body.getError().

It is working in localhost, but not in live server. I can also login but can't sign up. I am following this tutorial = https://www.simplifiedcoding.net/retrofit-android-tutorial/

Please help me!

Here is the code i am getting error:

            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));
            }
        }

Here is 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;
}

Thanks! code screen

Here is my index.php file

    $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));
}

});

Here is 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 function for registering user

     //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;
}

Complete SignUp java code:

    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);

2 Answers2

1

I faced same issue when I get response from php web server. In my case, the server response was not correct. Server response type has to equal with Android one.

In your case, there are 3 members - Boolean error, String message and User user. Maybe, the User class format seems not equal with server response.

//////Please try this/////

    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));
        }
    }
Wencheng Li
  • 126
  • 6
0

change if statment to :

if (response.body()!=null) {
                //starting profile activity
                finish();
                SharedPrefManager.getInstance(getApplicationContext()).userLogin(response.body().getUser());
                startActivity(new Intent(getApplicationContext(), HomeActivity.class));
            }

because if status code != 200 the body return null

Mohammad Sommakia
  • 1,773
  • 3
  • 15
  • 48
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/194980/discussion-on-answer-by-mohammad-sommakia-java-lang-nullpointerexception-attemp). – Samuel Liew Jun 15 '19 at 09:00