使用Cursor Adapter实现带有过滤器的多个select的列表视图

时间:2012-02-22 17:31:52

标签: android android-listview simplecursoradapter

此问题Android: Wrong item checked when filtering listview中讨论了此问题。总结该问题,当使用带有CursorAdapter和过滤器的列表视图时,在过滤后的列表中选择的项目将在删除过滤器后丢失其选择,而是选择未过滤列表中该位置的项目。

使用上面链接问题中的代码示例,我们应该在哪里放置代码来标记复选框。我相信它应该在CustomCursorAdapter的getView()方法中,但我不确定。另外,我们如何访问包含自定义适配器类中所有selectedIds的HashSet,因为它将在保存列表的主活动中初始化和修改。

我实施ListView的活动

@Override
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();
      startManagingCursor(c);

      Log.v(TAG, "fetchAllFriends Over") ;


      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://stackoverflow.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://stackoverflow.com/questions/2002607/android-how-to-text-filter-a-listview-based-on-a-simplecursoradapter
     */

       adapter.setFilterQueryProvider(new FilterQueryProvider() {
            public Cursor runQuery(CharSequence constraint) {
                // Search 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();

  }


    @Override   
    protected void onListItemClick(ListView parent, View v, int position, long id) {

        String item = (String) getListAdapter().getItem(position);
        Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();

        //gets the Bookmark ID of selected position
         Cursor cursor = (Cursor)parent.getItemAtPosition(position);
         String bookmarkID = cursor.getString(0);

         Log.d(TAG, "mListener -> bookmarkID = " + bookmarkID);

         Log.d(TAG, "mListener -> position = " + position);

 //        boolean currentlyChecked = checkedStates.get(position);
 //        checkedStates.set(position, !currentlyChecked);


         if (!selectedIds.contains(bookmarkID)) {

             selectedIds.add(bookmarkID);
             selectedLines.add(position);

         } else {

             selectedIds.remove(bookmarkID);
             selectedLines.remove(position);


             }

     }



  private TextWatcher filterTextWatcher = new TextWatcher() {

      public void afterTextChanged(Editable s)  {

      }

      public void beforeTextChanged(CharSequence s, int start, int count, int after)    {

      }

      public void onTextChanged(CharSequence s, int start, int before, int count)   {
          Log.v(TAG, "onTextChanged called. s = " + s);
          adapter.getFilter().filter(s);
      }
  };

  @Override
  protected void onDestroy()    {
        super.onDestroy();
        filterText.removeTextChangedListener(filterTextWatcher);
  }

我的自定义光标适配器:

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") ;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)   {
    Log.d(TAG, "At the start of rowView. position = " + position) ;
    View rowView = convertView ;
    if(rowView == null) {
        Log.d(TAG, "rowView = null");
        try {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(layout, parent, 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;

}

}

2 个答案:

答案 0 :(得分:1)

我做了什么解决了它:

cur = cursor。 c = simplecursoradapter内部游标。

我的MainActivity中的

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

if (!selectedIds.contains(bookmarkID)) {

    selectedIds.add(bookmarkID);
    selectedLines.add(position);


} else {

     selectedIds.remove(bookmarkID);
     selectedLines.remove(position);



 if (selectedIds.isEmpty()) {
    //clear everything
        selectedIds.clear();
        checkedStates.clear();      
        selectedLines.clear();

        //refill checkedStates to avoid force close bug - out of bounds
        if (cur.moveToFirst()) {
            while (!cur.isAfterLast()) {    
                MainActivity.checkedStates.add(false);

                cur.moveToNext();
            }
        }                       

 }

在我添加的SimpleCursorAdapter中(都在getView中):

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

String bookmarkID = c.getString(0);
        CheckedTextView markedItem = (CheckedTextView) row.findViewById(R.id.btitle);
        if (MainActivity.selectedIds.contains(new String(bookmarkID))) {
            markedItem.setChecked(true);
            MainActivity.selectedLines.add(pos);

        } else {
            markedItem.setChecked(false);
            MainActivity.selectedLines.remove(pos);
        }

希望这会有所帮助......你当然需要根据自己的需要进行调整。

修改

下载的FB SDK,无法通过FB登录。你有一个错误,如果在设备上安装了FB应用程序,你就无法获得有效的access_token。删除了FB应用程序,并在getFriends()中获得了一个FC。通过用runOnUiThread(new Runnable...)包装其范围来解决它。

你得到的错误与糟糕的过滤,错误的复选框状态无关......你得到它,因为你在查询之前尝试访问游标(已经关闭)。 在适配器使用之前,您似乎正在关闭光标。通过添加:

验证它
mDbHelper = new FriendsDbAdapter(context);

        mDbHelper.open() ;
        cursor = mDbHelper.fetchAllFriends();

到SelectFriendsAdapter中的getView范围。

添加后,它不会FC,你可以开始照顾你的过滤器。 确保光标未关闭,基本上如果您使用startManagingCursor()进行管理,则无需手动关闭它。

希望你能从这里拿走它!

答案 1 :(得分:0)

adapter.setFilterQueryProvider(new FilterQueryProvider() {
            public Cursor runQuery(CharSequence constraint) {

                return db.fetchdatabyfilter(constraint.toString(), "name");

                }
        });