Search code examples
androidretrofit

how to get user id with retrofit in android java


I am confuse to get UserId in android with retrofit, I have tried to get UserId into a Integer when I used getUserId(). It show an error Incompatible types. Found: 'void', required: 'java.lang.Integer', How do I solve it and make the app work?

MyCode:

Integer id;

LoginRequest loginRequest = new LoginRequest();
        id = loginRequest.setUserId(loginRequest.getUserId());
        IdGet(loginRequest);

public void IdGet(LoginRequest loginRequest)
    {
        Call<LoginResponse> loginResponseCall = ApiClient.getService().PersonEyeGet(id);
        loginResponseCall.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if(response.isSuccessful()) {
                    LoginResponse loginResponse = response.body();
                }
                else
                {
                    String message = "No User Found";
                    Toast.makeText(Visitor.this, message, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                String message = "User Data Missing";
                Toast.makeText(Visitor.this, message, Toast.LENGTH_LONG).show();
            }
        });
    }

How do I solve it and make the app work?

Added Information:

public class LoginRequest {

    public int UserId;
    private String username;
    private String password;

    public int getUserId() {
        return UserId;
    }

    public void setUserId(int userId) {
        UserId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
public class ApiClient {
    public static Retrofit getRetrofit() {

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();


        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://XXX.XX.XXX.X/webapi/")
                .client(okHttpClient)
                .build();

        return retrofit;
    }

    public static UserService getService() {
        UserService userService = getRetrofit().create(UserService.class);

        return userService;
    }
}
public class MainActivity extends AppCompatActivity {

    Button btnLogin;
    EditText edUsername, edPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnLogin = findViewById(R.id.btnLogin);
        edUsername = findViewById(R.id.etUsername);
        edPassword = findViewById(R.id.etPassword);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(edUsername.getText().toString()) || TextUtils.isEmpty(edPassword.getText().toString())) {
                    String message = "Please Insert Username and Password";
                    Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
                } else {
                    LoginRequest loginRequest = new LoginRequest();
                    loginRequest.setUsername(edUsername.getText().toString());
                    loginRequest.setPassword(edPassword.getText().toString());
                    loginUser(loginRequest);
                }
            }
        });
    }

    public void loginUser(LoginRequest loginRequest) {
        Call<LoginResponse> loginResponseCall = ApiClient.getService().loginUser(edUsername.getText().toString(), edPassword.getText().toString());
        loginResponseCall.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if(response.isSuccessful()) {
                    LoginResponse loginResponse = response.body();
                    startActivity(new Intent(MainActivity.this, MainMenu.class));
                    finish();
                } else {
                    String message = "No User Found";
                    Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                String message = "Incorrect Username or Password";
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
            }
        });
    }
}

Solution

  • As pointed out by @jayesh gurudayalani, the issue seems to be cause by the following line:

    id = loginRequest.setUserId(loginRequest.getUserId());
    

    This line has many problems. At first, you are initializing LoginRequest LoginRequest loginRequest = new LoginRequest() and immediately trying to get userId in the following line. Initially, the userId will be 0 (since it's a global variable). So, the getUserId() method returns 0, and the setUserId() method sets x as userId. Ultimately, the value of userId remains x even after all these operations. Again, the setUserId method returns void. And so after these operations are complete, the line looks like this: id = void. Since id is an integer, you cannot assign void to it.

    I think you should've written it like this:

    LoginRequest loginRequest = new LoginRequest();
    id = loginRequest.getUserId();
    loginRequest.setUserId(id);
    IdGet(loginRequest);
    

    However, a more logical approach would be not setting the id here.

    LoginRequest loginRequest = new LoginRequest();
    //id = loginRequest.getUserId();
    //loginRequest.setUserId(id);
    IdGet(loginRequest);
    

    Instead, set the id sent by response in onResponse:

    if(response.isSuccessful()) {
        LoginResponse loginResponse = response.body();
        // assuming that loginResponse has a method named getUserId
        id = loginResponse.getUserId();
        loginRequest.setUserId(id);
    }