问题描述
我试图在我的项目中使用MVVM这么多天。但无法实现。
我的代码:
FeedRepository.java
public class FeedsRepository {
private static FeedsRepository instance;
private List<Feed> feedsToAppend = new ArrayList<>();
public static FeedsRepository getInstance() {
if (instance == null) {
instance = new FeedsRepository();
}
return instance;
}
public MutableLiveData<List<Feed>> getFeeds() {
MutableLiveData<List<Feed>> mFeeds = new MutableLiveData<>();
Query query;
query = feedsRef.whereEqualTo("userID",currentUID).whereEqualTo("not_interested",false)
.orderBy("created_at",Query.Direction.DESCENDING).limit(10);
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot snapshot = task.getResult();
if (snapshot.isEmpty()) {
} else {
List<DocumentSnapshot> documents = snapshot.getDocuments();
for (DocumentSnapshot doc: documents) {
final Feed feed = doc.toObject(Feed.class);
feed.setFeedID(doc.getId());
feed.setFeedAvailable(true);
feedsToAppend.add(feed);
System.out.println("Feed: " + feed.getFeedID());
}
System.out.println("Total feeds to append: " + feedsToAppend.size());
mFeeds.setValue(feedsToAppend);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
return mFeeds;
}
HomeViewModel.java
public class HomeViewModel extends ViewModel {
private MutableLiveData<List<Feed>> mFeeds;
private FeedsRepository repo;
public void init() {
if (mFeeds != null) {
return;
}
repo = FeedsRepository.getInstance();
mFeeds = repo.getFeeds();
}
public LiveData<List<Feed>> getFeeds() {
return mFeeds;
}
}
HomeFragment.java
public View onCreateView(@NonNull LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment,container,false);
feedsRecycleView = view.findViewById(R.id.feeds_recycler_view);
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
homeViewModel.init();
homeViewModel.getFeeds().observe(getViewLifecycleOwner(),new Observer<List<Feed>>() {
@Override
public void onChanged(List<Feed> feeds) {
System.out.println("Feed adapter feeds: "+feeds.size());
mFeeds = feeds;
feedAdapter.notifyDataSetChanged();
}
});
List<Feed> testFeeds = homeViewModel.getFeeds().getValue();
System.out.println("Test feeds are : " + testFeeds.size());
feedAdapter = new FeedAdapter(getContext(),homeViewModel.getFeeds().getValue());
feedsRecycleView.setAdapter(feedAdapter);
feedsRecycleView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setStackFromEnd(true); //newer posts will be shown on top
linearLayoutManager.setReverseLayout(true);
feedsRecycleView.setLayoutManager(linearLayoutManager);
return view;
}
我收到错误消息
“试图在接口上调用接口方法'int java.util.List.size()' 空对象引用”
在此行
List<Feed> testFeeds = homeViewModel.getFeeds().getValue();
和
feedAdapter = new FeedAdapter(getContext(),homeViewModel.getFeeds().getValue());
请任何人告诉我我在哪里犯错。
解决方法
您遇到以下错误:
“试图在空对象引用上调用接口方法'int java.util.List.size()'”
最有可能在此特定代码行:
System.out.println("Test feeds are : " + testFeeds.size());
这是因为您的testFeeds
对象是null
,这意味着:
homeViewModel.getFeeds().getValue();
返回null
。这也意味着getValue()
方法返回一个null
的LiveData对象,的确如此,就像您的HomeViewModel
类中那样,getFeeds()
方法返回一个从不存在的LiveData对象。初始化。要解决此问题,请更改以下代码行:
private MutableLiveData<List<Feed>> mFeeds
到
private MutableLiveData<List<Feed>> mFeeds = new MutableLiveData<>();
,
我尝试了这个,但是仍然是相同的错误
public MutableLiveData<List<Feed>> getFeeds() {
MutableLiveData<List<Feed>> mFeeds = new MutableLiveData<>();
return mFeeds;
}
,
好的。我知道了。
我必须在FeedsRepository中添加此行,
public MutableLiveData<ArrayList<Feed>> getFeeds() {
MutableLiveData<ArrayList<Feed>> mFeeds = new MutableLiveData<>();
mFeeds.setValue(feedsToAppend);
......
并且从后端获取记录后,再次
mFeeds.setValue(feedsToAppend);
由于后端进程是异步的,因此需要一段时间才能提取 它将返回空对象。