Search code examples
javaandroidlistviewandroid-listviewlistadapter

Can I dynamically populate a ListView in an ActionBarActivity?


I saw a number of examples that populated ListViews in a ListActivity. I want both a dynamically populated ListView, but in an activity with an action bar.

So instead of (as in the examples I've seen):

public class EditHolidaysActivity extends ListActivity {

I have:

public class EditHolidaysActivity extends ActionBarActivity {

But the setListAdapter method cannot be resolved. What method might I use to populate the ListView? Here are snippets of the xml and java:

    ...
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Anni"
        android:id="@+id/chkbxAnniversary"
        android:checked="false"
        android:onClick="saveAnniPref"/>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

Java:

public class EditHolidaysActivity extends ActionBarActivity {
    public static final String PREFS_NAME = MainActivity.PREFS_NAME;
    private final static String TEXT_DATA_KEY = "textData";
    private CommentsDataSource datasource;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_holidays);

        datasource = new CommentsDataSource(this);
        datasource.open();

        List<Comment> values = datasource.getAllComments();

        // use the SimpleCursorAdapter to show the
        // elements in a ListView
        ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
                android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
    }

Thank you!


Solution

  • Something like this:

    public class EditHolidaysActivity extends ActionBarActivity {
    public static final String PREFS_NAME = MainActivity.PREFS_NAME;
    private final static String TEXT_DATA_KEY = "textData";
    private CommentsDataSource datasource;
    private ListView lstView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_holidays);
    
        lstView = (ListView)findViewById(R.id.list);
    
        datasource = new CommentsDataSource(this);
        datasource.open();
    
        List<Comment> values = datasource.getAllComments();
    
        // use the SimpleCursorAdapter to show the
        // elements in a ListView
        ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
                android.R.layout.simple_list_item_1, values);
        lstView.setAdapter(adapter);
    }