android Listview not showing anything

10,167

Solution 1

Your problem is that you have the same layout R.layout.main for two different use.
You set the content view as setContentView(R.layout.main); where your ListView is but you also use this layout with your adapter as new ArrayAdapter<String>(this, R.layout.main, myItems);.
So with your code, you don't have any item layout to display your array myItems. You need to create another layout as R.layout.item_layout with a TextView inside (or use an android layout like android.R.layout.simple_list_item_1) for your adapter.

Note: to avoid some bugs with ListView, you have also to set the height to match_parent or fill_parent

Solution 2

Try this for your adapter:

ArrayAdapter<String> adapter= 
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myItems);

The adapter has to inflate a TextView. You can make your own TextView (if you want to customize it) in XML.

Then it will be:

ArrayAdapter<String> adapter= 
new ArrayAdapter<String>(this, R.layout.yourcustomtextview, myItems);
Share:
10,167
daniel
Author by

daniel

Updated on June 13, 2022

Comments

  • daniel
    daniel almost 2 years

    I am working on a first basic android app as a university project and I have an array list of names. I want it to be put into a ListView. The problem I have is nothing appears when I bring in the ListViewunder the xml document. I don't get the basic template for item1, sub item 1 etc. Then when I set up the array to play in the list view still empty list. Below I have the xml document

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <ListView
            android:layout_width="wrap_content"
            android:layout_height="277dp"
            android:id="@+id/listView" android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true" android:layout_marginTop="7dp"
            android:layout_alignParentBottom="true"/>
    </RelativeLayout>
    

    then here is the java code:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateListView();
    }
    
    private void populateListView() {
        String[] myItems = {"frank","george","alice", "anna"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.main, myItems);
        ListView list = (ListView)findViewById(R.id.listView);
        list.setAdapter(adapter);
    }