我有一个程序会显示带有循环复选框的AlertDialog(复选框值来自数据库),然后用户将选中复选框,之后我想将所有选中的复选框存储到变量中,然后将值存储到数据库
所以流程是: 从数据库读取值 - >将所有值(循环)打印到“警报对话框”复选框 - >用户选中复选框,然后单击确定 - >选中复选框的值将被存储并传递给DBHelper
我试过编码它,它运行良好,直到我想存储所选复选框的值,但我得到错误,错误是java.lang.NullPointerException .. 这里我将选中的值存储到字符串temp [i](参见builder.setPositiveButton),然后在循环外部,我将temp [i]传递给groupToBePosted 这是我的代码,希望您能帮我存储值并将其传递给数据库,
谢谢..
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bBrowseSelectGroup:
myDb.open();
final String[] groupName = myDb.fetchGroupName(username);
myDb.close();
final boolean[] itemsChecked = new boolean[groupName.length];
AlertDialog.Builder builder = new AlertDialog.Builder(
CreateAnnouncementActivity.this);
builder.setTitle("Choose Your Group : ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
myDb.open();
final String[] groupId = myDb.fetchGroupId(username);
myDb.close();
String selectedGroup="Post To : ";
String temp[] = null;
for (int i = 0; i < groupName.length; i++) {
if (itemsChecked[i]) {
temp[i]=groupId[i];
selectedGroup=selectedGroup+groupName[i]+", ";
itemsChecked[i]=false;
}
}
PostTo.setText(selectedGroup); //Set the TextView Value
for(int i=0;i<temp.length;i++){
groupToBePosted[i]=temp[i];
}
}
});
builder.setMultiChoiceItems(groupName, new boolean[] { false,
false, false },
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
itemsChecked[which] = isChecked;
}
});
builder.show();
myDb.close();
break;
case R.id.bDoPostAnnouncement:
//Get all the data stored and pass to the database
for(int i=0; i<groupToBePosted.length;i++){
myDb.open();
myDb.insertNewAnnouncement(title, detail, time, groupToBePosted[i], username);
myDb.close();
}
break;
}
}
这是logcat
答案 0 :(得分:1)
使用LinkedList:
LinkedList<String> temp = new LinkedList<String>();
然后替换
temp[i]=groupId[i];
通过
temp.add(groupId[i]);
然后迭代遍历列表而不是临时数组。变化:
for(int i=0;i<temp.length;i++){
groupToBePosted[i]=temp[i];
}
到
int i=0;
for(String t:temp){
groupToBePosted[i]=t;
i++;
}