Good day. I have a ListView associated with an adapter where the source is a SQLite table, I need to know the programmatically select the ListView element, knowing the id row. I saw a bunch of examples of selection by position, but I need to select by id records from SQLite.

    2 answers 2

    In fact, the task is reduced to finding a position in the list by the id of the list item and applying the found position: ListView.setSelection(position)

    There are 2 ways to bind id to position:

    1) Hand to hand to find the position of the list by id, such as:

     public int getPositionById(long id) { for (int position=0; position<mList.size(); position++) if (mList.get(position).getId() == id) return position; return 0; } 

    the way is frankly crappy, especially in the case when the Cursor is the backend

    2) Method 2 is better:

     public View getView (int position, View convertView, ViewGroup parent) { //blah-blah convertView.setTag(convertView.getId(),position); //позицию храним в теге return convertView; } 

    Then you can already find through the tag:

     int getItemPosition(View view) { return view.getTag(view.getId()); } 

    In the case of a CursorAdapter usually instead of getView() , the pair newView()/bindView() , which does not change the essence - in the source code of the CursorAdapter() it is written like this:

     /** * @see android.widget.ListAdapter#getView(int, View, ViewGroup) */ public View getView(int position, View convertView, ViewGroup parent) { if (!mDataValid) { throw new IllegalStateException("this should only be called when the cursor is valid"); } if (!mCursor.moveToPosition(position)) { throw new IllegalStateException("couldn't move cursor to position " + position); } View v; if (convertView == null) { v = newView(mContext, mCursor, parent); } else { v = convertView; } bindView(v, mContext, mCursor); return v; } 

    So tag insertion can be safely inserted into bindView()

      You can bypass the entire cursor and save in some HashMap matching id (key) and the cursor position. And when you need to search, then get in this HashMap by id position, well, select it in the listView