3

Can anybody help me? I'm trying to create a ListView in Android, and I'm trying to load items into it using code (not using XML)

Here's the code that I have so far

tweetList = (ListView)this.findViewById(R.id.tweetListView);
        TextView tv;
        for(int i=0;i<20;i++)
        {
            tv = new TextView(this);
            tv.setText("I'm a textView");
            tweetList.addHeaderView(tv);

        }

        tweetList.invalidate();

What am I doing wrong? The items are not showing in runtime

EDIT: I changed the code as per the answers below and here's the code I have now

 tweetList = (ListView)this.findViewById(R.id.tweetListView);
        ArrayAdapter<TextView> aa = new ArrayAdapter<TextView>(this, R.id.tweetListView);
        tweetList.setAdapter(aa);
        TextView tv;
        for(int i=0;i<20;i++)
        {
            tv = new TextView(this);
            tv.setText("I'm a textView");
            //tweetList.addHeaderView(tv);

            aa.add(tv);

        }

        tweetList.invalidate();

I'm getting an exception now

11-10 01:32:16.002: ERROR/AndroidRuntime(867): android.content.res.Resources$NotFoundException: Resource ID #0x7f050030 type #0x12 is not valid

Why am I not able to add them dynamically now?

KamalSalem
  • 495
  • 2
  • 8
  • 21

2 Answers2

7

You need to use ArrayAdapter and add it to the ListView. Then just add elements to the ArrayAdapter dynamically.

For example:

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
tweetList.setAdapter(arrayAdapter);
// ...
arrayAdapter.add("New Item");
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • THANKS DUDE, you ROCK!!!!! I had a mistake in the declaration of the Adapter, once fixed the adapter is working now – KamalSalem Nov 09 '11 at 23:39
  • Now I have another issue, I'm trying to add TextViews to the ListView, is that even possible like we do in WPF? now all the items in the listview appear as 'android.widget.textview@someID' – KamalSalem Nov 09 '11 at 23:42
  • @user974038 try `ArrayAdapter` instead of `ArrayAdapter` – Eng.Fouad Nov 09 '11 at 23:44
  • What is 'context' out here?? Because 'this' doesn't work because it is not of type android.content.Context – Menno van Leeuwen Mar 06 '15 at 20:02
0

The header view is just a header, its not the items in the list. Your listview receives its contents through an Adapter. The ListView does not keep Views for its children, but its the adaptor who creates them and fills them with the appropiate data when they need to be shown at the screen. Search for basic tutorials on how to do this, there are lots out there; and remember adapters are the key.

K-ballo
  • 80,396
  • 20
  • 159
  • 169