Saturday, April 19, 2014

java.lang.IllegalStateException: ArrayAdapter requires the resources ID to be a TextView

Recently i was creating ListActivity for my Android application. After doing the necessary work, when i try to run the application, i was spatted with the error java.lang.IllegalStateException: ArrayAdapter requires the resources ID to be a TextView. What causes this issue?.

When you are passing an layout to the constructor like this new ArrayAdapter(this, R.layout.list_employee, this.employeeList). You need to make sure that your layout file list_employee wasn't wrapped by another layout. Unfortunately, my layout was wrapped with the RelativeLayout , which results in the above exception.

Below is the layout of my activity, which results in the exception

 <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"  
  >  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="@string/employee_list_heading" />  
 </RelativeLayout>  

To Resolve the issue, i have just removed the layout element which just wrapped my TextView, and modified my XML as below

 <?xml version="1.0" encoding="utf-8"?>  
 <TextView xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="wrap_content"   
   // other attributes of the TextView  
 />  

Happy Programming...!!!