Wednesday, 6 May 2015

Lesson 9 List with custom objects and adapter ---- 4

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:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
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;
}
}
view rawMainActivity.java hosted with ❤ by GitHub
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!

No comments:

Post a Comment