【问题标题】:Android: pass the value using intent and match the previous selected radiobutton when clicked on previous buttonAndroid:使用意图传递值并在单击上一个按钮时匹配上一个选择的单选按钮
【发布时间】:2017-07-12 19:20:07
【问题描述】:

单击上一个/下一个按钮上设置单选按钮需要帮助。 我正在使用 JSON 对象来创建调查问题。对于每个问题,我都创建了一个新活动,例如surveyquestion1.java、surveyquestion2.java、surveyquestion3.java、....、surveyquestion10.java。我正在尝试在 json 对象中传递问题和单选按钮文本值。

一些问题的单选按钮包含两个或更多单选按钮,其他问题有图像或文本。第一个问题有是/否单选按钮。基于是/否的单击事件,它跳转到特定活动。

我想使用意图传递值并在单击下一个/上一个按钮时匹配上一个选择的单选按钮。谁能给我一个提示或示例。

//Surveyquetion.java

public class Survey {
private static JSONObject survey_response = new JSONObject();
private static String TAG = "HS_" + Survey.class.getSimpleName();

public static void init_response_object(Context context) {
    try {
        if ((null == SaveSharedPreference.getUserResponse(context)) || (SaveSharedPreference.getUserResponse(context).length() == 0)) {
            JSONArray question_array = new JSONArray();
            JSONObject question = new JSONObject();

            question.put("qid", 1);
            question.put("type", "multiple_choice");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            question = new JSONObject();
            question.put("qid", 2);
            question.put("type", "image");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            question = new JSONObject();
            question.put("qid", 3);
            question.put("type", "multiple_choice");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            question = new JSONObject();
            question.put("qid", 4);
            question.put("type", "multiple_choice");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            question = new JSONObject();
            question.put("qid", 5);
            question.put("type", "multiple_choice");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            question = new JSONObject();
            question.put("qid", 6);
            question.put("type", "multiple_choice");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            question = new JSONObject();
            question.put("qid", 7);
            question.put("type", "image");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            question = new JSONObject();
            question.put("qid", 8);
            question.put("type", "text");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            question = new JSONObject();
            question.put("qid", 9);
            question.put("type", "multiple_choice");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            question = new JSONObject();
            question.put("qid", 10);
            question.put("type", "multiple_choice");
            question.put("value", "");
            question.put("textvalue", "");
            question_array.put(question);

            survey_response.put("urn", "nill");
            survey_response.put("data", question_array);

            SaveSharedPreference.setUserResponse(context, survey_response.toString());
            Log.d(TAG + "_SR", survey_response.toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void manageAnswers(int qid, String value, Context context) {
    try {
        JSONObject userResponse = SaveSharedPreference.getUserResponse(context);
        JSONArray questions = userResponse.getJSONArray("data");

        if (1 == qid) {
            JSONObject question1 = questions.getJSONObject(0);
            if (qid == question1.getInt("qid")) {
                if (value.equalsIgnoreCase("no")) {

                    JSONObject question2 = questions.getJSONObject(1);
                    question2.put("value", "");
                    question2.put("textvalue", "");
                    questions.put(1, question2);

                    JSONObject question3 = questions.getJSONObject(2);
                    question3.put("value", "");
                    question3.put("textvalue", "");
                    questions.put(2, question3);

                    JSONObject question4 = questions.getJSONObject(3);
                    question4.put("value", "");
                    question4.put("textvalue", "");
                    questions.put(3, question4);

                    Log.d(TAG, "Q1 Ans is NO, hence resetting other questions - " + questions.toString());
                    userResponse.put("data", questions);
                    SaveSharedPreference.setUserResponse(context, userResponse.toString());
                } else {
                    Log.d(TAG, "Ans : yes");
                }
            } else {
                Log.d(TAG, "ERROR, MISMATCH IN qid / index");
            }
        } else if (3 == qid) {
            JSONObject question3 = questions.getJSONObject(2);
            if (qid == question3.getInt("qid")) {
                if (value.equalsIgnoreCase("yes")) {

                    JSONObject question4 = questions.getJSONObject(3);
                    question4.put("value", "");
                    question4.put("textvalue", "");
                    questions.put(3, question4);

                    JSONObject question5 = questions.getJSONObject(4);
                    question5.put("value", "");
                    question5.put("textvalue", "");
                    questions.put(4, question5);

                    Log.d(TAG, "Q3 Ans is YES, hence resetting other questions - " + questions.toString());
                    userResponse.put("data", questions);
                    SaveSharedPreference.setUserResponse(context, userResponse.toString());
                } else {
                    Log.d(TAG, "Ans : no");
                }
            } else {
                Log.d(TAG, "ERROR, MISMATCH IN qid / index");
            }
        } else if (6 == qid) {
            JSONObject question6 = questions.getJSONObject(5);
            if (qid == question6.getInt("qid")) {
                if (value.equalsIgnoreCase("no")) {

                    JSONObject question7 = questions.getJSONObject(6);
                    question7.put("value", "");
                    question7.put("textvalue", "");
                    questions.put(6, question7);

                    Log.d(TAG, "Q6 Ans is NO, hence resetting other questions - " + questions.toString());
                    userResponse.put("data", questions);
                    SaveSharedPreference.setUserResponse(context, userResponse.toString());
                } else {
                    Log.d(TAG, "Ans : yes");
                }
            } else {
                Log.d(TAG, "ERROR, MISMATCH IN qid / index");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//using this as uservalue to set the radiobutton
public static String userValue(int prevQuestion,Context context) {
    String textValue = null;
    try {
        JSONObject userVal = SaveSharedPreference.getUserResponse(context);
        Log.d(TAG, "userVal:" + userVal.toString());

        JSONArray userTextVal = userVal.getJSONArray("data");
        Log.d(TAG, "userTextValue" + userTextVal.toString());

        for (int i = 0; i < userTextVal.length(); i++) {
            JSONObject us = userTextVal.getJSONObject(i);
            int quet = us.getInt("qid");
            if (quet == prevQuestion) {
                Log.d(TAG, "qId :" + quet);
                Log.d(TAG, "textvalue :" + us.getString("textvalue"));
                textValue = us.getString("textvalue");
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return textValue;
}

public static int prev(int qid, Context context) {
    int returnValue = -1;
    int count;
    try {
        JSONArray userPos = SaveSharedPreference.getUserResponsePosition(context);
        /*ArrayList<String> pos = new ArrayList<>();
        for (int i = 0; i < userPos.length(); i++) {
            pos.add(userPos.getString(i).trim());
        }*/
        // count = pos.size();
        count = userPos.length();
        Log.d(TAG, "userPos : " + userPos.toString());
    Log.d(TAG, "count : " + count);
        if (count > 0) {
            // returnValue = Integer.parseInt((pos.get(count - 1)));
            returnValue = (int) userPos.get(count - 1);
            Log.d(TAG, "position : " + returnValue);

    //resetting the position
            userPos.remove(count - 1);
            SaveSharedPreference.setUserResponsePosition(context, userPos.toString());
        } else {
            returnValue = -1;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return returnValue;
}

public static String next(int qid, String value, Context context) {

    // RESET UNWANTED ANSWERS
    Survey.manageAnswers(qid, value, context);

    String returnValue = "";
    JSONArray positionArray = SaveSharedPreference.getUserResponsePosition(context);
    if (null == positionArray || positionArray.length() > 8) {
        positionArray = new JSONArray();
    }
    positionArray.put(qid);
    SaveSharedPreference.setUserResponsePosition(context, positionArray.toString());

    try {
        JSONObject submitData = SaveSharedPreference.getUserResponse(context);
        submitData.put("urn", SaveSharedPreference.getCurrentURN(context));
        JSONArray dataArray = submitData.getJSONArray("data");

        if (1 == qid) {

            JSONObject question = dataArray.getJSONObject(0);
            question.put("qid", qid);
            question.put("type", "multiple_choice");

            if (value.toLowerCase().equals("yes")) {
                question.put("value", 1);
                returnValue = "2";
            } else if (value.toLowerCase().equals("no")) {
                question.put("value", 2);
                returnValue = "5";
            }
            dataArray.put(0, question);
            question.put("textvalue", value);
        } else if (2 == qid) {

            JSONObject question = dataArray.getJSONObject(1);
            question.put("qid", qid);
            question.put("type", "image");
            question.put("value", value);
            returnValue = "3";
            dataArray.put(1, question);
            question.put("textvalue", value);
        } else if (3 == qid) {

            JSONObject question = dataArray.getJSONObject(2);
            question.put("qid", qid);
            question.put("type", "multiple_choice");

            if (value.toLowerCase().equals("yes")) {
                question.put("value", 3);
                returnValue = "6";
            } else if (value.toLowerCase().equals("no")) {
                question.put("value", 4);
                returnValue = "4";
            }
            dataArray.put(2, question);
            question.put("textvalue", value);
        } 
    .
    .   
    .
    .
    .
    .
    .   

        } else if (10 == qid) {

            JSONObject question = dataArray.getJSONObject(9);
            question.put("qid", qid);
            question.put("type", "multiple_choice");

            if (value.toLowerCase().trim().equalsIgnoreCase("something")) {
                question.put("value", 19);
            } else if (value.toLowerCase().trim().equalsIgnoreCase("something")) {
                question.put("value", 20);
            } else if (value.toLowerCase().trim().equalsIgnoreCase("something")) {
                question.put("value", 21);
            } else if (value.toLowerCase().trim().equalsIgnoreCase("something")) {
                question.put("value", 22);
            } else if (value.toLowerCase().trim().equalsIgnoreCase("something")) {
                question.put("value", 23);
            }

            returnValue = "";
            dataArray.put(9, question);
            question.put("textvalue", value);
        }

        submitData.put("data", dataArray);
        SaveSharedPreference.setUserResponse(context, submitData.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }
    return returnValue;
}
}   

//Surveyquestion2.java

      prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int prevQuestion = (Survey.prev(1, context));
            String val=Survey.userValue(prevQuestion,context);
            Log.d(TAG,"prevQusetionValue :" +val);
            Log.d(TAG, "prevQuestion : " + String.valueOf(prevQuestion));
            if (9 == prevQuestion) {
                Intent intent = new Intent(SurveryQuestion1.this, SurveryQuestion9.class);
                intent.putExtra("value",val);
                    startActivity(intent);
                    finish();
                }
            }
        });

      next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int selectedId = radioGroup.getCheckedRadioButtonId();

            if (-1 == selectedId) {
                Toast.makeText(SurveryQuestion1.this, "Please answer to proceed", Toast.LENGTH_LONG).show();
            } else {
                radioButton = (RadioButton) findViewById(selectedId);
                String answer = radioButton.getText().toString().toLowerCase().trim();

                Log.d(TAG, "Answer : " + answer);
                if ((null != answer) && (answer.length() > 0)) {
                    String nextQuestion = Survey.next(1, answer, context);
                    if (2 == Integer.valueOf(nextQuestion)) {
                        Intent intent = new Intent(SurveryQuestion1.this, SurveryQuestion2.class);
                        startActivity(intent);
                        finish();
                    } else if (5 == Integer.valueOf(nextQuestion)) {
                        Intent intent = new Intent(SurveryQuestion1.this, SurveryQuestion5.class);
                        startActivity(intent);
                        finish();
                    }
                }
            }

        }
    });   

//SavedPreferences.java

    public static void setUserResponse(Context ctx, String userResponse) {
    SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
    editor.putString(PREF_USER_RESPONSE, userResponse);
    editor.commit();
}

public static JSONObject getUserResponse(Context ctx) {
    String response = getSharedPreferences(ctx).getString(PREF_USER_RESPONSE, "").toString();
    JSONObject userResponse = null;
    try {
        if (null != response && response.length() > 0) {
            userResponse = new JSONObject(response);
        }
    } catch (Exception e) {
        e.printStackTrace();
        userResponse = null;
    }
    return userResponse;
}

注意:1.使用 Json Object .2 不使用 Fragmentactivity

我尝试在单击事件之前的新活动中的 onCreate() 中使用此方法设置单选按钮的值。给我错误:- radioButton1.getText() 的空指针执行

SurveyQuestion1.java

    radioButton1 = (RadioButton) findViewById(R.id.rb_yes);
        String check= (String) radioButton1.getText().toString();//Null Pointer Exception
        Log.d(TAG,"check"+check);*/
        radioButton2 = (RadioButton) findViewById(R.id.rb_no);
        if (check.equalsIgnoreCase(prevValue)) {
            radioButton1.setChecked(true);
        }
        else {
            radioButton2.setChecked(true);
        }
prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SurveryQuestion9.this, SurveryMgmt.class);
                startActivity(intent);
                finish();
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // CREATE A DUMMY JSON
                Survey.init_response_object(context);

                // INIT USER POSITION
                SaveSharedPreference.setUserResponsePosition(context, new JSONArray().toString());

                int selectedId = radioGroup.getCheckedRadioButtonId();

                if (-1 == selectedId) {
                    Toast.makeText(SurveryQuestion9.this, "Please answer to proceed", Toast.LENGTH_LONG).show();
                } else {
                    radioButton = (RadioButton) findViewById(selectedId);
                    String answer = radioButton.getText().toString().toLowerCase().trim();
                    String nextQuestion = Survey.next(9, answer, context);
                    if (1 == Integer.valueOf(nextQuestion)) {
                        Intent intent = new Intent(SurveryQuestion9.this, SurveryQuestion1.class);
                        startActivity(intent);
                        finish();
                    } else if (10 == Integer.valueOf(nextQuestion)) {
                        Intent intent = new Intent(SurveryQuestion9.this, SurveryQuestion10.class);
                        startActivity(intent);
                        finish();
                    }
                }

            }
        });

【问题讨论】:

  • 提前致谢
  • 请重新格式化您的问题,您没有正确缩进
  • 可以简要告诉我意图有什么问题..如何解决该问题..请给我一些提示...@GrayCygnus
  • 看到“}”挂出来了吗?...您应该正确缩进(每级 4 个空格)您的代码,我看到您在每行上错过了 4 个空格,所以它处于同一级别跨度>
  • 我已经重新格式化了问题..你们能帮帮我吗..@GrayCygnus

标签: android json


【解决方案1】:

创建一个活动并为每个问题添加视图。有一个全局计数器和 next() 和 previous() 方法。对于第一个问题,使用 counter==0 加载您的视图,并将响应保存在模型中。当您按下下一个按钮调用 next() 并增加计数器添加下一个问题的视图。如果您以前,请从模型中获取保存的数据并使用该值更新您的单选按钮。 这将使您的代码易于管理,并且可以在以后扩展而无需任何额外的努力。

Class Xyz extends Activity
{
  int counter=0; 
  onCreate()
  {
    loadView(0);
  }

  loadView(int index)
  {
   //if value is already saved then rtetrieve from model or load with default value
  }
   // called on next button click
  next()
  {
   index++;
   loadView(index);
  }
  // called on previous button click
  previous()
  {
   index--;
   loadView(index);
  }

  save() 
  {//save in model }



}

【讨论】:

  • 是的,这是真的..我想创建这样的代码..现在可以提示我在新活动中设置单选按钮的值..
  • 请检查我的问题我添加了一个空指针异常部分@Payal
  • 好吧,参考这个链接:- stackoverflow.com/questions/12862987/…
  • 是的,这是传递单选按钮的一种方式。如果我想将单选按钮传递给上一个活动怎么办。考虑将surveyquestion1作为第一个活动,然后将surveyquestion2.java作为第二个。
  • 是的,这是将单选按钮传递给下一个活动的一种方式。如果我想将单选按钮传递给前一个活动怎么办。考虑将surveyquestion1 作为第一个活动,然后将surveyquestion2.java 作为第二个活动。从surveyquestion2,我希望它传递给surveyquestion1选择的值...... @Payal
猜你喜欢
  • 2021-04-09
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
  • 2015-02-27
  • 2013-08-26
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
相关资源
最近更新 更多