无法理解NullPointerException

时间:2013-01-11 12:57:22

标签: listview nullpointerexception android-arrayadapter

我正在尝试ListViews和ArrayAdapters,而且我遇到了一个runTimeException问题,DDMS错误报告告诉我,我在包含“public void onItemClick”的行上有一个NullPointerException,我看不清楚为什么它给了我一个问题。

 package com.example.worksheet2;

import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

ListView listview;

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

    ListView listview = (ListView) findViewById(R.layout.activity_main);
    String[] values = { "A", "B", "C" };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            R.id.menu_settings, values);

    // asign adapter to listview
    listview.setAdapter(adapter);

    listview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            Toast.makeText(getApplicationContext(),
                    "Click ListItem Number " + position, Toast.LENGTH_LONG)
                    .show();

        }
    });

}

   }

这是错误报告

   Caused by: java.lang.NullPointerException
at com.example.worksheet2.MainActivity.onCreate(MainActivity.java:31)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1836)

1 个答案:

答案 0 :(得分:0)

尝试给listview一个id,然后按id找到它。