kain runnie kain runnie - 10 months ago 54
Android Question

How to change background color of elements in ListView(data from ContentProvider)?

I need to change the background color of elements in ListView depends on their status.
lvLinks.getCount() returns the correct value. "If-else" and logs works correctly also. But it doesn't work (doesn't change color of background). Please, help me! Hope you will understand my code.

final Uri CONTACT_URI = Uri.parse("content://com.application.provider.LinkProvider/links");
ListView lvLinks;
Cursor cursor;
SimpleCursorAdapter adapter;

protected void onCreate(Bundle savedInstanceState) {

lvLinks = (ListView) findViewById(R.id.lvLinks);

public void showListView(String order){
cursor = getContentResolver().query(CONTACT_URI, null, null,
null, order);

int to[] = { android.R.id.text1, android.R.id.text2 };
String from[] = {"ref" , "status"};
adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, cursor, from, to);


public void setBackgroundColor(){

for(int i = 0; i < lvLinks.getCount(); i++){
View v = lvLinks.getAdapter().getView(i, null, null);
Cursor cursor = (Cursor) lvLinks.getItemAtPosition(i);
int status = cursor.getInt(cursor.getColumnIndexOrThrow("status"));
Log.d("MYTAG", String.valueOf(status));
if (status == 1){
Log.d("MYTAG", "GREEN");
} else if (status == 2){
Log.d("MYTAG", "RED");
} else if (status == 3){
Log.d("MYTAG", "GRAY");

Answer Source

First: Your adapter should be handling setting the backgroud color of the view when you bind the contact data to that row. SimpleCursorAdapter has no logic to do this. You should extend CursorAdapter and implement bindView() to handle this the way you want.

Second: startManagingCursor() is deprecated. Learn to use the Loader framework, specifically CursorLoader.