1
\$\begingroup\$

I have added a correct question callback for different types of questions like: radio, checkbox and descriptive..

QuestionListActivity.class (it shows the list of questions to attempt)

    public class QuestionListActivity extends AppCompatActivity {

    private Context mContext;
    private List<QuestionBO> questionList;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private TextView noResultTv;// FIXME: 8/1/2018 update it after other work done...
    private QuestionAdapter mAdapter;
    private FirebaseFirestore db = null;

    private final String TAG = getClass().getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_list);

        FrameLayout frameLayout = findViewById(R.id.parent);
        frameLayout.setBackgroundColor(Color.WHITE);

        mContext = QuestionListActivity.this;
        questionList = new ArrayList<>();

        mRecyclerView = findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        noResultTv = findViewById(R.id.tv_no_result);

        mSwipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getQuestionsFromServer(true);
            }
        });

        if (mAdapter == null) {
            mAdapter = new QuestionAdapter(questionList, new OnRecyclerItemClickListener() {
                @Override
                public void onItemClick(View view, int position, boolean isCorrectAnswer) {
                    int post = position + 1;
                    Toast.makeText(mContext, "Answer Correct at : " + post
                                    + "  " +  isCorrectAnswer, Toast.LENGTH_LONG).show();
                }
            });
        }

        mRecyclerView.setAdapter(mAdapter);

        getQuestionsFromServer(true);
    }

    public void getQuestionsFromServer(boolean isRefresh) {
        db = FirebaseFirestore.getInstance();

        //fetching data by comparison...
        /*Query radioQuestions = db.collection("questionCollection").whereEqualTo("questionType", 1);*/

        db.collection("questionCollection")
                .get()
                .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        if (queryDocumentSnapshots.isEmpty()) {
                            Log.d(TAG, "onSuccess: LIST EMPTY");
                            return;
                        } else {
                            // Convert the whole Query Snapshot to a list
                            // of objects directly! No need to fetch each
                            // document.
                            questionList = queryDocumentSnapshots.toObjects(QuestionBO.class);

                            if (questionList != null && questionList.size() > 0)
                                mAdapter.updateQuestions(questionList);
                        }
                    }
                });
        if(mSwipeRefreshLayout.isRefreshing())
            mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_questions, menu);
        return true;
        ///return super.onCreateOptionsMenu(menu);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.menu_action_save) {
            Toast.makeText(QuestionListActivity.this, "Action clicked", Toast.LENGTH_LONG).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

where activity_question_list.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parent"
    tools:context=".QuestionListActivity">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </android.support.v7.widget.RecyclerView>

    </android.support.v4.widget.SwipeRefreshLayout>

    <include layout="@layout/no_result" />
</FrameLayout>

QuestionAdapter.class

public class QuestionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<QuestionBO> items;
    private OnRecyclerItemClickListener onRecyclerItemClickListener;

    private static final int VIEW_TYPE_DESCRIPTIVE = 0;
    private static final int VIEW_TYPE_CHECKBOX = 1;
    private static final int VIEW_TYPE_RADIO = 2;

    public QuestionAdapter(List<QuestionBO> questions,
                           OnRecyclerItemClickListener onRecyclerItemClickListener) {
        this.items = questions;
        this.onRecyclerItemClickListener = onRecyclerItemClickListener;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_CHECKBOX) {
            return new CheckBoxVH(parent, R.layout.item_checkbox, onRecyclerItemClickListener);
        } else if (viewType == VIEW_TYPE_RADIO) {
            return new RadioVH(parent, R.layout.item_radio, onRecyclerItemClickListener);
        } else
            return new DescriptiveVH(parent, R.layout.item_descriptive, onRecyclerItemClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof CheckBoxVH)
            ((CheckBoxVH) holder).onBindData(items.get(position));
        else if (holder instanceof RadioVH)
            ((RadioVH) holder).onBindData(items.get(position));
        else if (holder instanceof DescriptiveVH)
            ((DescriptiveVH) holder).onBindData(items.get(position));
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (items.get(position).getQuestionType() == EnumUtils.QuestionType.CHECKBOX)
            return VIEW_TYPE_CHECKBOX;
        else if (items.get(position).getQuestionType() == EnumUtils.QuestionType.RADIO)
            return VIEW_TYPE_RADIO;
        else
            return VIEW_TYPE_DESCRIPTIVE;
    }

    public QuestionBO getItemAt(int position) {
        return items.get(position);
    }

    public void clearItems() {
        items.clear();
        notifyDataSetChanged();
    }

    public void updateQuestions(List<QuestionBO> newQuestions) {
        items.clear();
        items.addAll(newQuestions);
        this.notifyDataSetChanged();
    }
}

CheckBoxVH

public class CheckBoxVH extends BaseQuestionTypeVH<QuestionBO> {

    private TextView questionTitleTv;
    private LinearLayout checkboxLL;
    private Context mContext;
    private boolean isAnswerCorrect = false;

    public CheckBoxVH(ViewGroup parent, int layoutId, OnRecyclerItemClickListener onRecyclerItemClickListener) {
        super(parent, layoutId, onRecyclerItemClickListener);
        mContext = parent.getContext();
        questionTitleTv = itemView.findViewById(R.id.tv_question_title);
        checkboxLL = itemView.findViewById(R.id.ll_checkbox);
    }

