不幸的是,Listview已经停止工作(android错误)

时间:2017-05-22 19:14:37

标签: java android listview

我遇到了问题"很遗憾,您的列表视图已停止工作"当我使用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>

对于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);
    }
}

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

1 个答案:

答案 0 :(得分:1)

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

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