不幸的是,列表视图已停止工作(安卓错误)



我在使用 android 模拟器运行代码时遇到问题"不幸的是,您的列表视图已停止工作"。请看一下我的代码,谢谢!

对于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>

对于主活动.java:

    public class MainActivity extends AppCompatActivity {
    ArrayAdapter<CharSequence>adapter;
    TextView tvSelection;
    ListView lvLocation;
    String []strArray;
    String []superHeros = {"1. Batmann 2. SpiderMan", "1. Peter Pann2. Superman",
            "1. IronMann2. 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);
    }
}

对于字符串.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>
adapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_list_item_1, strArray);

onCreate 方法中的这一行采用 strArray,该数组未初始化,因此其值为 null。现在,当您将具有空数据的适配器设置为列表视图时,它会崩溃。

最新更新