1

I am creating simple ListView in my user class, but everytime when I launch my application I get error in the logcat , which gives

FATAL EXCEPTION: main
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

I don't know why in the ArrayAdapter causes the error.I just followed this tutorial

http://www.tutorialspoint.com/android/android_list_view.htm

Thank you in advance.

package com.example.myemployee;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;



public class User extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.user_layout);



        String[] countryArray = {"India", "Pakistan", "USA", "UK"};
        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                R.layout.user_txtview, countryArray);

        ListView listView = (ListView) findViewById(R.id.lstview_user);
        listView.setAdapter(adapter);

    }

}

user_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent" >


    <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/lstview_user" android:layout_gravity="center_horizontal"/>
</LinearLayout>

user_txtview.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

</TextView>
mfaisalhyder
  • 2,250
  • 3
  • 28
  • 38
jemz
  • 4,987
  • 18
  • 62
  • 102

1 Answers1

2

Change this

ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.user_txtview, countryArray);

to this

ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listitem,R.id.textview, countryArray);

listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/textview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</TextView>

The documentation says:

By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

sandeepmaaram
  • 4,191
  • 2
  • 37
  • 42
williamj949
  • 11,166
  • 8
  • 37
  • 51