#android #android-recyclerview #ui-thread #notifydatasetchanged
Вопрос:
Я борюсь с этой проблемой около 2-3 дней; Я изучал тему и кое-что еще об этом случае, но безрезультатно.
моя проблема: у меня есть действие с RecyclerView и SearchView, когда я что-то ищу, RecyclerView не обновляется, вызывая notifyDataSetChanged. после поиска об этом я узнал, что это связано с вызовом этого метода в потоке пользовательского интерфейса none, так как я должен это сделать? Я попробовал AsyncTask, новое запускаемое и другое решение, но результат оказался неэффективным.
большое спасибо и извините за мой плохой английский.
Класс активности:
public class GoodsListActivity extends AppCompatActivity {
private GoodsListAdapter goodsListAdapter;
private RecyclerView rvGoodsList;
private List goodsList= new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goods_list);
GoodsDAO goodsDAO =TopDb.getTopDb(getApplicationContext()).getGoodsDAO();
goodsList= (ArrayList<Goods>) goodsDAO.getAllGoods();
rvGoodsList=findViewById(R.id.rv_goods_list);
rvGoodsList.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
goodsListAdapter=new GoodsListAdapter((ArrayList<Goods>) goodsList,this);
rvGoodsList.setAdapter(goodsListAdapter);
SearchView searchView=findViewById(R.id.sv_search_goods_list);
search(searchView);
}
private void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
goodsListAdapter.getFilter().filter(newText);
return true;
}
});
}
}
Класс адаптеров:
public class GoodsListAdapter extends RecyclerView.Adapter<GoodsListAdapter.ViewHolder> implements Filterable {
private Context context;
private ArrayList<Goods> goodsList =new ArrayList<>();
private ArrayList<Goods> filteredGoodsList =new ArrayList<>();
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.single_goods_list,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
//get goods code and combine with goods name to show in goods name text view
String goodsCodeStr=goodsList.get(position).getgCode();
String goodsNameStr=goodsList.get(position).getgName();
String goodsNameCodeStr=goodsNameStr " " "(" goodsCodeStr ")";
holder.getTvgName().setText(goodsNameCodeStr);
//
//get goods picture Uri path and set to goods picture image button
String goodPicUri=MainPanelActivity.topPicsUri "/" goodsCodeStr ".jpg";
holder.getImgBtngPicture().setImageURI(Uri.parse(goodPicUri));
//
//calculate goods units count and set to goods units text view
String gPrimUnit=goodsList.get(position).getgPrimaryUnit();
String gFunit=goodsList.get(position).getgFirstUnit();
String gSunit=goodsList.get(position).getgSecondUnit();
String gFunitRatio=goodsList.get(position).getgFirstUnitRatio().toString();
String gSunitRatio=goodsList.get(position).getgSecondUnitRatio().toString();
String gPrimStock=goodsList.get(position).getgPrimaryUnitStock().toString();
String gFstock=goodsList.get(position).getgFirstUnitStock().toString();
String gSstock=goodsList.get(position).getgSecondUnitStock().toString();
String gPunitStock="(" gPrimStock " " gPrimUnit ")";
String gFunitStock="(" gFstock " " gFunit " " gFunitRatio " " gPrimUnit ")";
String gSunitStock="(" gSstock " " gSunit " " gSunitRatio " " gPrimUnit ")";
String gFullUnitStock=gPunitStock "n " gFunitStock " " gSunitStock;
holder.getTvgUnits().setText(gFullUnitStock);
//
//set accessible stock to accessible stock text view
if (goodsList.get(position).getgAccessiblePrinmaryUnitStock() != null) {
String gAccessibleStock = goodsList.get(position).getgAccessiblePrinmaryUnitStock().toString();
String gAccessibleUnitStock = "(" gAccessibleStock " " gPrimUnit ")";
holder.getTvgAccissibleStock().setText(gAccessibleUnitStock);
}
else {
holder.getTvgAccissibleStock().setVisibility(View.GONE);
}
//
holder.getTvgSerialTech().setText(goodsList.get(position).getgSerial());
holder.getTvgPrice1().setText(goodsList.get(position).getgPrice1().toString());
holder.getTvgPrice2().setText(goodsList.get(position).getgPrice2().toString());
holder.getTvgPrice3().setText(goodsList.get(position).getgPrice3().toString());
holder.getTvgDescription().setText(goodsList.get(position).getgDescription());
//set click listener for each goods item to show full screen goods picture
holder.getImgBtngPicture().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(context, ShowSinglePictureActivity.class);
i.putExtra("gPicUriValue", goodPicUri);
context.startActivity(i);
}
});
//
holder.getTvgName().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//check to response only we have came from new order activity
if (NewOrderActivity.isResultFromGoodsListActivity==true)
{
NewOrderActivity.newOrderGcode=goodsList.get(position).getgCode();
NewOrderActivity.tvNewOrderGname.setText(goodsList.get(position).getgName());
NewOrderActivity.etNewOrderGprice.setText(goodsList.get(position).getgPrice1().toString());
//obtain and set goods units to new order activity units selection spinner
String primaryU=goodsList.get(position).getgPrimaryUnit();
String firstU=goodsList.get(position).getgFirstUnit();
String secondUnit=goodsList.get(position).getgSecondUnit();
String[] goodsUnits={primaryU,firstU,secondUnit};
ArrayAdapter<String> spinerUnitAdapter=new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item,goodsUnits);
NewOrderActivity.spNewOrderUnits.setAdapter(spinerUnitAdapter);
//
NewOrderActivity.isResultFromGoodsListActivity=false;
( (GoodsListActivity)context).onBackPressed();
}
}
});
}
@Override
public int getItemCount() {
return goodsList.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filteredGoodsList = goodsList;
} else {
ArrayList<Goods> filteredList = new ArrayList<>();
for (Goods goods : goodsList) {
if (goods.getgName().contains(charString)) {
filteredList.add(goods);
}
}
filteredGoodsList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredGoodsList;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filteredGoodsList = (ArrayList<Goods>) filterResults.values;
notifyDataSetChanged();
}
};
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private final TextView tvgName;
private final TextView tvgUnits;
private final TextView tvgAccissibleStock;
private final TextView tvgSerialTech;
private final TextView tvgPrice1;
private final TextView tvgPrice2;
private final TextView tvgPrice3;
private final TextView tvgDescription;
private final ImageButton imgBtngPicture;
public ViewHolder(View view){
super(view);
tvgName=view.findViewById(R.id.single_goods_list_gname);
tvgUnits=view.findViewById(R.id.single_goods_list_gunits);
tvgAccissibleStock=view.findViewById(R.id.single_goods_list_gaccissiblestock);
tvgSerialTech=view.findViewById(R.id.single_goods_list_gserial_gtechcode);
tvgPrice1=view.findViewById(R.id.single_goods_list_gprice1);
tvgPrice2=view.findViewById(R.id.single_goods_list_gprice2);
tvgPrice3=view.findViewById(R.id.single_goods_list_gprice3);
tvgDescription=view.findViewById(R.id.single_goods_list_gdescription);
imgBtngPicture=view.findViewById(R.id.single_goods_list_gpicture);
}
public TextView getTvgName() {
return tvgName;
}
public TextView getTvgUnits() {
return tvgUnits;
}
public TextView getTvgAccissibleStock() {
return tvgAccissibleStock;
}
public TextView getTvgSerialTech() {
return tvgSerialTech;
}
public TextView getTvgPrice1() {
return tvgPrice1;
}
public TextView getTvgPrice2() {
return tvgPrice2;
}
public TextView getTvgPrice3() {
return tvgPrice3;
}
public TextView getTvgDescription() {
return tvgDescription;
}
public ImageButton getImgBtngPicture() {
return imgBtngPicture;
}
}
///
public GoodsListAdapter(ArrayList<Goods> goodsObjsList,Context c){
context=c;
goodsList =goodsObjsList;
}
///
}
в адаптерклассе notifyDataSetChanged() внутри результатов публикации не работает.