Reputation: 1330
I have this code in android that prints data from database to log.
List<Message> messages = db.getAllMessages();
for (Message mg : messages)
{
String log = "Id: "+mg.getID()+", Message: " + mg.getMessage() + ", Time: " + mg.getDate();
// display everything on log
Log.d("", log);
}
How do I display it in a ListView instead of printing to log ?
Upvotes: 0
Views: 1723
Reputation: 20080
First, create a list that you would store your values in if not already. For example:
private ArrayList<String> YOUR_LIST = new ArrayList<>();
Now, use this in an array adapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, YOUR_LIST);
Finally, set your adapter:
ListView listView = (ListView) findViewById(R.id.YOUR_LISTVIEW);
listView.setAdapter(adapter);
What you could do in your example, is something like this:
List<Message> messages = db.getAllMessages();
ArrayList<String> YOUR_LIST = new ArrayList<>();
for (Message mg : messages) {
String log = "Id: " + mg.getID() + ", Message: " + mg.getMessage() + ", Time: " + mg.getDate();
YOUR_LIST.add(log);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, YOUR_LIST);
ListView listView = (ListView) findViewById(R.id.YOUR_LISTVIEW);
listView.setAdapter(adapter)
Upvotes: 1