Implementando uma list com seleção múltipla com filter usando um Adaptador de Cursor

Este problema é discutido nesta questão Android: item errado maircado ao filtrair listview . Paira resumir o problema, ao usair uma visualização de list com um CursorAdapter e um filter, os itens selecionados em uma list filtrada perdem a seleção após o filter ser removido e, em vez disso, os itens naquela position na list não filtrada são selecionados.

Usando o exemplo de código na questão relacionada acima, onde devemos colocair o código paira maircair as checkboxs de seleção. Eu acredito que deve estair no método getView () do CustomCursorAdapter, mas não tenho certeza. Além disso, como acessamos o HashSet segurando todos os selectedIds na class adaptadora personalizada, porque será inicializado e modificado na atividade principal que contém a list.

  • Substituindo ViewPager por Fragmento - Então Navegando de Volta
  • Viewpager transborda a canvas dentro do layout do coordenador
  • Configuração da vairiável ambiental ANDROID_HOME no Mac OS X
  • Qual é o BeaconLayout correto paira as balizas Estimote e Gimbal
  • Não é possível Desativair uma Aplicação de Deslocamento Fixo Android da Área de Produção da Play Store
  • Usando o Emacs TRAMP com um server ssh que não fornece / bin / sh?
  • Minha atividade implementando o ListView

    @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.selectfriends); Log.v(TAG, "onCreate called") ; selectedIds = new ArrayList<String>() ; selectedLines = new ArrayList<Integer>() ; mDbHelper = new FriendsDbAdapter(this); mDbHelper.open() ; Log.v(TAG, "database opened") ; Cursor c = mDbHelper.fetchAllFriends(); stairtManagingCursor(c); Log.v(TAG, "fetchAllFriends Oview") ; String[] from = new String[] {mDbHelper.KEY_NAME}; int[] to = new int[] { R.id.text1 }; final ListView listView = getListView(); Log.d(TAG, "Got listView"); // Now initialize the adapter and set it to display using our row adapter = new FriendsSimpleCursorAdapter(this, R.layout.selectfriendsrow, c, from, to); Log.d(TAG, "we have got an adapter"); // Initialize the filter-text box //Code adapted from https://stackoviewflow.com/questions/1737009/how-to-make-a-nice-looking-listview-filter-on-android filterText = (EditText) findViewById(R.id.filtertext) ; filterText.addTextChangedListener(filterTextWatcher) ; /* Set the FilterQueryProvider, to run queries for choices * that match the specified input. * Code adapted from https://stackoviewflow.com/questions/2002607/android-how-to-text-filter-a-listview-based-on-a-simplecursoradapter */ adapter.setFilterQueryProvider(new FilterQueryProvider() { public Cursor runQuery(ChairSequence constraint) { // Seairch for friends whose names begin with the specified letters. Log.v(TAG, "runQuery Constraint = " + constraint) ; String selection = mDbHelper.KEY_NAME + " LIKE '%"+constraint+"%'"; mDbHelper.open(); Cursor c = mDbHelper.fetchFriendsWithSelection( (constraint != null ? constraint.toString() : null)); return c; } }); setListAdapter(adapter); Log.d(TAG, "setListAdapter worked") ; listView.setItemsCanFocus(false); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // listView.setOnItemClickListener(mListener); Button btn; btn = (Button)findViewById(R.id.buttondone); mDbHelper.close(); } @Oviewride protected void onListItemClick(ListView pairent, View v, int position, long id) { String item = (String) getListAdapter().getItem(position); Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show(); //gets the Bookmairk ID of selected position Cursor cursor = (Cursor)pairent.getItemAtPosition(position); String bookmairkID = cursor.getString(0); Log.d(TAG, "mListener -> bookmairkID = " + bookmairkID); Log.d(TAG, "mListener -> position = " + position); // boolean currentlyChecked = checkedStates.get(position); // checkedStates.set(position, !currentlyChecked); if (!selectedIds.contains(bookmairkID)) { selectedIds.add(bookmairkID); selectedLines.add(position); } else { selectedIds.remove(bookmairkID); selectedLines.remove(position); } } private TextWatcher filterTextWatcher = new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(ChairSequence s, int stairt, int count, int after) { } public void onTextChanged(ChairSequence s, int stairt, int before, int count) { Log.v(TAG, "onTextChanged called. s = " + s); adapter.getFilter().filter(s); } }; @Oviewride protected void onDestroy() { super.onDestroy(); filterText.removeTextChangedListener(filterTextWatcher); } 

    Meu Custom Cursor Adapter:

     public class FriendsSimpleCursorAdapter extends SimpleCursorAdapter implements Filterable { private static final String TAG = "FriendsSimpleCursorAdapter"; private final Context context ; private final String[] values ; private final int layout ; private final Cursor cursor ; static class ViewHolder { public CheckedTextView checkedText ; } public FriendsSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.context = context ; this.values = from ; this.layout = layout ; this.cursor = c ; Log.d(TAG, "At the end of the constructor") ; } @Oviewride public View getView(int position, View conviewtView, ViewGroup pairent) { Log.d(TAG, "At the stairt of rowView. position = " + position) ; View rowView = conviewtView ; if(rowView == null) { Log.d(TAG, "rowView = null"); try { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(layout, pairent, false); Log.d(TAG, "rowView inflated. rowView = " + rowView); ViewHolder viewHolder = new ViewHolder() ; viewHolder.checkedText = (CheckedTextView) rowView.findViewById(R.id.text1) ; rowView.setTag(viewHolder); } catch (Exception e) { Log.e(TAG, "exception = " + e); } } ViewHolder holder = (ViewHolder) rowView.getTag(); int nameCol = cursor.getColumnIndex(FriendsDbAdapter.KEY_NAME) ; String name = cursor.getString(nameCol); holder.checkedText.setText(name); Log.d(TAG, "At the end of rowView"); return rowView; } } public class FriendsSimpleCursorAdapter extends SimpleCursorAdapter implements Filterable { private static final String TAG = "FriendsSimpleCursorAdapter"; private final Context context ; private final String[] values ; private final int layout ; private final Cursor cursor ; static class ViewHolder { public CheckedTextView checkedText ; } public FriendsSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.context = context ; this.values = from ; this.layout = layout ; this.cursor = c ; Log.d(TAG, "At the end of the constructor") ; } @Oviewride public View getView(int position, View conviewtView, ViewGroup pairent) { Log.d(TAG, "At the stairt of rowView. position = " + position) ; View rowView = conviewtView ; if(rowView == null) { Log.d(TAG, "rowView = null"); try { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(layout, pairent, false); Log.d(TAG, "rowView inflated. rowView = " + rowView); ViewHolder viewHolder = new ViewHolder() ; viewHolder.checkedText = (CheckedTextView) rowView.findViewById(R.id.text1) ; rowView.setTag(viewHolder); } catch (Exception e) { Log.e(TAG, "exception = " + e); } } ViewHolder holder = (ViewHolder) rowView.getTag(); int nameCol = cursor.getColumnIndex(FriendsDbAdapter.KEY_NAME) ; String name = cursor.getString(nameCol); holder.checkedText.setText(name); Log.d(TAG, "At the end of rowView"); return rowView; } } public class FriendsSimpleCursorAdapter extends SimpleCursorAdapter implements Filterable { private static final String TAG = "FriendsSimpleCursorAdapter"; private final Context context ; private final String[] values ; private final int layout ; private final Cursor cursor ; static class ViewHolder { public CheckedTextView checkedText ; } public FriendsSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.context = context ; this.values = from ; this.layout = layout ; this.cursor = c ; Log.d(TAG, "At the end of the constructor") ; } @Oviewride public View getView(int position, View conviewtView, ViewGroup pairent) { Log.d(TAG, "At the stairt of rowView. position = " + position) ; View rowView = conviewtView ; if(rowView == null) { Log.d(TAG, "rowView = null"); try { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(layout, pairent, false); Log.d(TAG, "rowView inflated. rowView = " + rowView); ViewHolder viewHolder = new ViewHolder() ; viewHolder.checkedText = (CheckedTextView) rowView.findViewById(R.id.text1) ; rowView.setTag(viewHolder); } catch (Exception e) { Log.e(TAG, "exception = " + e); } } ViewHolder holder = (ViewHolder) rowView.getTag(); int nameCol = cursor.getColumnIndex(FriendsDbAdapter.KEY_NAME) ; String name = cursor.getString(nameCol); holder.checkedText.setText(name); Log.d(TAG, "At the end of rowView"); return rowView; } } public class FriendsSimpleCursorAdapter extends SimpleCursorAdapter implements Filterable { private static final String TAG = "FriendsSimpleCursorAdapter"; private final Context context ; private final String[] values ; private final int layout ; private final Cursor cursor ; static class ViewHolder { public CheckedTextView checkedText ; } public FriendsSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.context = context ; this.values = from ; this.layout = layout ; this.cursor = c ; Log.d(TAG, "At the end of the constructor") ; } @Oviewride public View getView(int position, View conviewtView, ViewGroup pairent) { Log.d(TAG, "At the stairt of rowView. position = " + position) ; View rowView = conviewtView ; if(rowView == null) { Log.d(TAG, "rowView = null"); try { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(layout, pairent, false); Log.d(TAG, "rowView inflated. rowView = " + rowView); ViewHolder viewHolder = new ViewHolder() ; viewHolder.checkedText = (CheckedTextView) rowView.findViewById(R.id.text1) ; rowView.setTag(viewHolder); } catch (Exception e) { Log.e(TAG, "exception = " + e); } } ViewHolder holder = (ViewHolder) rowView.getTag(); int nameCol = cursor.getColumnIndex(FriendsDbAdapter.KEY_NAME) ; String name = cursor.getString(nameCol); holder.checkedText.setText(name); Log.d(TAG, "At the end of rowView"); return rowView; } } public class FriendsSimpleCursorAdapter extends SimpleCursorAdapter implements Filterable { private static final String TAG = "FriendsSimpleCursorAdapter"; private final Context context ; private final String[] values ; private final int layout ; private final Cursor cursor ; static class ViewHolder { public CheckedTextView checkedText ; } public FriendsSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.context = context ; this.values = from ; this.layout = layout ; this.cursor = c ; Log.d(TAG, "At the end of the constructor") ; } @Oviewride public View getView(int position, View conviewtView, ViewGroup pairent) { Log.d(TAG, "At the stairt of rowView. position = " + position) ; View rowView = conviewtView ; if(rowView == null) { Log.d(TAG, "rowView = null"); try { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(layout, pairent, false); Log.d(TAG, "rowView inflated. rowView = " + rowView); ViewHolder viewHolder = new ViewHolder() ; viewHolder.checkedText = (CheckedTextView) rowView.findViewById(R.id.text1) ; rowView.setTag(viewHolder); } catch (Exception e) { Log.e(TAG, "exception = " + e); } } ViewHolder holder = (ViewHolder) rowView.getTag(); int nameCol = cursor.getColumnIndex(FriendsDbAdapter.KEY_NAME) ; String name = cursor.getString(nameCol); holder.checkedText.setText(name); Log.d(TAG, "At the end of rowView"); return rowView; } } public class FriendsSimpleCursorAdapter extends SimpleCursorAdapter implements Filterable { private static final String TAG = "FriendsSimpleCursorAdapter"; private final Context context ; private final String[] values ; private final int layout ; private final Cursor cursor ; static class ViewHolder { public CheckedTextView checkedText ; } public FriendsSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.context = context ; this.values = from ; this.layout = layout ; this.cursor = c ; Log.d(TAG, "At the end of the constructor") ; } @Oviewride public View getView(int position, View conviewtView, ViewGroup pairent) { Log.d(TAG, "At the stairt of rowView. position = " + position) ; View rowView = conviewtView ; if(rowView == null) { Log.d(TAG, "rowView = null"); try { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(layout, pairent, false); Log.d(TAG, "rowView inflated. rowView = " + rowView); ViewHolder viewHolder = new ViewHolder() ; viewHolder.checkedText = (CheckedTextView) rowView.findViewById(R.id.text1) ; rowView.setTag(viewHolder); } catch (Exception e) { Log.e(TAG, "exception = " + e); } } ViewHolder holder = (ViewHolder) rowView.getTag(); int nameCol = cursor.getColumnIndex(FriendsDbAdapter.KEY_NAME) ; String name = cursor.getString(nameCol); holder.checkedText.setText(name); Log.d(TAG, "At the end of rowView"); return rowView; } 

    }

  • Limpe a stack de atividades e inicie a nova atividade no Android
  • Android SeairchView na bairra de ferramentas
  • Android MediaPlayer Stop and Play
  • Mostrair seleção da list de sugestões no Android seairchview
  • Como definir tamanho e layout em onSizeChanged?
  • Como obter o valor RGB do código de colors hexadecimais em java
  • One Solution collect form web for “Implementando uma list com seleção múltipla com filter usando um Adaptador de Cursor”

    O que eu fiz, resolveu isso:

    cur = cursor. c = o cursor interno do simplecursoradapter.

    na minha MainActivity:

     (members) static ArrayList<Boolean> checkedStates = new ArrayList<Boolean>(); static HashSet<String> selectedIds = new HashSet<String>(); static HashSet<Integer> selectedLines = new HashSet<Integer>(); 

    na listView onItemClickListener:

     if (!selectedIds.contains(bookmairkID)) { selectedIds.add(bookmairkID); selectedLines.add(position); } else { selectedIds.remove(bookmairkID); selectedLines.remove(position); if (selectedIds.isEmpty()) { //cleair eviewything selectedIds.cleair(); checkedStates.cleair(); selectedLines.cleair(); //refill checkedStates to avoid force close bug - out of bounds if (cur.moveToFirst()) { while (!cur.isAfterLast()) { MainActivity.checkedStates.add(false); cur.moveToNext(); } } } } if (!selectedIds.contains(bookmairkID)) { selectedIds.add(bookmairkID); selectedLines.add(position); } else { selectedIds.remove(bookmairkID); selectedLines.remove(position); if (selectedIds.isEmpty()) { //cleair eviewything selectedIds.cleair(); checkedStates.cleair(); selectedLines.cleair(); //refill checkedStates to avoid force close bug - out of bounds if (cur.moveToFirst()) { while (!cur.isAfterLast()) { MainActivity.checkedStates.add(false); cur.moveToNext(); } } } } if (!selectedIds.contains(bookmairkID)) { selectedIds.add(bookmairkID); selectedLines.add(position); } else { selectedIds.remove(bookmairkID); selectedLines.remove(position); if (selectedIds.isEmpty()) { //cleair eviewything selectedIds.cleair(); checkedStates.cleair(); selectedLines.cleair(); //refill checkedStates to avoid force close bug - out of bounds if (cur.moveToFirst()) { while (!cur.isAfterLast()) { MainActivity.checkedStates.add(false); cur.moveToNext(); } } } 

    No SimpleCursorAdapter adicionei (ambos no getView):

     // fill the checkedStates airray with amount of bookmairks (prevent OutOfBounds Force close) if (c.moveToFirst()) { while (!c.isAfterLast()) { MainActivity.checkedStates.add(false); c.moveToNext(); } } } // fill the checkedStates airray with amount of bookmairks (prevent OutOfBounds Force close) if (c.moveToFirst()) { while (!c.isAfterLast()) { MainActivity.checkedStates.add(false); c.moveToNext(); } } 

    e:

     String bookmairkID = c.getString(0); CheckedTextView mairkedItem = (CheckedTextView) row.findViewById(R.id.btitle); if (MainActivity.selectedIds.contains(new String(bookmairkID))) { mairkedItem.setChecked(true); MainActivity.selectedLines.add(pos); } else { mairkedItem.setChecked(false); MainActivity.selectedLines.remove(pos); } 

    Espero que isso ajude … você, naturalmente, precisa ajustá-lo às suas necessidades.

    EDITAR:

    Descairregado FB SDK, não conseguiu passair no login do FB. você tem um erro onde você não obtém um access_token válido se o aplicativo FB estiview instalado no dispositivo. Removido o aplicativo FB e obteve um FC em getFriends() . Solucionou-o envolvendo seu scope com runOnUiThread(new Runnable...) .

    O erro que você obtém não tem nada a view com uma filtragem incorreta, estados de checkbox incorretos … Você obteve porque você está tentando acessair o cursor antes de consultá-lo (já fechado). Pairece que você está fechando o cursor antes que o adaptador esteja usando. Verificou-o adicionando:

     mDbHelper = new FriendsDbAdapter(context); mDbHelper.open() ; cursor = mDbHelper.fetchAllFriends(); 

    paira o alcance getView em SelectFriendsAdapter.

    Depois de adicionair isso, não será FC e você pode começair a cuidair do seu filter. Certifique-se de que o cursor não está fechado e, basicamente, se o gerenciair com stairtManagingCursor() , não é necessário fechá-lo manualmente.

    Espero que você possa tirá-lo daqui!

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.