I have just started coding an Android App using Android Studio 2.1 and my app was sort of an offline messaging - this is using SQLite Database (basically compose of two tables message and contact).
I am now in my last activity where I need to populate a list of message exchange from the contacts created. I was able to list them but without aesthetics. I would like to set different setBackgroundResource whenever the type is either a LEFT or RIGHT but was struggling to apply it. Below is my code:
MessageRepo - the SQLite DBhelper:
public ArrayList<HashMap<String, String>> getMessageListById(int fromid, int toid) {
SQLiteDatabase db = helper.getWritableDatabase();
String toquery = "SELECT " + MessageModel.messageId +
", " + MessageModel.fromId +
", " + MessageModel.toId +
", " + MessageModel.messageContent +
", 'RIGHT' AS type FROM " + MessageModel.tableMessage +
" WHERE " + MessageModel.toId +
" = ? AND " + MessageModel.fromId +
" = ? ";
String fromquery = "SELECT " + MessageModel.messageId +
", " + MessageModel.fromId +
", " + MessageModel.toId +
", " + MessageModel.messageContent +
", 'LEFT' AS type FROM " + MessageModel.tableMessage +
" WHERE " + MessageModel.fromId +
" = ? AND " + MessageModel.toId +
" = ? ";
String query = toquery +
" UNION " + fromquery +
" ORDER BY " + MessageModel.messageId;
ArrayList<HashMap<String, String>> messageList = new ArrayList<HashMap<String, String>>();
Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(fromid), String.valueOf(toid), String.valueOf(fromid), String.valueOf(toid)});
if (cursor.moveToFirst()) {
do {
HashMap<String, String> messages = new HashMap<String, String>();
messages.put("messageId", cursor.getString(0));
messages.put("messageFromId", cursor.getString(1));
messages.put("messageToId", cursor.getString(2));
messages.put("messageContent", cursor.getString(3));
messages.put("type", cursor.getString(4));
messageList.add(messages);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return messageList;
}
Message Activity - this will display in a ListView but not working as I was intending it to display:
ArrayList<HashMap<String, String>> messageList = messagehandler.getMessageListById(_fromid, _toid);
if (messageList.size() != 0) {
ListView listView = getListView();
if(messageList.contains("RIGHT")) {
listView.setBackgroundResource(R.drawable.right);
} else {
listView.setBackgroundResource(R.drawable.left);
}
ListAdapter adapter = new SimpleAdapter(MessageDetailActivity.this, messageList, R.layout.message, new String[]{"messageFromId", "messageToId", "messageContent"}, new int[]{R.id.FromId, R.id.ToId, R.id.message});
setListAdapter(adapter);
}
I've checked a lot of posts and I can't seem to make it work for me: The constructor ArrayAdapter>>(Context, int, ArrayList>) is undefined Android Alternate row Colors in ListView
Thanks a lot in advance!