检查自定义对象ArrayList的属性是否为空字符串?

时间:2019-05-09 11:48:23

标签: java android android-layout arraylist

如果自定义对象Arraylist(arrQues)的code属性不包含任何内容,我想隐藏WebView对象(txtCode)。

if (arrQues.get(count).code.isEmpty())
            txtCode.setVisibility(View.GONE);

它是从数据库表中获取的自定义对象的ArrayList,如下所示

enter image description here

如果code属性确实包含代码,那么我将动态添加规则到布局中,如下所示:

            if (!(arrQues.get(count).code.isEmpty())) {

            submit_params.removeRule(RelativeLayout.BELOW);

            submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
            main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());

            mainContainer.setLayoutParams(main_params);
            submitContainer.setLayoutParams(submit_params);
}

问题是当我加载第二个问题,依此类推时...布局混乱,即使其问题2如下所示,当前问题编号也不显示为2:

1st Question

2nd Question

这两个问题仅在我使用时才会出现...     代码中的arrQues.get(count).code.isEmpty() 我也尝试使用“”代替isEmpty()甚至为null,但是结果是相同的。

我还注意到,只有从数据库中加载的那些在代码列中包含某些内容的问题。

下面是Java文件的完整代码

    public class QuestionsFragment extends Fragment implements View.OnClickListener {
    TextView txtTimer, txtStatus;
    LinearLayout boxA, boxB, boxC, boxD, mainContainer;
    RelativeLayout submitContainer;

    RelativeLayout.LayoutParams submit_params;
    RelativeLayout.LayoutParams main_params;

    ScrollView scrollView;
    Button btnSubmit;

    DBHelper dbHelper;

    SharedPreferences sharedPreferences;

    TextView txtQues;
    WebView txtCode;
    TextView txtOptA, txtOptB, txtOptC, txtOptD;
    String ans;
    ArrayList<QuestionModal> arrQues = new ArrayList<>();
    ArrayList<String> arrAnswers = new ArrayList<>();

    CountDownTimer countDownTimer;
    boolean timerSwitch;

    int selectedVal, id;

    int curr_quesNo = 0;
    int count = 0;
    int right = 0;
    int non_attempted = 0;

    public QuestionsFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_questions, container, false);

        txtQues = view.findViewById(R.id.txtQues);
        txtOptA = view.findViewById(R.id.txtOptionA);
        txtOptB = view.findViewById(R.id.txtOptionB);
        txtOptC = view.findViewById(R.id.txtOptionC);
        txtOptD = view.findViewById(R.id.txtOptionD);
        txtCode = view.findViewById(R.id.txtCode);
        txtStatus = view.findViewById(R.id.txtStatus);

        boxA = view.findViewById(R.id.boxA);
        boxB = view.findViewById(R.id.boxB);
        boxC = view.findViewById(R.id.boxC);
        boxD = view.findViewById(R.id.boxD);

        scrollView = view.findViewById(R.id.scrollView);
        btnSubmit = view.findViewById(R.id.btnSubmit);

        submitContainer = view.findViewById(R.id.submitContainer);
        mainContainer = view.findViewById(R.id.mainContainer);
        submit_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
        main_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);

        sharedPreferences = getActivity().getSharedPreferences("PrefFile", MODE_PRIVATE);

        timerSwitch = sharedPreferences.getBoolean("timer_switch", true);

        selectedVal = sharedPreferences.getInt("selectedVal", 10);

        dbHelper = DBHelper.getDB(getActivity(), sharedPreferences.getString("db_name", null));

        if (!dbHelper.checkDB()) {
            dbHelper.createDB(getActivity());
        }

        dbHelper.openDB();

        String levelKey = sharedPreferences.getString("level_key", null);

        arrQues = dbHelper.getQues(levelKey, selectedVal);

        loadQues(timerSwitch);

        txtTimer = view.findViewById(R.id.txtTimer);

        switch (sharedPreferences.getString("db_name", null)) {
            case "Android":
                ((MainActivity) getActivity()).setFragTitle("Android Quiz");
//                topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
                break;
            case "Java":
                ((MainActivity) getActivity()).setFragTitle("Java Quiz");
//                topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
                break;
            case "C":
                ((MainActivity) getActivity()).setFragTitle("C Quiz");
                ((MainActivity) getActivity()).setFragLogo(R.drawable.ic_home_black_24dp);
                break;
            case "C++":
                ((MainActivity) getActivity()).setFragTitle("C++ Quiz");
                break;
            case "Python":
                ((MainActivity) getActivity()).setFragTitle("Python Quiz");
                break;
            case "Kotlin":
                ((MainActivity) getActivity()).setFragTitle("Kotlin Quiz");
                break;

        }

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (timerSwitch)
                    countDownTimer.cancel();

                if (id == 0) {
                    non_attempted++;
                    arrAnswers.add("NotAttempted");
                    Toast.makeText(getActivity(), "Not Attempted!", Toast.LENGTH_SHORT).show();
                }

                switch (id) {
                    case R.id.boxA:
                        arrAnswers.add("A");
                        break;
                    case R.id.boxB:
                        arrAnswers.add("B");
                        break;
                    case R.id.boxC:
                        arrAnswers.add("C");
                        break;
                    case R.id.boxD:
                        arrAnswers.add("D");
                        break;
                }

                if ((id == R.id.boxA && ans.equals("A"))
                        || (id == R.id.boxB && ans.equals("B"))
                        || (id == R.id.boxC && ans.equals("C"))
                        || (id == R.id.boxD && ans.equals("D"))) {

                    right++;
                    count++;
                    Toast.makeText(getActivity(), "RIGHT!", Toast.LENGTH_SHORT).show();

                    if (count < arrQues.size()) {
                        loadQues(timerSwitch);
                    } else {
                        sendResult();
                    }

                } else {
                    count++;
                    if (count < arrQues.size()) {
                        loadQues(timerSwitch);
                    } else {
                        sendResult();
                    }
                }

            }
        });
        return view;
    }

    public void setBtnDefault() {
        boxA.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        boxB.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        boxC.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        boxD.setBackgroundColor(getResources().getColor(android.R.color.transparent));
    }

    public void sendResult() {
        int attempted = selectedVal - non_attempted;

        Gson gson = new Gson();
        String jsonAnswers = gson.toJson(arrAnswers);
        String jsonQues = gson.toJson(arrQues);

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("right_key", right);
        editor.putInt("wrong_key", attempted - right);
        editor.putInt("total_key", selectedVal);
        editor.putInt("attempted_key", attempted);
        editor.putString("arr_answers", jsonAnswers);
        editor.putString("arr_ques", jsonQues);
        editor.commit();

        ((MainActivity) getActivity()).AddFrag(new ResultFragment(), 1);

    }

    public void LoadTimer() {

        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                txtTimer.setText("0:" + millisUntilFinished / 1000);
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onFinish() {
                txtTimer.setText("Time Over");
            }
        };
    }

    @SuppressLint("NewApi")
    public void loadQues(boolean timer_switch) {
        try {
            id = 0;
            setBtnDefault();

            if (timer_switch) {
                LoadTimer();
                countDownTimer.start();
            }

            curr_quesNo++;

            txtStatus.setText(curr_quesNo + "/" + selectedVal);

            txtOptC.setVisibility(View.VISIBLE);
            txtOptD.setVisibility(View.VISIBLE);
            txtCode.setVisibility(View.VISIBLE);

            main_params.removeRule(RelativeLayout.ABOVE);
            submit_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

            submit_params.addRule(RelativeLayout.BELOW, mainContainer.getId());
            submit_params.topMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 70));

            mainContainer.setLayoutParams(main_params);
            submitContainer.setLayoutParams(submit_params);

            txtQues.setText(arrQues.get(count).ques);
            txtOptA.setText(arrQues.get(count).optionA);
            txtOptB.setText(arrQues.get(count).optionB);
            txtOptC.setText(arrQues.get(count).optionC);
            txtOptD.setText(arrQues.get(count).optionD);

            txtCode.loadDataWithBaseURL(null, arrQues.get(count).code, "text/html", null, null);

            if (txtOptC.getText().toString().isEmpty())
                txtOptC.setVisibility(View.GONE);

            if (txtOptD.getText().toString().isEmpty())
                txtOptD.setVisibility(View.GONE);

            if (arrQues.get(count).code.isEmpty())
                txtCode.setVisibility(View.GONE);

            if (!(arrQues.get(count).code.isEmpty())) {

                submit_params.removeRule(RelativeLayout.BELOW);

                submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
                main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());

                mainContainer.setLayoutParams(main_params);
                submitContainer.setLayoutParams(submit_params);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.arrowScroll(View.FOCUS_DOWN);

                    }
                }, 1000);
            }

            ans = arrQues.get(count).answer;

            boxA.setOnClickListener(this);
            boxB.setOnClickListener(this);
            boxC.setOnClickListener(this);
            boxD.setOnClickListener(this);
        } catch (Exception e) {
            ((MainActivity) getActivity()).AddFrag(new QuestionsFragment(), 1);
        }
    }

    @Override
    public void onClick(View v) {
        setBtnDefault();
        id = v.getId();
        v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
    }

    public float convertDpToPx(Context context, float dp) {
        return dp * context.getResources().getDisplayMetrics().density;
    }

    public float convertPxToDp(Context context, float px) {
        return px / context.getResources().getDisplayMetrics().density;
    }
}

1 个答案:

答案 0 :(得分:0)

我解决了它,所有问题都发生了,因为arrQues.get(count).code正在从数据库中获取空值(“代码”列具有空值)。我将空值替换为空字符串后,立即将isEmpty()完美地工作了。我猜isEmpty()不适用于null值,仅用于空字符串。