我有一个searchview和一个recyclerview。从TheMovieDb.org API查询搜索结果后,我想在recyclerview上显示结果。
尝试
这是我的代码
private static final String API_KEY = "2e08750083b7e21e96e915011d3f8e2d";
private static final String TAG = SearchAdapter.class.getSimpleName();
private RecyclerView recyclerView;
public Search() {
// Required empty public constructor
}
@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
SearchView searchView = view.findViewById(R.id.search_view);
recyclerView = view.findViewById(R.id.search_result_tv);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
loadData(s);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return view;
}
private void loadData(String s) {
ApiInterface apiInterface = ApiClient.getList().create(ApiInterface.class);
Call<Response> responseCall = apiInterface.getMovieSearch(API_KEY, s);
responseCall.enqueue(new Callback<Response>() {
@Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
/* Load search from String here */
ArrayList<ResultsItem> resultsItemList;
if (response.body() != null) {
resultsItemList = (ArrayList<ResultsItem>) response.body().getResults();
SearchAdapter searchAdapter = new SearchAdapter(resultsItemList, getContext());
recyclerView.setAdapter(searchAdapter);
} else {
Log.d("NoResponse", "response null");
}
}
@Override
public void onFailure(@NotNull Call<Response> call, Throwable t) {
Log.d(TAG, t.toString());
}
});
}
答案 0 :(得分:0)
最好是在进行API调用之前定义适配器。像这样:
SearchAdapter searchAdapter = new SearchAdapter(resultsItemList, getContext());
recyclerView.setAdapter(searchAdapter);
Call<Responce> responceCall = //...
那是因为您无法将适配器设置为主线程或UI所在的位置。但是,由于您在定义项目时将其为空,因此需要使用notifyDataSetChanged()
。继续,将此功能添加到您的适配器类:
public void updateItems(List<Object> newItems) {
//Set your adapter items to the new items
adapterItems.clear()
adapterItems.addAll(newItems);
notifyDataSetChanged();
}
请注意,adapterItems
是适配器类中的List<Object>
。完成此操作后,您可以像这样更新您的回收站视图:
if (response.body() != null) {
resultsItemList = (ArrayList<ResultsItem>) response.body().getResults();
searchAdapter.updateItems(resultsItemList);
}
这应该可以解决您的问题。
答案 1 :(得分:0)
不要在on response中设置适配器,首先要使用onresponse方法在arraylist中获取数据。每次调用onresponse时都要清除arraylist,然后再调用adapter并在oncreateviewview中设置adapter。希望这会有所帮助。