Search code examples
androidlistviewandroid-contentprovider

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) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.history);

    lvLinks = (ListView) findViewById(R.id.lvLinks);
    showListView(null);
    setBackgroundColor();
    lvLinks.setOnItemClickListener(this);
}


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

    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);
    lvLinks.setAdapter(adapter);


}

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){
            v.setBackgroundColor(Color.GREEN);
            Log.d("MYTAG", "GREEN");
        } else if (status == 2){
            v.setBackgroundColor(Color.RED);
            Log.d("MYTAG", "RED");
        } else if (status == 3){
            v.setBackgroundColor(Color.GRAY);
            Log.d("MYTAG", "GRAY");
        }
    }
}

Solution

  • 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.