-8

I have written code about ListView in Android with Eclipse. I have followed tutorial based on book. But after i copied the code and run with Emulator. The Force Close message appeared. Like the image below:

Force Close

I don't know whats the probem occured. Instead, i have searched the solution in this question: Can't create android onListItemClick method

And my code like the image below: Code

The image below shown the logcat: Logcat Can you give me solutions?

Community
  • 1
  • 1
Ilham
  • 21
  • 9

2 Answers2

2

Make sure your ListView is named <ListView android:id="@android:id/list".

Since you are using a ListActivity (the same goes for ListFragments), this is the only possible name for your ListView.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
0

try this,

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/output"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#758AA7"
        android:padding="1px"
        android:text="Click : "
        android:textColor="#ffffff" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

MainActivity.java

public class MainActivity extends ListActivity {

TextView content;

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

    content = (TextView) findViewById(R.id.output);

    String[] CoffeeShop = {"Creation","Starbucks","Caribou","Mo'Joe" };

    // Define a new Adapter
    // First parameter - Context
    // Second parameter - Layout for the row
    // Third - the Array of data

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

    // Assign adapter to List
    setListAdapter(adapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    super.onListItemClick(l, v, position, id);

// ListView Clicked item index
    int itemPosition = position;

    // ListView Clicked item value
    String itemValue = (String) l.getItemAtPosition(position);

    content.setText("Click : \n  Position :" + itemPosition
            + "  \n  ListItem : " + itemValue);

    }
}
Jignesh Jain
  • 1,518
  • 12
  • 28