Q:

How to set different color to each row

How can I set different color to each row? The data are get from SQLite to table layout and the number of rows are not fixed. I want to set the first row to green, second to red, third row to red again...I have declared the color on color.xml, but they are not working...
DisplayData.java 
// outer for loop
for (int i = 0; i < rows; i++) {

    TableRow row = new TableRow(this);
    row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));

    // inner for loop
    for (int j = 0; j < cols; j++) {

        TextView tv = new TextView(this);
        tv.setLayoutParams(new TableRow.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        ));
       // tv.setBackgroundResource(R.drawable.cell_shape);
        tv.setGravity(Gravity.CENTER);
        tv.setTextSize(18);
        tv.setPadding(0, 5, 0, 5);

        tv.setText(c.getString(j));

        row.addView(tv);
        row.setBackgroundResource(R.drawable.color);

        row.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent intent = new Intent(DisplayData.this, UpdatePage.class);
                intent.putExtra("name", name2);
                intent.putExtra("date",date2);
                startActivity(intent);
            }
        });

    }

    c.moveToNext();

        table_layout.addView(row);

    }
    sqlcon.close();
}

    }

color.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <resources xmlns:android="http://schemas.android.com/apk/res/android">
        <color android:name="green">#00ff00</color>
        <color android:name="red">#FF0000</color>
    </resources>

</LinearLayout>

A:

There's probably a much nicer solution, but I guess this could work:
// outer for loop
   int colorIndex = 0;

   for (int i = 0; i < rows; i++) {

        if (index == 0)
        {
            //set background
            row.setBackgroundColor(getResources().getColor(R.color.some_color));
            index++;
        }

        else if (index == 1)
        {
            //set background
            row.setBackgroundColor(getResources().getColor(R.color.some_other_color));
            index++;
        }
        if (index == 2)
        {
            //set background
            row.setBackgroundColor(getResources().getColor(R.color.yet_another_color));
            index = 0;
        }
}

