我正在尝试使用 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)