Как просмотреть данные в RecycleView?

#android

#Android

Вопрос:

Я использую retrofit2 для импорта данных из каждой из трех таблиц.

Поместите значения в один список и покажите их в RecycleView.

Но он показывает первый результат после второго запуска.

Второй результат отображается после третьего запуска.

Первый запуск — ничего.

При первом запуске list.size() адаптера также дает ноль.

Я не знаю, почему.

Это MainActivity.

 public class HistoryActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView foodTextView, companyTextView, dateTextView, useMaterialTextView;
    private ImageView dateChangeImgView;
    Calendar calendar;
    RecyclerView historyRecyclerView;
    ApiInterface apiInterface;
    RecyclerView.LayoutManager layoutManager;
    List<CowInfoData> cowInfoDataList;
    List<RiceInfoData> riceInfoDataList;
    List<VegetableInfoData> vegetableInfoDataList;
    List list = new ArrayList();
    HistoryAdapter historyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        HistoryActivityInit();

        Intent intent = getIntent();
        String foodName = intent.getExtras().getString("food_name");
        String companyName = intent.getExtras().getString("company_name");

        foodTextView.setText(foodName);
        companyTextView.setText(companyName);
    }

    private void HistoryActivityInit() {
        foodTextView = findViewById(R.id.text_food_name);
        companyTextView = findViewById(R.id.text_company_name);
        dateChangeImgView = findViewById(R.id.imgview_date_change);
        dateTextView = findViewById(R.id.text_date);
        useMaterialTextView = findViewById(R.id.text_use_material);
        historyRecyclerView = findViewById(R.id.recyclerview_history);

        calendar = new GregorianCalendar();

//        dateTextView.setText(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));

        layoutManager = new LinearLayoutManager(this);
        historyRecyclerView.setLayoutManager(layoutManager);
        historyRecyclerView.setHasFixedSize(true);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgview_date_change:
                chooseDate();
                break;
        }
    }

    private void chooseDate() {
        final View dialogView = View.inflate(this, R.layout.dialog_date_picker, null);
        final DatePicker datePicker = dialogView.findViewById(R.id.date_picker);
        datePicker.updateDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);
        builder.setNegativeButton("Cancel", null);
        builder.setPositiveButton("Ok", (dialog, which) -> {
            calendar = new GregorianCalendar(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
            dateTextView.setText(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));

            String f_name = foodTextView.getText().toString();
            String c_name = companyTextView.getText().toString();
            String d_date = dateTextView.getText().toString();

            Log.e("HistoryActivity", f_name);
            Log.e("HistoryActivity", c_name);
            Log.e("HistoryActivity", d_date);

            historyInquiry(f_name, c_name, d_date);
        });

        builder.show();
    }

    private void historyInquiry(String food_name, String company_name, String date) {
        apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
        Call<List<CowInfoData>> call = apiInterface.getHistory_cow(food_name, company_name, date);
        call.enqueue(new Callback<List<CowInfoData>>() {
            @Override
            public void onResponse(Call<List<CowInfoData>> call, Response<List<CowInfoData>> response) {
                cowInfoDataList = response.body();
                list.addAll(cowInfoDataList);
            }

            @Override
            public void onFailure(Call<List<CowInfoData>> call, Throwable t) {
                Log.e("ErrorMessage", t.toString());
            }
        });

        Call<List<RiceInfoData>> call2 = apiInterface.getHistory_rice(food_name, company_name, date);
        call2.enqueue(new Callback<List<RiceInfoData>>() {
            @Override
            public void onResponse(Call<List<RiceInfoData>> call, Response<List<RiceInfoData>> response) {
                riceInfoDataList = response.body();
                list.addAll(riceInfoDataList);
            }

            @Override
            public void onFailure(Call<List<RiceInfoData>> call, Throwable t) {
                Log.e("ErrorMessage", t.toString());
            }
        });

        Call<List<VegetableInfoData>> call3 = apiInterface.getHistory_vegetable(food_name, company_name, date);
        call3.enqueue(new Callback<List<VegetableInfoData>>() {
            @Override
            public void onResponse(Call<List<VegetableInfoData>> call, Response<List<VegetableInfoData>> response) {
                vegetableInfoDataList = response.body();
                list.addAll(vegetableInfoDataList);
            }

            @Override
            public void onFailure(Call<List<VegetableInfoData>> call, Throwable t) {
                Log.e("ErrorMessage", t.toString());
            }
        });

        historyAdapter = new HistoryAdapter(list, HistoryActivity.this);
        historyRecyclerView.setAdapter(historyAdapter);
        historyAdapter.notifyDataSetChanged();
    }
}
  

