Reputation: 1313
I am building a Java android app and I am using realm.io for my database. My problem is I have a RealmList and my Custom ListView adapter only accepts RealmResults. Below is the code and more details.
I have an Chat class that has a RealmList, RealmList, userId and a chatId.
public class Chat extends RealmObject{
private RealmList<Friend> participants;
private RealmList<Message> messages;
@PrimaryKey
private String chatId;
private String userId;
...
}
In my activity where I am trying to display all the messages that the chat has, I can call chat.getMessages() to get all the messages for this chat as a RealmList but my ListView adapter below takes a RealmResult because it extends RealmBaseAdapter
public class MessageAdapter extends RealmBaseAdapter<Message> implements ListAdapter {
private String TAG = getClass().getSimpleName();
public MessageAdapter(Context context,
RealmResults<Message> realmResults,
boolean automaticUpdate) {
super(context, realmResults, automaticUpdate);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listitem_message, parent, false);
}
Message message = getRealmResults().get(position);
if (message != null)
{
((TextView) convertView.findViewById(R.id.message_content)).setText(message.getContent());
DateFormat dateFormat = new SimpleDateFormat("HH:mm", Locale.CANADA);
((TextView) convertView.findViewById(R.id.message_time)).setText(dateFormat.format(message.getTimestamp()));
}
return convertView;
}
public RealmResults<Message> getRealmResults() {
return realmResults;
}
}
Here is where I call it all
RealmList<Message> messages = chat.getMessages();
ListView messageList = (ListView) findViewById(R.id.message_list);
adapter = new MessageAdapter(this, messages, true);
messageList.setAdapter(adapter);
I am open to changing my RealmList to a RealmResult if possible (I have looked and it doesn't seem to be) or If I can use a RealmList in the custom realm adapter that would another solution. Anything to help me move forward would be great help.
thanks
Upvotes: 7
Views: 3295
Reputation: 3575
RealmBaseAdapter has a very simple implementation.
So in the case, you can pass the specific Chat
to you adapter, and overload below methods:
@Override
public int getCount() {
if (realmResults == null || realmResults.size() == 0) {
return 0;
}
return realmResults.first().getMessages().size();
}
@Override
public T getItem(int i) {
if (realmResults == null || realmResults.size() == 0) {
return null;
}
return realmResults.first().getMessages().get(i);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// You message view here
}
Upvotes: 1