There is an adapter based on BaseAdapter.

public class WordsAdapter extends BaseAdapter { Context ctx; ArrayList<SingleWord> words; int perevod; //Объект класса SingleWord SingleWord p; private Spinner spinner; //Объявляет переменную типа SlovarDBHeler SlovarDBHeler db; //Конструктор класса WordsAdapter WordsAdapter(Context context, ArrayList<SingleWord> words, int p, SlovarDBHeler db) { ctx = context; this.words = words; perevod = p; this.db = db; } static class ViewHolder { TextView txtAlphabet; TextView txtWord; ImageButton btnFavorites; } //Сеттер для переменной perevod чтобы из MainActivity устанавливать значение переменной, а в этом адаптере брать это значение и проверять в условиях public void setPerevod(int perevod) { this.perevod = perevod; } //Геттер для переменной perevod public int getPerevod() { return perevod; } public void updateAdapter(ArrayList<SingleWord> res) { words = res; notifyDataSetChanged(); } public void setSpinner(Spinner spinner) { this.spinner = spinner; } public Spinner getSpinner() { return spinner; } @Override public int getCount() { return words.size(); } @Override public Object getItem(int position) { return words.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { //Переменная типа ViewHolder final ViewHolder viewHolder; //Создаем объект типа SingleWord p = getSingleWord(position); if (convertView == null){ LayoutInflater inflater = (LayoutInflater) ctx .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.item, parent, false); //Создаем объект типа ViewHolder viewHolder = new ViewHolder(); // viewHolder.txtAlphabet = (TextView) convertView.findViewById(R.id.txtAlphabet); viewHolder.txtWord = (TextView) convertView.findViewById(R.id.txtWord); viewHolder.btnFavorites = (ImageButton) convertView.findViewById(R.id.btnFavorites); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } //Вставляем в соответствующие TextView и ImageButton данные из класса SingleWord viewHolder.txtWord.setText(p.word); viewHolder.txtAlphabet.setText(p.alphabet); viewHolder.btnFavorites.setImageResource(p.bntIcon); viewHolder.btnFavorites.setFocusable(false); //Проверяем если значение favorites из класса SingleWord = 1, то одна иконки, иначе другая if (words.get(position).getFavorites().equals("1")) { viewHolder.btnFavorites.setImageResource(R.drawable.icon_star_yellow); } else if (words.get(position).getFavorites().equals("0")) { viewHolder.btnFavorites.setImageResource(R.drawable.icon_star_outline_black); } //Событие клика на кнопку "Добавить в избранное" viewHolder.btnFavorites.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (getPerevod() == 1) { System.out.println(getPerevod()); //Проверяем опять переменную favorites if (words.get(position).getFavorites().equals("1")) { String wordStr = viewHolder.txtWord.getText().toString(); ContentValues values = new ContentValues(); values.put(SlovarContract.SlovarEntry.COLUMN_FAVORITES, "0"); // Вставляем новый ряд в базу данных и запоминаем его идентификатор long newRowId = db.database.update(SlovarContract.SlovarEntry.TABLE_RUS, values, SlovarContract.SlovarEntry.COLUMN_WORD + "= ?", new String[]{wordStr}); words.get(position).setFavorites("0"); // Выводим сообщение в успешном случае или при ошибке if (newRowId == -1) { // Если ID -1, значит произошла ошибка Toast.makeText(ctx, "Ошибка", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ctx, "Удалено из избранное", Toast.LENGTH_SHORT).show(); viewHolder.btnFavorites.setImageResource(R.drawable.icon_star_outline_black); } } else if (words.get(position).getFavorites().equals("0")){ String wordStr = viewHolder.txtWord.getText().toString(); ContentValues values = new ContentValues(); values.put(SlovarContract.SlovarEntry.COLUMN_FAVORITES, "1"); // Вставляем новый ряд в базу данных и запоминаем его идентификатор long newRowId = db.database.update(SlovarContract.SlovarEntry.TABLE_RUS, values, SlovarContract.SlovarEntry.COLUMN_WORD + "= ?", new String[]{wordStr}); words.get(position).setFavorites("1"); // Выводим сообщение в успешном случае или при ошибке if (newRowId == -1) { // Если ID -1, значит произошла ошибка Toast.makeText(ctx, "Ошибка", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ctx, "Добавлено в избранное", Toast.LENGTH_SHORT).show(); viewHolder.btnFavorites.setImageResource(R.drawable.icon_star_yellow); } } } } }); return convertView; } SingleWord getSingleWord(int position) { return ((SingleWord) getItem(position)); } } 

The data is output to the ListView from the database through this adapter. I'm trying to update the data in Listview after closing another activity and returning to MainActivity. I added updateAdapter method to adapter, and I call updateAdapter in MainActivity in onActivityResult, but nothing is updated.

    1 answer 1

    Excuse me, why do you need a model? The code is just awful

    1) Inherit from SimpleCursorAdapter . This will allow you to use the id record passed in onItemClick .

    2) In your case, you need to remove the model and the code that creates your List too. The adapter does not need to transfer it. Pass only the cursor . Accordingly, in bindView you need to receive data directly from the database, for example,

     String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME)); 

    And bandage

     textview.setText(name); 

    3) If you update the data in the database and then call notifyDataSetChanged , then before this you should restore the cursor

     cursor.requery(); 

    So everything will work for you.

    • Is there any example where you can see how your version is implemented? - Collective Farmer
    • SimpleCursorAdapter itself iterates the cursor (no need to move the position on the cursor). Instead of getView() , the CursorAdapter uses the newView() methods for inflate and bindView() for binding data on the item. Custom adapter example - pavlofff
    • Explain to a newbie what is binding and inflate? :) - The collective farmer
    • @ Collective farmer In the example, everything is written. Inflite - creating view-objects from xml-markup, binding - linking view-objects with the data that they should display. - pavlofff
    • I will look .. For now, based on my example, can I do what I want? - Collective Farmer