Skip to content

Lots of Lists: Part 2, List with custom objects and adapter

Putting it all together

We’ve defined the project, layouts, objects, and adapter. Now that we have our new tools, we need to put them together to achieve our goal.

In order to make use of our new adapter, we’ll need to go back to our original Activity. We need to do the following:

  • Reference the ListView in the MainActivity
  • Bind the ListView to the NewsEntryAdapter
  • Populate the NewsEntryAdapter with NewsEntry objects

Here is the code we came up with:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
package com.learnandroid.listviewtutorial.adapter;
 
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
 
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup the list view
final ListView newsEntryListView = (ListView) findViewById(R.id.list);
final NewsEntryAdapter newsEntryAdapter = new NewsEntryAdapter(this, R.layout.news_entry_list_item);
newsEntryListView.setAdapter(newsEntryAdapter);
// Populate the list, through the adapter
for(final NewsEntry entry : getNewsEntries()) {
newsEntryAdapter.add(entry);
}
}
private List<NewsEntry> getNewsEntries() {
// Let's setup some test data.
// Normally this would come from some asynchronous fetch into a data source
// such as a sqlite database, or an HTTP request
final List<NewsEntry> entries = new ArrayList<NewsEntry>();
for(int i = 1; i < 50; i++) {
entries.add(
new NewsEntry(
"Test Entry " + i,
"Anonymous Author " + i,
new GregorianCalendar(2011, 11, i).getTime(),
i % 2 == 0 ? R.drawable.news_icon_1 : R.drawable.news_icon_2
)
);
}
return entries;
}
}

And that’s it! There are a lot more options to explore with ListViews and Adapters not covered here (yet.)

Download this project now: [ Git | ZIP ]

Consider leaving a comment if you would like to see other details covered from this article, any mistakes, or general questions. Thanks for reading!

{ 2 } Comments

  1. zAo | July 1, 2012 at 9:02 am | Permalink

    Hi, should
    android:text=”@string/hello” />
    Not be
    android:text=”@string/hello_world” />

    Thanks

  2. Gav Newalkar | July 2, 2012 at 3:25 am | Permalink

    Excellent tutorial. Thanks for the explanations, this is awesome.

{ 1 } Trackback

  1. [...] managed to implement a great listview that I found here http://www.learn-android.com/2011/11/22/lots-of-lists-custom-adapter/comment-page-1/ but I can’t seem to add an onclicklistener I just want to be able to do an action when I [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *