我有一个Retrofit请求,该请求从我的API请求一个GroupAccount对象列表。该API会毫无问题地返回所有值,因此我尝试在活动中循环响应,这样可以完美地检索值,但是一旦调用
//groupAccounts is my list, declared and initialised globally, groupAccount is the object I create at the end of each iteration
groupAccounts.add(groupAccount);
它将所有groupAccount对象值设置为null。为什么会这样呢?
GroupAccount模型类中的构造函数:
public GroupAccount(long groupAccountId,
long adminId,
String accountName,
String accountDescription,
int numberOfMembers,
BigDecimal totalAmountPaid,
BigDecimal totalAmountOwed,
int testResourceId) {
}
具有onResponse和onFailure的请求方法:
public void getUserAssociatedAccounts(String userId){
Call<List<GroupAccount>> call = apiInterface.getUserAssociatedAccounts(userId);
call.enqueue(new Callback<List<GroupAccount>>() {
@Override
public void onResponse(Call<List<GroupAccount>> call, Response<List<GroupAccount>> response) {
if(!response.isSuccessful()) {
//Handle
} else {
if(response.body().size() > 0){
for(int i=0; i<response.body().size(); i++) {
//This is just for clarity
long groupAccountId = response.body().get(i).getGroupAccountId();
long adminId = response.body().get(i).getAdminId();
String accountName = response.body().get(i).getAccountName();
String accountDescription = response.body().get(i).getAccountDescription();
int numberOfMembers = response.body().get(i).getNumberOfMembers();
BigDecimal amountPaid = response.body().get(i).getTotalAmountPaid();
BigDecimal amountOwed = response.body().get(i).getTotalAmountOwed();
int testRes = R.drawable.human_photo;
//Value setting works fine
GroupAccount groupAccount = new GroupAccount(groupAccountId,
adminId,
accountName,
accountDescription,
numberOfMembers,
amountPaid,
amountOwed,
testRes);
//Values are now null here???
groupAccounts.add(groupAccount);
}
setUpFAB();
setUpNavDrawer();
setUpAccountPreviewRecyclerView();
emptyRVTextViewSetUp(checkIfListIsEmpty(groupAccounts));
}
}
}
@Override
public void onFailure(Call<List<GroupAccount>> call, Throwable t) {
}
});
}
在课程开始时,我的列表设置如下:
public class Home extends AppCompatActivity {
List<GroupAccount> groupAccounts = new ArrayList<>();
.
...rest of class
.
}
答案 0 :(得分:1)
您尚未在构造函数中设置对象
您的代码:
public GroupAccount(long groupAccountId,
long adminId,
String accountName,
String accountDescription,
int numberOfMembers,
BigDecimal totalAmountPaid,
BigDecimal totalAmountOwed,
int testResourceId) {
}
正确的构造方法:
public GroupAccount(long groupAccountId,
long adminId,
String accountName,
String accountDescription,
int numberOfMembers,
BigDecimal totalAmountPaid,
BigDecimal totalAmountOwed,
int testResourceId) {
this.groupAccountId = groupAccountId;
this.adminId = adminId;
this.accountName = accountName;
this.accountDescription = accountDescription;
this.numberOfMembers = numberOfMembers;
this.totalAmountPaid = totalAmountPaid;
this.totalAmountOwed = totalAmountOwed;
this.testResourceId = testResourceId;
}