0
我想從ListView中的選定項目設置ContextMenu的標題。然而,每次我在模擬器上運行它,它崩潰,我必須強制關閉它。 DDMS顯示引發了未捕獲的java.lang.NullPointerException。我的DbTest.java類會出現問題嗎?我已經定義了DbTest.java類中的所有數據庫操作。來自ListView的ContextMenu的標題項目
注:異常可能拋出在這條線: -
Cursor mCursor = (Cursor) getListAdapter().getItem(info.position);
請看看我的代碼,並指出錯誤。
package com.tintin.prototype_2;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
public class Contact_LA extends ListActivity {
DbTest db;
SimpleCursorAdapter dataAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
db = new DbTest(this);
displayList();
}
public void onResume(){
Cursor newCursor = db.getallContacts();
dataAdapter.changeCursor(newCursor);
super.onResume();
}
public void displayList(){
Cursor cursor = db.getallContacts();
String columns[] = new String[] {db.Name, db.Number};
int to[] = new int[] {R.id.textView1, R.id.textView2};
dataAdapter = new SimpleCursorAdapter(this, R.layout.check_layout, cursor, columns, to, 0);
//ListView lv = (ListView) findViewById(R.id.list);
ListView lv = getListView();
lv.setAdapter(dataAdapter);
registerForContextMenu(lv);
Button b = (Button) findViewById(R.id.AddContact);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
startActivity(new Intent(Contact_LA.this, Contact_Add.class));
}
});
db.close();
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info;
try{
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
}catch(ClassCastException e){
Log.v("BAD", "Bad Info");
return;
}
Cursor mCursor = (Cursor) getListAdapter().getItem(info.position);
if(mCursor == null)return;
menu.setHeaderTitle(mCursor.getString(mCursor.getColumnIndex("Name")));
menu.add(0, v.getId(), 0, "Delete");
}
}
它顯示了一個錯誤:方法getMenuInfo()是未定義類型ContextMenu.ContextMenuInfo – tintin