Я использую структуру MVVM в своем проекте. В одном упражнении у меня есть два обзора и один адаптер. Они оба используют один и тот же tasks_layout . Я установил данные следующим образом:
final UnsortedAdapter adapter = new UnsortedAdapter();
eatFrog.setHasFixedSize(true);
eatFrog.setLayoutManager(new LinearLayoutManager(this));
eatFrog.setAdapter(adapter);
biologicalRhythms.setAdapter(adapter);
biologicalRhythms.setLayoutManager(new LinearLayoutManager(this));
biologicalRhythms.setHasFixedSize(true);
viewModel.getUnsortedWhereDateIs(currentDate).observe(this, new Observer<List<Unsorted>>() {
@Override
public void onChanged(List<Unsorted> unsorted) {
adapter.setData(EatAFrog(unsorted));
eatAFrogList = EatAFrog(unsorted);
adapter.setData(BiologicalRhythms(unsorted));
biologicalList = BiologicalRhythms(unsorted);
}
});
Дело в том, что каждое представление переработчика получает данные одного и того же класса "Unsorted", но данные проходили через два разных алгоритма. Если я сделаю это таким образом, то два обзора переработчика будут иметь одинаковые данные, которые проходили по второму алгоритму.
Я пытался делать разные вещи. Во-первых, я попытался использовать другой экземпляр моего адаптера для второго обзора переработчика, но в этом случае не было данных, отображаемых в первом обзоре переработчика:
final UnsortedAdapter adapter = new UnsortedAdapter();
eatFrog.setHasFixedSize(true);
eatFrog.setLayoutManager(new LinearLayoutManager(this));
eatFrog.setAdapter(adapter);
final UnsortedAdapter adapter2 = new UnsortedAdapter();
biologicalRhythms.setAdapter(adapter2);
biologicalRhythms.setLayoutManager(new LinearLayoutManager(this));
biologicalRhythms.setHasFixedSize(true);
Вскоре я попытался создать другой класс адаптера, так же, как третий. Я также создал другой макет - tasks2_layout , где я изменил только идентификаторы элементов. Затем во втором новом адаптере я также изменил их в классе видоискателя. Мой самый первый адаптер выглядит так:
List<Unsorted> list = new ArrayList<>();
@NonNull
@Override
public UnsortedViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tasks_layout , parent, false);
return new UnsortedAdapter.UnsortedViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull UnsortedViewHolder holder, int position) {
Unsorted data = list.get(position);
holder.title.setText(data.getName());
holder.date.setText(data.getDate());
holder.category.setText(String.valueOf(data.getCategory()));
holder.attach.setText(String.valueOf(data.isAttach()));
holder.to.setText(String.valueOf(toTime(data.getDuration() + data.getTimeBegin())));
holder.from.setText(String.valueOf(toTime(data.getTimeBegin())));
}
public void setData(List<Unsorted> unsortedList){
this.list = unsortedList;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return list.size();
}
class UnsortedViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private TextView date;
private TextView from;
private TextView to;
private TextView category;
private TextView attach;
public UnsortedViewHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv_title);
date = itemView.findViewById(R.id.tv_date);
from = itemView.findViewById(R.id.tv_from2);
to = itemView.findViewById(R.id.tv_to2);
category = itemView.findViewById(R.id.tv_category);
attach = itemView.findViewById(R.id.tv_attach);
}
}
А второй, новый:
List<Unsorted> list = new ArrayList<>();
@NonNull
@Override
public UnsortedViewHolder2 onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tasks2_layout , parent, false);
return new UnsortedAdapter2.UnsortedViewHolder2(itemView);
}
@Override
public void onBindViewHolder(@NonNull UnsortedViewHolder2 holder, int position) {
Unsorted data = list.get(position);
holder.title.setText(data.getName());
holder.date.setText(data.getDate());
holder.category.setText(String.valueOf(data.getCategory()));
holder.attach.setText(String.valueOf(data.isAttach()));
holder.to.setText(String.valueOf(toTime(data.getDuration() + data.getTimeBegin())));
holder.from.setText(String.valueOf(toTime(data.getTimeBegin())));
}
public void setData1(List<Unsorted> unsortedList){
this.list = unsortedList;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return list.size();
}
class UnsortedViewHolder2 extends RecyclerView.ViewHolder{
private TextView title;
private TextView date;
private TextView from;
private TextView to;
private TextView category;
private TextView attach;
public UnsortedViewHolder2(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv_title1);
date = itemView.findViewById(R.id.tv_date1);
from = itemView.findViewById(R.id.tv_from3);
to = itemView.findViewById(R.id.tv_to3);
category = itemView.findViewById(R.id.tv_category1);
attach = itemView.findViewById(R.id.tv_attach1);
}
}
Когда я установил разные адаптеры для каждого из видов переработчика, ничего не изменилось. Как и в предыдущем случае, только во втором обзоре утилизатора были показаны некоторые данные.
final UnsortedAdapter adapter = new UnsortedAdapter();
eatFrog.setHasFixedSize(true);
eatFrog.setLayoutManager(new LinearLayoutManager(this));
eatFrog.setAdapter(adapter);
final UnsortedAdapter2 adapter2 = new UnsortedAdapter();
biologicalRhythms.setAdapter(adapter2);
biologicalRhythms.setLayoutManager(new LinearLayoutManager(this));
biologicalRhythms.setHasFixedSize(true);
А в onChange:
adapter.setData(EatAFrog(unsorted));
eatAFrogList = EatAFrog(unsorted);
adapter2.setData1(BiologicalRhythms(unsorted));
biologicalList = BiologicalRhythms(unsorted);
Не могли бы вы подсказать, как я могу решить эту проблему? Спасибо за любую помощь.
Класс MyViewModel:
public class UnsortedViewModel extends AndroidViewModel {
private DatesRepository repository2;
private UnsortedRepository repository;
private SortedRepository repository3;
private LiveData<List<Unsorted>> allUnsorted;
public UnsortedViewModel(@NonNull Application application) {
super(application);
repository3 = new SortedRepository(application);
repository2 = new DatesRepository(application);
repository = new UnsortedRepository(application);
allUnsorted = repository.getAllUnsorted();
}
public LiveData<List<Unsorted>> getUnsortedWhereDateIsAlgo1(String currentDate) throws ExecutionException, InterruptedException{
return repository.getUnsortedWhereDateIs(currentDate);
}
public LiveData<List<Unsorted>> getUnsortedWhereDateIsAlgo2(String currentDate) throws ExecutionException, InterruptedException{
return repository.getUnsortedWhereDateIs(currentDate);
}
MutableLiveData<List<Unsorted>> unsortedWhereDateIsAlgo1 = new MutableLiveData<>();
MutableLiveData<List<Unsorted>> unsortedWhereDateIsAlgo2 = new MutableLiveData<>();
public void insertDate(Dates dates) {
repository2.insertDate(dates);
}
public LiveData<List<Unsorted>> getAllUnsorted() {
return allUnsorted;
}
public void insert(Unsorted data){
repository.insert(data);
}
public void deleteAllUnsorted(){
repository.deleteAllUnsorted();
}
public void deleteWhereDateIs(String currentDate){
repository.deleteWhereDateIs(currentDate);
}
public void insertSorted(Sorted data){
repository3.insertSorted(data);
}
}
Репозиторий:
public class UnsortedRepository {
private UnsortedDao unsortedDao;
private LiveData<List<Unsorted>> allUnsorted;
public UnsortedRepository(Application application){
UnsortedDatabase database = UnsortedDatabase.getInstance(application);
unsortedDao = database.unsortedDao();
allUnsorted = unsortedDao.getAllUnsorted();
}
public LiveData<List<Unsorted>> getUnsortedWhereDateIs(String currentDate)
throws ExecutionException, InterruptedException{
return new
GetUnsortedWhereDateIsAsyncTask(unsortedDao).execute(currentDate).get();
}
private static class GetUnsortedWhereDateIsAsyncTask extends
AsyncTask<String, Void, LiveData<List<Unsorted>>> {
private UnsortedDao unsortedDao;
private GetUnsortedWhereDateIsAsyncTask(UnsortedDao unsortedDao){
this.unsortedDao = unsortedDao;
}
@Override
protected LiveData<List<Unsorted>> doInBackground(String ... strings) {
LiveData<List<Unsorted>> list =
unsortedDao.getUnsortedWhereDateIs(strings[0]);
return list;
}
}
}
Дао:
@Query ("SELECT * FROM Unsorted WHERE date = :currentDate")
LiveData<List<Unsorted>> getUnsortedWhereDateIs (String currentDate);