I am creating a user selected favorites list by flagging items in the SQLite database table that populates a ListView. These flagged items will then populate the favorites ListView. To do this properly, I need to get the rowId in the SQLite database table that the ListView is populated from so I can add the flag. How do I get the rowId?
Here's my current code:
OnItemClickListener:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selected = (String)
mListView.getItemAtPosition(position);
mItemTextView = findViewById(R.id.itemWords);
mItemNumberTextView = findViewById(R.id.itemNumber);
mId = id;
mBookCopied =
mItemHeaderNameTextView.getText().toString();
mItemCategoryNumberCopied = Integer.toString(mCategorySelected + 1);
mItemNumberCopied =
mItemNumberTextView.getText().toString();
mPosition = position + 1;
mCopiedItemListItem = mItemCopied + " " +
mCategoryNumberCopied + ":" + mPosition + "\n\n" + selected;
showMenu(view);
}
});
ItemAdapter:
class ItemAdapter extends ArrayAdapter<String> {
public ItemAdapter(Context context, int resource1, List<String> items) {
super(context, resource1, items);
mContext = context;
mResource1 = resource1;
mItems= items;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItem = convertView;
int pos = position + 1;
if (listItem == null) {
listItem = LayoutInflater.from(mContext).inflate(mResource1, parent, false);
}
mItemNumberTextView = (TextView) listItem.findViewById(R.id.itemNumber);
mItemumberTextView.setText(String.valueOf(pos) + " ");
mItemTextView = (TextView) listItem.findViewById(R.id.itemWords);
mItemTextView.setText(mItems.get(position));
}
return listItem;
}
}
I have tried using the "long id" section of the onItemClickListener but that is just returning the position in the ListView. I need the actual rowId from the database table.
What am I missing here? I appreciate your help.
You need to either
use a CursorAdapater (then long id would then be the ID noting that the id column MUST be called _id (BaseColumns._ID
), you can have a column that aliases rowid e.g. rowid AS _id
).
class ItemAdapter extends ArrayAdapter....
use class ItemAdapter extends CursorAdapter
use a source that includes the id NOT data extracted as ArrayList<String>
but ArrayList<suitable_object_with_id>
and access this via the getItem(position) and use the appropriate object's method to extract the id.
build a complimentary array so that the position can access the id.