set_id不断循环输出ID

时间:2017-08-30 15:29:52

标签: android android-fragments for-loop

我有两个片段。 片段A 导致片段B - 在片段B中我从外部数据库获取数据并将值保存在共享首选项中并将其传回片段A

片段B 中,我有以下内容,即处理JSON数组:

public ArrayList getAll_question_ids(){
    return all_question_ids;
}

@Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();

            //Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();

            if (resp.getResult().equals(Constants.SUCCESS)) {

                SharedPreferences.Editor editor = pref.edit();

                Log.d("Question_IDs", "getAllQuestionID() = " + response.body().getQuestion().getAll_question_ids() );

                editor.putString(Constants.All_QUESTION_IDS,((resp.getQuestion().getAll_question_ids().toString())));
                editor.apply();

                String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");

                Toast.makeText(getActivity(), "Question ID = " + questionNumber,
                        Toast.LENGTH_LONG).show();

                goToCreateQuestionFragment();

            }
            progress.setVisibility(View.INVISIBLE);
        }

片段A 中,然后通过onViewCreated方法调用方法,如下所示:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    pref = getActivity().getPreferences(0);

    if ((!pref.getString(Constants.All_QUESTION_IDS, "").equals(null) && !pref.getString(Constants.All_QUESTION_IDS, "").equals(""))) {
        createQuestionButton();
    }
}

createQuestionButton 方法中,我很困惑。我有一个循环,我用它来将共享首选项中存储的值分配给动态创建的按钮,该按钮被添加到线性布局中。

我现在想要为按钮设置唯一ID并附加onClickListener,以便我可以为按钮创建操作。

我已经读过,我可以将View.generateViewId()用于使用API​​ 17及更高版本的设备,这很棒。

然而,当我做一个Toast来检查正确创建分配给每个按钮的值时,我注意到我的代码不是仅仅分配一个ID而是执行4/5次,因此4/5 ID正在按钮生成!

我认为这与我在onViewCreated中调用方法这一事实有关,但我不确定如何调用该方法。

被调用的方法如下:

@TargetApi(Build.VERSION_CODES.M)
public void createQuestionButton() {

    //get all the question_ids from shared pref, that have been stored from the SetQuestion Activity
    //in the allQuestionIDS() method
    String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
    //converting the above String back into a List
    questionNumber = questionNumber.substring(1, questionNumber.length() - 1);
    //split the array using the comma
    String[] array = questionNumber.split(", ");
    //Converting questionArray array to a list using Arrays.asList()
    List list = Arrays.asList(array);


    if (!questionNumber.equals("") && !questionNumber.equals(null)) {

        for (Object value : list) {


            try {

        /*Dynamically create new Button which includes the question number
          */

                AppCompatButton btn_question = new AppCompatButton(getActivity());

        /*LayoutParams (int width, int height,float weight)
        As LayoutParams defaults in px, I have called a method called dpToPX to make sure the dynamically added EditText is the same size on all devices.
         */
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dpToPx(280), dpToPx(45), 1);
                btn_question.setBackgroundColor(Color.parseColor("#3B5998"));
                btn_question.setTextColor(Color.WHITE);
                btn_question.setText("Question " + value);
                btn_question.setGravity(Gravity.CENTER);
                //generate unique ID for each new EditText dynamically created
                btn_question.setId(View.generateViewId());
                params.setMargins(0, dpToPx(10), 0, dpToPx(10));
                btn_question.setPadding(0, 0, 0, 0);
                btn_question.setLayoutParams(params);
                allEds.add(btn_question);
                mLayout.addView(btn_question);

                Toast.makeText(getActivity(), "Question ID = " + btn_question.getId(),
                        Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                Log.d(TAG, "Failed to create new button");
            }
        }
    }
}

任何关于如何引起这种情况以及避免最佳做法的指导都将受到赞赏。

修改

我已经在片段B 中通过了一个祝酒词,看起来来自服务器的结果是正确的但是吐司似乎是挂在上面,好像它是多次烘烤相同的信息一样。

我检查了解释器,并且数据是正确的,所以我不确定为什么它似乎陷入循环,特别是当片段B中没有循环时!

检索的JSON如下:

{
  "result": "success",
  "message": "All Questions Have Been Selected",
  "question": {
      "all_question_ids": ["1","2","3"]
  }
}

1 个答案:

答案 0 :(得分:0)

我建议您使用调试器进入您的函数,并检查var maxDays = 30; DateTime today = DateTime.Now; //todays date DateTime lastAction = '2017-03-07 12:47:58.967'; double totalDays = (lastAction - today).TotalDays; var days = Math.Round(totalDays); if(days > maxDays) { //never hits this even though days is greater than max days ..i'm so confused } 变量上的值。一个很可能的原因可能是list中的额外空间。最有可能它应该写成questionNumber.split(", ");