[英]How to update the RecyclerView Adapter outside the Adapter Class
I am making an android app and it allows user to enter the keywords in a editText and when they hit submit the recyclerview down below will show the result from an API request.我正在制作一个 android 应用程序,它允许用户在 editText 中输入关键字,当他们点击提交时,下面的 recyclerview 将显示来自 API 请求的结果。
I have a updateList() method inside my recyclerView adapter class我的 recyclerView 适配器类中有一个 updateList() 方法
list = savedInfo.getResult(); // get updated list from a singleton class
notifyDataSetChanged(); // update the recyclerView
I call this method after making the API Request successfully.我在成功发出 API 请求后调用此方法。 However, it is now working, the recyclerView is not updated.但是,它现在正在工作,recyclerView 没有更新。
mSearchBox is the editText allows users to enter keywords and here is the onEditorAction, it will make an API call and if it called successfully, it will call UpdateList(), then the adapter will get the updated list and do notifyDataSetChanged() mSearchBox 是editText 允许用户输入关键字,这里是onEditorAction,它会进行API 调用,如果调用成功,它将调用UpdateList(),然后适配器将获取更新的列表并执行notifyDataSetChanged()
mSearchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE) {
HttpRequest httpRequest = new HttpRequest();
mHomeText.setText(textView.getText());
try {
if (httpRequest.makeCall(textView.getText().toString())){
adapter.updateList();
}
else {
// showing error message
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
return false;
}
});
Also, here is the steps to set my adapter另外,这里是设置我的适配器的步骤
final ResultListAdapteradapter = new ResultListAdapter();
mResult.setAdapter(adapter);
mResult.setLayoutManager(new LinearLayoutManager(getContext()));
Debugging Steps: I tried to set break points and found out the API Request and my Singleton class are both working, the issue is just the RecyclerView.调试步骤:我尝试设置断点并发现 API 请求和我的单例类都在工作,问题只是 RecyclerView。
Thank you so much!非常感谢!
When you do当你做
list = savedInfo.getResult();
notifyDataSetChanged();
It is every time creating new list instance and the old one is not referenced anywhere.每次创建新的列表实例时都不会在任何地方引用旧的。 So instead of assigning to list you should do所以,而不是分配到列表你应该做
list.clear()
list.addAll(savedInfo.getResult());
notifyDataSetChanged();
Don't forget to initialize list
if not done before.如果之前没有完成,不要忘记初始化list
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.