Mona Mona - 1 year ago 64
Android Question

Unfortunately, Listview has stopped working (android error)

I'm experiencing the problem "Unfortunately, your listview has stopped working" when i was using the android emulator to run my codes.
Please take a look at my codes thanks!

For activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.it3783.listview.MainActivity">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Choose a location..."/>

<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:id="@+id/spLocations"></ListView>

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@+id/superHerosTV"
/>

</LinearLayout>


For MainActivity.java:

public class MainActivity extends AppCompatActivity {

ArrayAdapter<CharSequence>adapter;
TextView tvSelection;
ListView lvLocation;

String []strArray;
String []superHeros = {"1. Batman\n 2. SpiderMan", "1. Peter Pan\n2. Superman",
"1. IronMan\n2. Peter Pan", "1. SnowWhite \n2. Gingerbreadman"};

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

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

tvSelection = (TextView) findViewById(R.id.superHerosTV);
lvLocation = (ListView) findViewById(R.id.spLocations);

Resources myRes = this.getResources();
strArray = myRes.getStringArray(R.array.locationArea);

lvLocation.setAdapter(adapter);

lvLocation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String text = strArray[position];
tvSelection.setText(text);
}
});

adapter = ArrayAdapter.createFromResource(this, R.array.locationArea, android.R.layout.simple_list_item_1);
}
}


For strings.xml:

<resources>
<string name="app_name">ListView</string>

<string-array name="locationArea">

<item>North</item>
<item>South</item>
<item>East</item>
<item>West</item>

</string-array>

</resources>

Answer Source
adapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_list_item_1, strArray);

This line in your onCreate methods takes the strArray, which is not initialized so its value is null. Now when you set the adapter with null data to the listview, it crashes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download