String response = "[\n" +
" {\n" +
" \"id\": 1,\n" +
" \"name\": \"What is your your father name\"\n" +
" },\n" +
" {\n" +
" \"id\": 2,\n" +
" \"name\": \"What is your mother's father name\"\n" +
" },\n" +
" {\n" +
" \"id\": 3,\n" +
" \"name\": \"What is your brother's father name\"\n" +
" },\n" +
" {\n" +
" \"id\": 4,\n" +
" \"name\": \"What is your father's father name\"\n" +
" },\n" +
" {\n" +
" \"id\": 5,\n" +
" \"name\": \"What is your sister's father name\"\n" +
" }\n" +
"]";
我有这组问题,我想通过它循环显示在对话框列表中。将有2个AlertDialog,并且如果用户从AlertDialog中选择一个值。这些问题不会在其他AlerDialog中显示。对于循环,这是我的代码:如何在数组中循环并忽略所选值
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.q1:
try {
JSONArray jsonArray = new JSONArray(response);
if (selected2>-1)
q1 = new String[jsonArray.length()-1];
else
q1 = new String[jsonArray.length()];
int index = 0;
for (int x = 0; x<jsonArray.length(); x++){
idQuestion[index] = jsonArray.getJSONObject(x).getInt("id");
if (selected2==x)
continue;
q1[index]= jsonArray.getJSONObject(x).getString("name");
index++;
}
AlertDialog alertDialog =new AlertDialog.Builder(getActivity())
.setTitle(R.string.select_security_question)
.setItems(q1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
question1.setText(q1[which]);
if(selected == -1) {
selected = which;
} else {
selected = which+1;
}
}
}).create();
alertDialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case R.id.q2:
try {
JSONArray ja = new JSONArray(response);
if (selected>-1)
q2 = new String[ja.length()-1];
else
q2 = new String[ja.length()];
int index = 0;
for (int x = 0; x<ja.length(); x++){
if (selected==x)
continue;
q2[index] = ja.getJSONObject(x).getString("name");
index++;
}
AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.setTitle(R.string.select_security_question)
.setItems(q2, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
question2.setText(q2[which]);
selected2 = which;
if(selected2 == -1) {
selected2 = which;
} else {
selected2 = which+1;
}
}
}).create();
alertDialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
但是我发现,这个逻辑是wrong.Questions是形式的服务器,这就是为什么它是JSON格式。如果可能,我想使用问题的ID,因为我必须返回id的值,而不是问题。
我不明白,让它更简短你想要的朋友。 –
@ArpitPatel在这里,用户需要从同一组问题中选择2个问题。所以当用户点击按钮并选择问题时,我使用2 AlertDialog列表。当用户已经选择了一个问题时,如果用户点击第二个按钮,则不会出现相同的问题。 – leyreyyan
你在这里使事情变得非常复杂...... –