Accessing SQLite values from SimpleCursorAdapter
-
27-10-2019 - |
Question
I have a SQLite table called "Nodes" with a set of all nodes (each node has multiple properties).
In an activity, I use an extension of SimpleCursorAdapter to display a subset of the Nodes table, based on a SQL query, passing it the Cursor over the table of results (from the query).
{id_long, name_string, description_string, nodetype_enum_toString...}
1, "home", "home_desc", "cool"
2, "item1", "item1_desc", "warm"
3, "item2", "item2_desc", "hot"
4, "item3", "item3_desc", "warm"
5, "item4", "item4_desc", "hot"
I want to modify each of the list items in my ListActivity such that it displays a different color based on whether an item is cool, warm or hot. I have a small (empty) view, but it's always defaulting to white (the 'else' portion).
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
if (convertView == null) convertView = View.inflate(mContext, R.layout.viewstack_item, null);
View nodetype_view = (View) convertView.findViewById(R.id.nodetype_view);
mGenCursor_cur = mDataHelper_db.getAll();
mGenCursor_cur.moveToPosition(position);
Log.i("test", "node type key " + mGenCursor_cur.getColumnIndex(DataHelper.NODES_TYPE_KEY));
String type_nt = mGenCursor_cur.getString(mGenCursor_cur.getColumnIndex(DataHelper.NODES_TYPE_KEY));
String name_str = mGenCursor_cur.getString(mGenCursor_cur.getColumnIndex(DataHelper.NODES_NAME_KEY));
Log.i("getView", title_str + "typeis " + type_nt + " at position " + position);
if (prio_np.equals(NodePrio.HIGH.toString())) {
Log.i("prio_np", "high red");
prioView_view.setBackgroundColor(Color.RED);
} else if (prio_np.equals(NodePrio.NORMAL.toString())) {
Log.i("prio_np", "norm magenta");
prioView_view.setBackgroundColor(Color.MAGENTA);
} else {
Log.i("prio_np", "else (low) white");
prioView_view.setBackgroundColor(Color.WHITE);
}
mGenCursor_cur.close();
bindView(convertView, mContext, getCursor());
return(convertView);
}
My issue is that while the cursor passed to the SimpleListAdapter will contain the _IDs (I assume) of the corresponding nodes in the subset I want, the position parameter in getView is local to the subset, so I can't cross-reference it with the Nodes table. Am I missing some easy technique?
As always, any help appreciated.
comment 4 of the marked answer helped me solve this: storing the cursor that was passed to the SimpleCursorAdapter as a member variable, then using move to position, and getLong:
mCursor_cur.moveToPosition(position);
long id = mCursor_cur.getLong(0);
where position is the local parameter in the getView() method, and 0 is used for getLong because the db_id is the first column in the cursor passed to the SimpleCursorAdapter
Solution
in java == should not be used for string comparison
string1.equals(string2)
is what your are looking for
see here for further info