我在尝试创建新的OnItemLongClickListener的行中不断获得空指针异常。基本上,我想要的是从ListView创建一个对话框,显示选项,我希望它们是可选择的。这是我的代码:
private void viewPatientOptions(){
LayoutInflater factory4 = LayoutInflater.from(this);
final View textEntryView4 = factory4.inflate(R.layout.patient_dialog, null);
patientOptionV = (ListView) findViewById(R.id.patientOptions);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
new ArrayList<String>
(Arrays.asList(getResources().getStringArray(R.array.patientOptions))));
patientOptionV.setAdapter(adapter);
patientOptionV.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
String itemValue = (String) patientOptionV
.getItemAtPosition(position);
if(itemValue.equals("New Test")){
Log.i(TAG, "Viewing Tools for new test");
viewTools();
}
if(itemValue.equals("Gallery")){
Log.i(TAG, "Viewing Gall");
viewGall();
}
else
//Do nothing
return true;
}
});
mViewPatientOptionsDialog = new AlertDialog.Builder(this)
.setTitle("Patient ID: "+ PATIENT_ID_NUM)
.setIcon(0)
.setView(textEntryView4)
.setNegativeButton(
R.string.dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i(TAG, "Caption dialog: CANCEL...");
openView(patientList);
}
})
.create();
mViewPatientOptionsDialog.show();
}
更新:不能回答我自己的问题,但我解决了问题。谢谢 这是我的答案:
让它发挥作用。想通了一个AlertDialog.Builder有它自己的set items方法。不知道我的第一种方法究竟出了什么问题,但这段代码现在正在运行:
private void viewPatientOptions(){
LayoutInflater factory4 = LayoutInflater.from(this);
final View textEntryView4 = factory4.inflate(R.layout.patient_dialog, null);
mViewPatientOptionsDialog = new AlertDialog.Builder(this)
.setTitle("Patient ID: "+PATIENT_ID)
.setIcon(0)
.setView(textEntryView4)
.setItems(R.array.patientOptions, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog2, int item) {
if(item==2){
Log.i(TAG, "Viewing Tools");
viewTools();
}
if(item==0){
Log.i(TAG, "Viewing Gall");
//viewTools();
}
else
Log.e(TAG,"NOTHONG SELECTED");//do nothing
}
})
.setNegativeButton(
R.string.dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i(TAG, "Caption dialog: CANCEL...");
openView(2);
}
})
.create();
mViewPatientOptionsDialog.show();
}
答案 0 :(得分:0)
您可能正在尝试访问范围之外的ListView。
将String itemValue = (String) patientOptionV.getItemAtPosition(position);
替换为String itemValue = (String) parent.getItemAtPosition(position);
下方代码段中的代码。
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) parent.getItemAtPosition(position);
...
}