getView из пользовательского адаптера не обновляет элементы списка

Я работаю над приложением WordList Builder в Android. Приложение выбирает слова из базы данных и отображает их. Существует также вкладка «Избранное» для отображения только избранного. На главной странице отображаются все слова и звездочка рядом с любимыми словами. Когда пользователь отменяет выбор слова на вкладке избранного и возвращается на главную страницу, звездочка по-прежнему отображается на невыбранном избранном слове. Однако данные, взятые из базы данных, ясно показывают обновление. Затем я добавил операторы журнала в метод getView пользовательского адаптера, и здесь список элементов по-прежнему показывает первоначально загруженный список слов. Он не обновляется.

Ниже приведен мой код для пользовательского адаптера:

public class WordListAdapter  extends ArrayAdapter<Word> {

    protected static final String LOG_TAG = WordListAdapter.class.getSimpleName();

    private ArrayList<Word> items;
    int layoutResourceId;
    private Context context;

    public WordListAdapter(Context context,int layoutResourceId,ArrayList <Word> items) {
        super(context,layoutResourceId,items);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.items = items;
    }

    @Override
    public int getCount() {

        return items.size();
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        Log.i("WordListAdapter" ," NotifyDataSetChanged is called items size = " + this.items.size());
    }

    public void refreshList(ArrayList<Word> items) {
        this.items.clear();
        this.items.addAll(items);
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup arg2) {
        Log.i("WordListAdapter; " , " getView item size =" + this.items.size());
        Word wordListItems = this.items.get(position);

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.wordlist_item, null);

        }

        TextView tvWordName = (TextView)convertView.findViewById(R.id.wordlist_word);
        tvWordName.setText(wordListItems.getWordName());
        TextView tvWordId = (TextView)convertView.findViewById(R.id.wordlist_id);
        tvWordId.setText(Integer.toString(wordListItems.getId()));
        CheckBox cbFav = (CheckBox)convertView.findViewById(R.id.checkBoxFav);
        Log.i("WordListAdapter :" , "Position= " + position + "  Word " + wordListItems);
        cbFav.setChecked(wordListItems.isFavourite());
        cbFav.setTag(position);

        return convertView;
    }
}

Ниже приведен код основного действия:

public class WordBuilder extends Activity {

    //private static SimpleCursorAdapter cursorAdapter = null;
    private static WordListAdapter wordListAdapter = null;
    private static ListView lv = null;
    private static WordListDBSupport dbSupport = null;
    TabBar tabbar;
    ArrayList<Word> wordList;
    Intent intent ;

    AdapterView.OnItemClickListener mOnItemClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            long viewId = view.getId();
            TextView tv = (TextView) view.findViewById(R.id.wordlist_id);
            int rowId = Integer.parseInt(tv.getText().toString());


            Log.i("RowId : ", String.format("%d", rowId));

            Bundle bundle = new Bundle();
            bundle.putInt("rowId", rowId);
            tabbar.getIntent().putExtra("rowId", rowId);
            switchTabInActivity(tabbar.WORDLISTDETAILACTIVITY_TAB);


        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("WordBuilder ", " onCreate() ");
        setContentView(R.layout.activity_main);

        intent = getIntent();

        tabbar = (TabBar) this.getParent();


        dbSupport = new WordListDBSupport(this);
        lv = (ListView) findViewById(R.id.wordlist);

        //If getting tab 3, only the favourites
        wordList = new ArrayList<Word>();

        wordListAdapter = new WordListAdapter(this,R.id.wordlist, wordList);
        lv.setAdapter(wordListAdapter);

        lv.setOnItemClickListener(mOnItemClick);


    }

    public void switchTabInActivity(int indexTabToSwitchTo){
        tabbar.switchTab(indexTabToSwitchTo);
    }

    public void onResume() {
        super.onResume();
        Log.i("WordBuilder ", " onResume() ");
        updateCursorAdapter();
    }


    public void updateCursorAdapter() {
        //Query to get the updated list
        wordList.clear();
        Log.i("WordBuilder ", " updateCursorAdapter() wordList size =  " + wordList.size());
        wordList = dbSupport.getAllWords(intent.getIntExtra("isfavourite",0));
        Log.i("WordBuilder", "wordlist size after = " +wordList.size() );

        wordListAdapter.refreshList(wordList);
    }

    public void saveFavouritesHandler(View view) {

        //To be called on check or uncheck of the checkbox
        int position = (Integer)view.getTag();
        CheckBox cbFav = (CheckBox)view;
        Word wordToUpdate = wordList.get(position);
        int rowId = wordToUpdate.getId();
        Log.i("RowId isFav: ", String.format("%d ", rowId) + " isfav " + cbFav.isChecked() + " wordname= " + wordToUpdate.getWordName() + " Position = " + position);
        if (cbFav.isChecked()) {
            //save the selection in the database
            dbSupport.updateFavourite(rowId,1);
        } else {
            dbSupport.updateFavourite(rowId,0);
            Log.i("WordBuilder :" , " Position bring removed =" + position );
            if(intent.getIntExtra("isfavourite",0) == 1) {
                wordList.remove(position);
            }
        }
        updateCursorAdapter();
    }



}

Я удалил бой из списка избранного и обновил базу данных. Однако, когда я возвращаюсь на главную вкладку, где перечислены все слова, битва по-прежнему отображается как любимая.

все слова, показывающие старые данные списка с выделенной битвой

список избранного показывает только 3 элемента


person neetw    schedule 24.02.2016    source источник


Ответы (2)


Вы обновляете адаптер ListView, когда добавляете или удаляете значок fav. если это 2 разных действия, вам нужно обновить aapter в onResume основной деятельности

person Nidhin Prathap    schedule 24.02.2016

Попробуйте вызвать адаптер.notifyDataSetChanged(). Когда вы хотите обновить список. Надеюсь, поможет

person Jagjit Singh    schedule 24.02.2016