如何在Android Java中使用Retrofit获取用户ID。

huangapple go评论54阅读模式
英文:

how to get user id with retrofit in android java

问题

I am confused about how to get the UserId in Android with Retrofit. When I use getUserId(), it shows an error: "Incompatible types. Found: 'void', required: 'java.lang.Integer'. How can I solve this and make the app work?

Here is your translated code:

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

Your LoginRequest class:

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

Your ApiClient class:

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

Your MainActivity class:

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

Please make sure to import the necessary classes and dependencies as needed in your Android project.

英文:

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: &#39;void&#39;, required: &#39;java.lang.Integer&#39;, 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&lt;LoginResponse&gt; loginResponseCall = ApiClient.getService().PersonEyeGet(id);
loginResponseCall.enqueue(new Callback&lt;LoginResponse&gt;() {
@Override
public void onResponse(Call&lt;LoginResponse&gt; call, Response&lt;LoginResponse&gt; response) {
if(response.isSuccessful()) {
LoginResponse loginResponse = response.body();
}
else
{
String message = &quot;No User Found&quot;;
Toast.makeText(Visitor.this, message, Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call&lt;LoginResponse&gt; call, Throwable t) {
String message = &quot;User Data Missing&quot;;
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(&quot;http://XXX.XX.XXX.X/webapi/&quot;)
.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 = &quot;Please Insert Username and Password&quot;;
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&lt;LoginResponse&gt; loginResponseCall = ApiClient.getService().loginUser(edUsername.getText().toString(), edPassword.getText().toString());
loginResponseCall.enqueue(new Callback&lt;LoginResponse&gt;() {
@Override
public void onResponse(Call&lt;LoginResponse&gt; call, Response&lt;LoginResponse&gt; response) {
if(response.isSuccessful()) {
LoginResponse loginResponse = response.body();
startActivity(new Intent(MainActivity.this, MainMenu.class));
finish();
} else {
String message = &quot;No User Found&quot;;
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call&lt;LoginResponse&gt; call, Throwable t) {
String message = &quot;Incorrect Username or Password&quot;;
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
});
}
}

答案1

得分: 0

问题似乎出在这一行:id = loginRequest.setUserId(loginRequest.getUserId());

在这里,你通过setUserId方法设置了userId,所以这个方法的返回类型肯定是void,但你正在尝试使用setUserId初始化一个int类型的变量id,而setUserId的返回类型是void,所以这是不可能的,因为它不返回int值。

要初始化id变量,你需要获取存储userId的地方。不幸的是,从你的代码中,我无法确定你在哪里存储userId。

英文:

Issue looks like at this line id = loginRequest.setUserId(loginRequest.getUserId());

here you are setting userId by setUserId method so definitely this method return type is void and you are trying to initialise id variable type of int using setUserId whose return type is void so that's not possible as it is not returning int value

To initialise id variable , you need to fetch userid where you are storing . Unfortunately from your code , I am not getting where you storing userId

答案2

得分: 0

根据@jayesh gurudayalani指出的问题,问题似乎是由以下一行代码引起的:

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

这行代码存在许多问题。首先,你正在初始化LoginRequest LoginRequest loginRequest = new LoginRequest(),并在接下来的代码中立即尝试获取userId。最初,userId将为0(因为它是一个全局变量)。因此,getUserId()方法返回0,而setUserId()方法将x设置为userId。最终,尽管执行了所有这些操作,userId的值仍然是x。再次强调,setUserId方法返回void。因此,在这些操作完成后,该行代码看起来像这样:id = void。由于id是一个整数,你不能将void赋给它。

我认为你应该这样写:

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

然而,一个更合逻辑的方法是在这里不设置id。

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

而是,在onResponse中使用响应中发送的id来设置id:

if(response.isSuccessful()) {
    LoginResponse loginResponse = response.body();
    // 假设loginResponse有一个名为getUserId的方法
    id = loginResponse.getUserId();
    loginRequest.setUserId(id);
}
英文:

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

huangapple
  • 本文由 发表于 2023年5月15日 11:20:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定