0

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 ?

1
  • Hold these values in a pojo class and pass the object of pojo class to List's adapter. Commented Mar 20, 2015 at 9:25

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.