    @Override
    public void onBindData(final QuestionBO data) {

        questionTitleTv.setText(data.getTitle());

        if (data.getOptions() != null && data.getOptions().size() > 0) {
            checkboxLL.removeAllViews();

            for (int x = 0; x < data.getOptions().size(); x++) {
                final CheckBox subCheckbox = new CheckBox(mContext);
                subCheckbox.setText(data.getOptions().get(x));
                subCheckbox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        isAnswerCorrect = false;

                        int counter = 0;
                        int numberOfChecked = 0;
                        for(int y =0 ; y < checkboxLL.getChildCount() ; y++){
                            CheckBox checkBox = (CheckBox) checkboxLL.getChildAt(y);
                            if (checkBox.isChecked()){
                                numberOfChecked++;
                                for (Integer intVariable : data.getOptionIndexes()) {
                                    if(intVariable.intValue() == y)
                                        counter++;
                                }
                            }
                        }
                        if(counter == data.getOptionIndexes().size() && numberOfChecked == data.getOptionIndexes().size()){
                            isAnswerCorrect = true;
                        }
                    }
                });

                checkboxLL.addView(subCheckbox, new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            }
        }
    }

    @Override
    public void onClick(View view) {
        if(onItemClicked != null){
            onItemClicked.onItemClick(view,getAdapterPosition(),isAnswerCorrect);
        }
    }
}

RadioVH.class

public class RadioVH extends BaseQuestionTypeVH<QuestionBO> {

    private TextView questionTitleTv;
    private RadioGroup radioLL;
    private Context mContext;
    private boolean isAnswerCorrect = false;

    public RadioVH(ViewGroup parent, int layoutId, OnRecyclerItemClickListener onRecyclerItemClickListener) {
        super(parent, layoutId, onRecyclerItemClickListener);
        mContext = parent.getContext();
        questionTitleTv = itemView.findViewById(R.id.tv_question_title);
        radioLL = itemView.findViewById(R.id.ll_radio);
    }

    @Override
    public void onBindData(final QuestionBO data) {
        questionTitleTv.setText(data.getTitle());

        if (data.getOptions() != null && data.getOptions().size() > 0) {
            radioLL.removeAllViews();

            for (int x = 0; x < data.getOptions().size(); x++) {

                final RadioButton subRadio = new RadioButton(mContext);
                subRadio.setText(data.getOptions().get(x));
                radioLL.addView(subRadio, new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            }
        }
        radioLL.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {

                View radioButton = itemView.findViewById(checkedId);
                int index = radioGroup.indexOfChild(radioButton);

                isAnswerCorrect = false;
                for (Integer intVariable : data.getOptionIndexes()) {
                    if (intVariable.intValue() == index) {
                        isAnswerCorrect = true;
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        if (onItemClicked != null)
            onItemClicked.onItemClick(view, getAdapterPosition(), isAnswerCorrect);
    }
}

DescriptiveVH.class

public class DescriptiveVH extends BaseQuestionTypeVH<QuestionBO> {

    private TextView questionTitleTv;
    private EditText answerEt;
    private boolean isAnswerCorrect = false;

    public DescriptiveVH(ViewGroup parent, int layoutId, OnRecyclerItemClickListener onRecyclerItemClickListener) {
        super(parent, layoutId, onRecyclerItemClickListener);
        questionTitleTv = itemView.findViewById(R.id.tv_question_title);
        answerEt = itemView.findViewById(R.id.et_answer);
    }

    @Override
    public void onBindData(final QuestionBO data) {
        questionTitleTv.setText(data.getTitle());

        answerEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.toString().equalsIgnoreCase(data.getAnswer()))
                    isAnswerCorrect = true;
                else
                    isAnswerCorrect = false;
            }
        });

    }

    @Override
    public void onClick(View view) {
        if(onItemClicked != null)
            onItemClicked.onItemClick(view,getAdapterPosition(),isAnswerCorrect);
    }
}

item_checkbox.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_question_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Title Text"
        android:textColor="@android:color/black" />

    <LinearLayout
        android:id="@+id/ll_checkbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />
</LinearLayout>

item_descriptive.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_question_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Title Text"
        android:textColor="@android:color/black" />

    <EditText
        android:id="@+id/et_answer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />
</LinearLayout>

item_radio.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_question_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Title Text"
        android:textColor="@android:color/black" />

    <RadioGroup
        android:id="@+id/ll_radio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />
</LinearLayout>

BaseQuestionTypeVH.class

public abstract class BaseQuestionTypeVH<T> extends RecyclerView.ViewHolder implements View.OnClickListener{

    public abstract void onBindData(T data);
    public OnRecyclerItemClickListener onItemClicked;

    public BaseQuestionTypeVH(ViewGroup parent, int layoutId , OnRecyclerItemClickListener onRecyclerItemClickListener) {
        super(LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false));
        this.onItemClicked = onRecyclerItemClickListener;
        itemView.setOnClickListener(this);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.