我正在努力为我的登录屏幕设计正确的设置。我想我需要将其更改为从视图模型调用的asynctask,但不确定这是否是正确的方法。当前代码将结果对象传回视图模型,但由于异步网络请求,它传回一个空对象。最好的方法是什么?
我的代码是这样的:
视图模型:
public void login(String username, String password) {
// can be launched in a separate asynchronous job
Result<LoggedInUser> result = loginRepository.login(username, password);
if (result instanceof Result.Success) {
LoggedInUser data = ((Result.Success<LoggedInUser>) result).getData();
loginResult.setValue(new LoginResult(new LoggedInUserView(data.getEmail(),data.getOrganisation(),data.getFirstname(),data.getLastname(),data.getOrganisationshort())));
} else {
loginResult.setValue(new LoginResult(R.string.login_failed));
}
}
存储库:
public Result<LoggedInUser> login(String username, String password) {
Result<LoggedInUser> result = dataSource.login(username, password);
if (result instanceof Result.Success) {
setLoggedInUser(((Result.Success<LoggedInUser>) result).getData());
}
return result;
}
数据源:
public Result<LoggedInUser> login(String username, String password) {
Log.d("LOGIN_ATTEMPTS", "Connecting...");
final LoggedInUser[] data = new LoggedInUser[1];
try {
LoggedOutUser loggedOutUser = new LoggedOutUser(username,password);
// TODO: handle loggedInUser authentication
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://192.168.0.239:3622/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<LoggedInUser> callAsync = jsonPlaceHolderApi.postAuth(loggedOutUser);
callAsync.enqueue(new Callback<LoggedInUser>() {
@Override
public void onResponse(Call<LoggedInUser> call, Response<LoggedInUser> response) {
if (!response.isSuccessful()) {
Log.d("HTTP_CODE","Code " + response.code());
try {
Log.d("HTTP_ERROR",response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
return;
}
data[0] = response.body();
Log.d("HTTP_DATA", ((LoggedInUser) data[0]).getUserId());
}
@Override
public void onFailure(Call<LoggedInUser> call, Throwable t) {
Log.d("HTTP_ERROR", t.getMessage());
}
});
return new Result.Success<>(data[0]);
} catch (Exception e) {
e.printStackTrace();
Log.d("HTTP_ERROR", "Error logging in");
return new Result.Error(new IOException("Error logging in", e));
}
}
暂无答案!
目前还没有任何答案,快来回答吧!