I'm newbie, I have read the article from here How to do custom ListView with colorful items' backgrounds? and I try to do some tasks: I have a table in Sqlserver contains list of table, each table have the status(0,1,2,3). My problem is how to apply to each status a color. Here is my Code:
try {
Statement stmt2 = conn.createStatement();
rs2 = stmt2.executeQuery(command);
ArrayList<HashMap<String, String>> data = null;
data = new ArrayList<HashMap<String, String>>();
while (rs2.next()) {
HashMap<String, String> datanum = new HashMap<String, String>();
datanum.put("A", rs2.getString(name));
datanum.put("B", rs2.getString(code));
datanum.put("C", rs2.getString("TTBan"));
// datanum.put("D", rs.getString("GiaVon"));
data.add(datanum);
}
String[] from = { "A", "C" };
int[] views = { R.id.txt_Name, R.id.txt_image_gridview};
SAD = new SimpleAdapter(this, data,
R.layout.fragment_activity_list_table, from, views)
{
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
image = (TextView)findViewById(R.id.txt_image_gridview);
View view = super.getView(position, convertView, parent);
String valueChosen = String.valueOf(gridviewTable.getItemAtPosition(position));
String[] k = valueChosen.split(", B=");
String h = k[1];
// String[] tables = h.split(",");
// table = tables[0];
// System.out.println("Ma Ban la: " + table);
String[] g = h.split(", C=");
String l = g[1];
String status = l.replace("}", "");
System.out.println("aaaaaaaaaaaaaaaaaaa " + status);
if (status == "0" || status == null) {
view.setBackgroundColor(Color.GREEN);
}if(status == "1"){
view.setBackgroundColor(Color.YELLOW);
}if(status == "2"){
view.setBackgroundColor(Color.CYAN);
}if(status == "3"){
view.setBackgroundColor(Color.RED);
}
return view;
}
}
;
} catch (Exception e) {
String err = (e.getMessage() == null) ? "Error occured" : e
.getMessage();
Log.e("Erro", err);
}
gridviewTable.setAdapter(SAD);
I have found the solution, The code is correct but I was wrong when i used if statement. So I edited it like this and everything is fine:
Replace this
if (status == "0" || status == null) {
view.setBackgroundColor(Color.GREEN);
}if(status == "1"){
view.setBackgroundColor(Color.YELLOW);
}if(status == "2"){
view.setBackgroundColor(Color.CYAN);
}if(status == "3"){
view.setBackgroundColor(Color.RED);
}
With this:
if (status.equals(String.valueOf(0))) {
view.setBackgroundColor(Color.RED);
} else if(status.equals(String.valueOf(1))){
view.setBackgroundColor(Color.GRAY);
}else if(status.equals(String.valueOf(2))){
view.setBackgroundColor(Color.YELLOW);
}else if(status.equals(String.valueOf(3))){
view.setBackgroundColor(Color.CYAN);
}else{
view.setBackgroundColor(Color.GREEN);
}
return view;
}