Пишу приложение словарь используя Room.
В БД есть две таблицы: ruseng и engrus. Для обеих таблиц написала классы-модели и интерфейсы DAO. Написала два адаптера для каждой таблицы. Но хотелось бы если возможно использовать один адаптер. В самом конце приведу пример как я пыталась написать один адаптер, но не поняла как получить нужные данные в MainActivity.
Класс RusOther (для таблицы ruseng)
@Entity(tableName = "ruseng") //Описывает таблицу в БД
public class RusOther {
@PrimaryKey(autoGenerate = true) //Система сама будет инкрементировать это поле в БД
@ColumnInfo(typeAffinity = INTEGER)
private int id;
@ColumnInfo(typeAffinity = TEXT)
private String word;
@ColumnInfo(typeAffinity = TEXT)
private String translation;
@ColumnInfo(typeAffinity = INTEGER)
private int favorites;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getTranslation() {
return translation;
}
public void setTranslation(String translation) {
this.translation = translation;
}
public int getFavorites() {
return favorites;
}
public void setFavorites(int favorites) {
this.favorites = favorites;
}
public RusOther(int id, String word, String translation, int favorites) {
this.id = id;
this.word = word;
this.translation = translation;
this.favorites = favorites;
}
}
Класс OtherRus (для таблицы engrus)
@Entity(tableName = "engrus") //Описывает таблицу в БД
public class OtherRus {
@PrimaryKey(autoGenerate = true) //Система сама будет инкрементировать это поле в БД
@ColumnInfo(typeAffinity = INTEGER)
private int id;
@ColumnInfo(typeAffinity = TEXT)
private String word;
@ColumnInfo(typeAffinity = TEXT)
private String translation;
@ColumnInfo(typeAffinity = INTEGER)
private int favorites;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getTranslation() {
return translation;
}
public void setTranslation(String translation) {
this.translation = translation;
}
public int getFavorites() {
return favorites;
}
public void setFavorites(int favorites) {
this.favorites = favorites;
}
public OtherRus(int id, String word, String translation, int favorites) {
this.id = id;
this.word = word;
this.translation = translation;
this.favorites = favorites;
}
}
Интерфейсы DAO
RusOtherDao
@Dao
public interface RusOtherDao {
@Query("SELECT * FROM ruseng")
LiveData<List<RusOther>> getAllRusOtherWords(); //Через LiveData мы наблюдаем за списком и обновляем его при изменениях
@Query("SELECT * FROM ruseng WHERE id = :id")
RusOther getRusOtherByID(long id);
}
OtherRusDao
@Dao
public interface OtherRusDao {
@Query("SELECT * FROM engrus")
LiveData<List<OtherRus>> getAllOtherRusWords(); //Через LiveData мы наблюдаем за списком и обновляем его при изменениях
@Query("SELECT * FROM engrusWHERE id = :id")
OtherRus getOtherRusByID(long id);
}
AppViewModel
public class AppViewModel extends AndroidViewModel {
private AppDatabase appDataBase;
public AppViewModel(Application application) {
super(application);
appDataBase = AppDatabase.createPersistentDatabase(this.getApplication());
}
//Получение всех слов с русского на другой язык
public LiveData<List<RusOther>> getAllRusOtherWords(){
return appDataBase.rusOtherDao().getAllRusOtherWords();
}
//Получение всех слов с другого на русский язык
public LiveData<List<OtherRus>> getAllOtherRusWords(){
return appDataBase.otherRusDao().getAllOtherRusWords();
}
public RusOther getByRusOtherId(long id){
return appDataBase.rusOtherDao().getRusOtherByID(id);
}
}
OtherRusAdapter
public class OtherRusAdapter extends RecyclerView.Adapter<OtherRusAdapter.WordViewHolder> implements Filterable {
private List<OtherRus> mWords;
private List<OtherRus> mFilteredList;
private Context mContext;
RusOtherAdapter.OnItemClickListener mItemClickListener;
public interface OnItemClickListener {
void onItemClick(long id);
}
public void setOnItemClickListener(final RusOtherAdapter.OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
class WordViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView txtWord;
private WordViewHolder(final View itemView) {
super(itemView);
txtWord = itemView.findViewById(R.id.txtWord);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
default:
mItemClickListener.onItemClick(mFilteredList.get(getAdapterPosition()).getId());
}
}
}
public OtherRusAdapter(Context context, List<OtherRus> mWords) {
this.mWords = mWords;
this.mFilteredList = mWords;
this.mContext = context;
}
@Override
public WordViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.item,parent,false);
WordViewHolder vh = new WordViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(WordViewHolder holder, int position) {
final OtherRus word = mFilteredList.get(position);
holder.txtWord.setText(word.getWord());
}
@Override
public int getItemCount() {
return mFilteredList.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = mWords;
} else {
List<OtherRus> filteredList = new ArrayList<>();
for (OtherRus word : mWords) {
if (word.getWord().toLowerCase().contains(charString)) {
filteredList.add(word);
}
}
mFilteredList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mFilteredList = (List<OtherRus>) filterResults.values;
notifyDataSetChanged();
}
};
}
}
Второй адаптер аналогичен
MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, RusOtherAdapter.OnItemClickListener, OtherRusAdapter.OnItemClickListener {
private AppViewModel viewModel;
private RecyclerView rvList;
RusOtherAdapter rusOtherAdapter;
OtherRusAdapter otherRusAdapter;
private TextView txtLeftLang;
private TextView txtRightLang;
private ImageButton btnChangeLang;
private boolean isOtherRight; //При запуске приложения False
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
***
txtLeftLang = findViewById(R.id.txtLeftLang);
txtRightLang = findViewById(R.id.txtRightLang);
btnChangeLang = findViewById(R.id.btnChangeLang);
txtLeftLang.setText(getResources().getString(R.string.rus_lang));
txtRightLang.setText(getResources().getString(R.string.other_lang));
rvList = findViewById(R.id.rvList);
rvList.setLayoutManager(new LinearLayoutManager(this));
viewModel = ViewModelProviders.of(this).get(AppViewModel.class);
viewModel.getAllRusOtherWords().observe(MainActivity.this, new Observer<List<RusOther>>() {
@Override
public void onChanged(@Nullable final List<RusOther> words) {
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i).getWord());
}
rusOtherAdapter = new RusOtherAdapter(MainActivity.this, words);
rusOtherAdapter.setOnItemClickListener(MainActivity.this);
rvList.setAdapter(rusOtherAdapter);
}
});
btnChangeLang.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txtRightLang.setText(isOtherRight? getResources().getString(R.string.other_lang):getResources().getString(R.string.rus_lang));
txtLeftLang.setText(isOtherRight? getResources().getString(R.string.rus_lang):getResources().getString(R.string.other_lang));
if (isOtherRight) { //перевод с русского на другой
rvList.setAdapter(null);
viewModel.getAllRusOtherWords().observe(MainActivity.this, new Observer<List<RusOther>>() {
@Override
public void onChanged(@Nullable final List<RusOther> words) {
rusOtherAdapter = new RusOtherAdapter(MainActivity.this, words);
rusOtherAdapter.setOnItemClickListener(MainActivity.this);
rvList.setAdapter(rusOtherAdapter);
}
});
} else { // перевод с другого на русский
rvList.setAdapter(null);
viewModel.getAllOtherRusWords().observe(MainActivity.this, new Observer<List<OtherRus>>() {
@Override
public void onChanged(@Nullable final List<OtherRus> words) {
otherRusAdapter = new OtherRusAdapter(MainActivity.this, words);
otherRusAdapter.setOnItemClickListener(MainActivity.this);
rvList.setAdapter(otherRusAdapter);
}
});
}
isOtherRight = !isOtherRight;
}
});
}
@Override //Нажатие на элемент списка
public void onItemClick(long id) {
Toast.makeText(this, id + "", Toast.LENGTH_LONG).show();
}
public void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
/*if (isOtherRight) {
if (rusOtherAdapter != null) {
rusOtherAdapter.getFilter().filter(newText);
}
} else {
if (otherRusAdapter != null) {
otherRusAdapter.getFilter().filter(newText);
}
}*/
return true;
}
});
}
}
P.S. Пыталась сделать так, но мне непонятно как дальше этот адаптер использовать в MainActivity
. Ведь в MainActivity
я получаю данные типа RusOther
или OtherRus
ItemAdapter
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {
private final int RUSOTHER = 1;
private final int OTHERRUS = 2;
boolean isSecondItem = false;
ArrayList<Item> items;
public ItemAdapter (ArrayList<Item> items) {
this.items = items;
}
@Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
switch (viewType) {
case RUSOTHER:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
break;
case OTHERRUS:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
break;
default:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
}
return new ItemHolder(v);
}
@Override
public void onBindViewHolder(ItemHolder holder, final int position) {
int type = getItemViewType(position);
switch (type) {
case RUSOTHER:
RusOther rusOther = (RusOther)items.get(position);
holder.txtWord.setText(rusOther.getWord());
break;
case OTHERRUS:
OtherRus otherRus = (OtherRus)items.get(position);
holder.txtWord.setText(otherRus.getWord());
isSecondItem = true;
break;
}
}
@Override
public int getItemViewType(int position) {
int type = items.get(position).getItemType();
if (type == 1) return RUSOTHER;
else return OTHERRUS;
}
@Override
public int getItemCount() {
return items.size();
}
class ItemHolder extends RecyclerView.ViewHolder {
public final TextView txtWord;
ItemHolder(View itemView) {
super(itemView);
txtWord = (TextView) itemView.findViewById(R.id.txtWord);
}
}
}
Интерфейс
public interface Item {
int getItemType ();
}