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
你在這裏使事情變得非常複雜...... –