My android app has a simple chat function. The chats are stored in the on-board SQLite database. I am using a ListView with a SimpleCursorAdapter to display the chats. This is what I have:
public class Chat extends Fragment {
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.chat, container, false);
return rootView;
}
@Override
public void onViewCreated(View rootView, Bundle savedInstanceState){
super.onViewCreated(rootView, savedInstanceState);
displayChats();
}
public void displayChats(){
DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
Cursor chatCursor = databaseHelper.getChatsCursor();
String[] fromColumns = {"messageInfo","messageText"};
int toViews{R.id.message_info, R.id.message_text};
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.line_of_chat, chatCursor, fromColumns, toViews, 0);
ListView listView = (ListView) rootView.findViewById(R.id.chat_text_display);
listView.setAdapter(simpleCursorAdapter);
databaseHelper.close();
}
}
I have a chat model that has a boolean, named localFlag, as one of its fields. If the chat is sent from the device, localFlag is set as true (or 1), if the chat is received from external to the device, localFlag is set as false (or 0).
My SQL call:
public static final String GET_ALL_CHATS = "select _id, localFlag, messageText, messageInfo from ChatTable";
public Cursor getChatsCursor(){
SQLiteDatabase sqliteDB = this.getReadableDatabase();
return sqliteDB.rawQuery(GET_ALL_CHATS, null);
}
What I want to do is if the local flag is set, I would like to use this:
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.outgoing_line_of_chat, chatCursor, fromColumns, toViews, 0);
and if the local flag is not set, I would like to use this:
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.incoming_line_of_chat, chatCursor, fromColumns, toViews, 0);
Notice I want to use R.layout.outgoing_line_of_chat
vs R.layout.incoming_line_of_chat
.
How can I go about accomplishing this?
Use getItemViewType()
and getViewTypeCount()
in your adapter to inform ListView
that there are different row types being displayed, so that it can provide the proper view as the convertView
argument to getView()
. Refer to this answer, and also to a video called The World of ListView for a fuller explanation.
EDIT
You will have to subclass SimpleCursorAdapter
(although you might want to subclass CursorAdapter
instead) in order to override those methods.
Aside: you may want to consider using RecyclerView
instead of ListView
. The principle is the same, but with a RecyclerView
adapter you only need to implement getItemViewType()
.