Search code examples
javaandroidandroid-layoutandroid-listviewandroid-sdk-2.3

Exception when using array adapter and listView


This is my activity class, copied by a book (Apress, "Pro Android 5"), that, by side, is a book full of typos in the code...

package com.example.list1;

import java.util.ArrayList;
import java.util.Arrays;

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

public class MainActivity extends Activity {

    private ListView listView1;
    private ArrayAdapter<String> listAdapter1;

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



        // Create an object of type ArrayList from an array of strings
        String[] someColors = new String[] { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet", "Black", "White"};
        ArrayList<String> colorArrayList = new ArrayList<String>();
        colorArrayList.addAll( Arrays.asList(someColors) );

        // Use values from colorArraylist as values for each text1 'sbuView' used by the listView
        listAdapter1 = new ArrayAdapter<String>(this, android.R.id.text1, colorArrayList);


        // Tell to the listView to take data and layout from our adapter
        listView1 = (ListView) findViewById(R.id.listView1);        
        listView1.setAdapter( listAdapter1 );

    }
}

And this is my layout file

<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.list1.MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" >

    </ListView>   

</RelativeLayout>

When I save, Eclipse give me no problem. When I run the app crash and from logcat I can see an exception that i'm not able to understand/debug

08-04 13:43:34.382: E/AndroidRuntime(888):  
android.content.res.Resources$NotFoundException: File  from xml type layout resource ID #0x1020014

What am I doing wrong?


Solution

  • Actually you initialize arrayAdapter with view id instead of layout id.That's why you are getting this error.use this

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