当我将获得的数据(包含在arraylist中)复制到新的arraylist中并返回时,新的arraylist不返回任何值。 onDataReceived(ArrayList arrayList)是通过arrayList中的凌空异步获取数据之后的侦听器回调方法。
package com.example.bike.ViewModels;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;
import com.example.bike.Models.BikesInfo;
import com.example.bike.Repository.BikesRepository;
import com.example.bike.Repository.Listener;
import com.example.bike.Views.ApplicationContext;
import java.util.ArrayList;
import java.util.Collections;
public class BikesViewModel extends AndroidViewModel {
private BikesRepository bikesRepository;
public static ArrayList<BikesInfo> vmarrayList = new ArrayList<>();
public BikesViewModel(@NonNull Application application) {
super(application);
bikesRepository = new BikesRepository(application, new Listener() {
@Override
public void onDataReceived(ArrayList<BikesInfo> arrayList) {
vmarrayList.addAll(arrayList);
}
@Override
public void onError(int error) {
}
});
bikesRepository.getArrayList();
}
public ArrayList<BikesInfo> getbikesinfolistobservable(){
return vmarrayList;
}
}
编辑: MainActivity.java
package com.example.bike.Views.ui;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.example.bike.Models.BikesInfo;
import com.example.bike.R;
import com.example.bike.ViewModels.BikesViewModel;
import com.example.bike.Views.Adapters.BikesListAdapter;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
BikesViewModel bikesViewModel;
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
BikesListAdapter bikesListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.bikes_recycler);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
bikesViewModel = ViewModelProviders.of(MainActivity.this).get(BikesViewModel.class);
bikesListAdapter = new BikesListAdapter(bikesViewModel.getbikesinfolistobservable());
recyclerView.setAdapter(bikesListAdapter);
}
}
答案 0 :(得分:1)
如果您正在使用截击进行请求,则不能确保在请求完成后将getbikesinfolistobservable()调用作为异步请求进行执行。
尝试在vmarrayList.addAll(arrayList)之后在vmarrayList上执行控制台日志。如果仍然为空,则ArrayList arrayList也为空,因此请求的响应将是一个问题。
另外,vmarrayList是一个静态变量,而BikesViewModel类是公共的,因此您不需要吸气剂。