Это адаптер.

 public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List list;
    private Context context;

    public HistoryAdapter(List list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getItemViewType(int position) {
        if(list.get(position) instanceof CowInfoData) {
            return 0;
        } else if(list.get(position) instanceof RiceInfoData) {
            return 1;
        }

        return 2;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if(viewType == 0) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history_cow, parent, false);
            CowHistoryViewHolder holder = new CowHistoryViewHolder(view);
            return holder;
        } else if(viewType == 1) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history_rice, parent, false);
            RiceHistoryViewHolder holder = new RiceHistoryViewHolder(view);
            return holder;
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history_vegetable, parent, false);
            VegetableHistoryViewHolder holder = new VegetableHistoryViewHolder(view);
            return holder;
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        if(this.getItemViewType(position) == 0) {
            CowInfoData cowInfoData = (CowInfoData)list.get(position);
            CowHistoryViewHolder holder = (CowHistoryViewHolder) viewHolder;
            holder.cowCategoryTextView.setText(cowInfoData.getCow_category());
            holder.cowCompanyTextView.setText(cowInfoData.getCow_packing_company());
            holder.cowTrackingNumTextView.setText(cowInfoData.getCow_tracking_num());
            holder.cowGradeTextView.setText(cowInfoData.getCow_grade());

            Log.e("HistoryAdapter", cowInfoData.getCow_tracking_num());
        } else if(this.getItemViewType(position) == 1) {
            RiceInfoData riceInfoData = (RiceInfoData)list.get(position);
            RiceHistoryViewHolder holder = (RiceHistoryViewHolder) viewHolder;
            holder.riceNameTextView.setText(riceInfoData.getRice_name());
            holder.riceCompanyTextView.setText(riceInfoData.getRice_company());
            holder.riceProduceTextView.setText(riceInfoData.getProduce_date());

            Log.e("HistoryAdapter", riceInfoData.getRice_name());
        } else if(this.getItemViewType(position) == 2) {
            VegetableInfoData vegetableInfoData = (VegetableInfoData)list.get(position);
            VegetableHistoryViewHolder holder = (VegetableHistoryViewHolder) viewHolder;
            holder.vegetableNameTextView.setText(vegetableInfoData.getVegetable_name());
            holder.vegetableCompanyTextView.setText(vegetableInfoData.getVegetable_company());

            Log.e("HistoryAdapter", vegetableInfoData.getVegetable_name());
        } else {
            Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public int getItemCount() {
        Log.e("HistoryAdapter", String.valueOf(list.size()));
        return list.size();
    }

    public static class CowHistoryViewHolder extends RecyclerView.ViewHolder {

        TextView cowCategoryTextView, cowCompanyTextView, cowTrackingNumTextView, cowGradeTextView;

        public CowHistoryViewHolder(@NonNull View itemView) {
            super(itemView);
            cowCategoryTextView = itemView.findViewById(R.id.text_cow_category);
            cowCompanyTextView = itemView.findViewById(R.id.text_cow_company);
            cowTrackingNumTextView = itemView.findViewById(R.id.text_cow_tracking_num);
            cowGradeTextView = itemView.findViewById(R.id.text_cow_grade);
        }
    }

    public static class RiceHistoryViewHolder extends RecyclerView.ViewHolder {

        TextView riceNameTextView, riceCompanyTextView, riceProduceTextView;

        public RiceHistoryViewHolder(@NonNull View itemView) {
            super(itemView);
            riceNameTextView = itemView.findViewById(R.id.text_rice_name);
            riceCompanyTextView = itemView.findViewById(R.id.text_rice_company);
            riceProduceTextView = itemView.findViewById(R.id.text_rice_produce);
        }
    }

    public static class VegetableHistoryViewHolder extends  RecyclerView.ViewHolder {

        TextView vegetableNameTextView, vegetableCompanyTextView;

        public VegetableHistoryViewHolder(@NonNull View itemView) {
            super(itemView);
            vegetableNameTextView = itemView.findViewById(R.id.text_vegetable_name);
            vegetableCompanyTextView = itemView.findViewById(R.id.text_vegetable_company);
        }
    }
}
  

Пожалуйста, помогите мне.

Ответ №1:

Вы не вызываете notifyDataSetChanged(); после обновления данных

просто добавьте historyAdapter.notifyDataSetChanged(); после list.addAll(cowInfoDataList) ;

также

 historyAdapter = new HistoryAdapter(list, HistoryActivity.this);
historyRecyclerView.setAdapter(historyAdapter);
  

Эти две строки должны быть выполнены перед вызовом API. Может быть внутри oncreate()