Yo man Yo man - 1 month ago 9
Java Question

Why isn't my list populating in Android Studio?

I want to create a simple list of items (names, in this case) in an application. I'm using Android Studio and as far as I know, I have written everything correctly and I don't know where I have gone wrong. Here's my

XML
file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.scott.exampleapp.test_page">

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/list_view"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</RelativeLayout>


And my corresponding Java file:

package com.example.scott.exampleapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class test_page extends AppCompatActivity {

String[] exampleArray = new String[]{"Scott", "Steffi", "Liam", "Jonny", "Zac"};

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

ListView listView = (ListView) findViewById(R.id.list_view);

ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_test_page, exampleArray);

listView.setAdapter(adapter);
}
}

Answer

your are passing the wrong layout to adapter , it should be the inbuild simple_list_item_1 layout.

use this

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

here new ArrayAdapter<String>(this, R.layout.activity_test_page, exampleArray); you are using the activity layout , but adapter uses it's own layout to populate listitems accordingly so either you can use the inbuild layout or you can also create a separate one (extra coding + extra beauty )

plus you don't have to do this

 String[] exampleArray = new String[]{"Scott", "Steffi", "Liam", "Jonny", "Zac"};

you can use this without new String[] at the time of declaration with initialization

 String[] exampleArray = {"Scott", "Steffi", "Liam", "Jonny", "Zac"};