Quiz app Randomize answers on Android studio

Quiz app Randomize answers on Android studio



I bought in courses on creating android application "Quiz app". But in this course, a random order of answers is not implemented. I'm a beginner programmer without any technical education I know that I need to insert somewhere in the code
"Collections.shuffle (list)" but I can not yet figure out where. Help please. I'm making an application for students that would make life easier for them. Helping me you are helping them.



QUIZ ACTIVITY


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.vn.iambulance.prototype_20.R;
import com.vn.iambulance.prototype_20.adapters.QuizAdapter;
import com.vn.iambulance.prototype_20.constants.AppConstants;
import com.vn.iambulance.prototype_20.data.preference.AppPreference;
import com.vn.iambulance.prototype_20.listeners.ListItemClickListener;
import com.vn.iambulance.prototype_20.models.quiz.QuizModel;
import com.vn.iambulance.prototype_20.models.quiz.ResultModel;
import com.vn.iambulance.prototype_20.utilities.ActivityUtilities;
import com.vn.iambulance.prototype_20.utilities.BeatBox;
import com.vn.iambulance.prototype_20.utilities.DialogUtilities;
import com.vn.iambulance.prototype_20.utilities.SoundUtilities;


public class QuizActivity extends BaseActivity implements DialogUtilities.OnCompleteListener

private Activity mActivity;
private Context mContext;
private ImageButton btnSpeaker;
private Button btnNext;
private RecyclerView mRecyclerQuiz;
private TextView tvQuestionText;
private TextView tvQuestionTitle;
private ImageView imgFirstLife, imgSecondLife, imgThirdLife, imgFourthLife, imgFifthLife;

private QuizAdapter mAdapter = null;
private List<QuizModel> mItemList;
ArrayList<String> mOptionList;
ArrayList<String> mBackgroundColorList;

private int mQuestionPosition = 0;
private int mQuestionsCount = 0;
private int mScore = 0, mWrongAns = 0, mSkip = 0;
private int mLifeCounter = 5;
private boolean mUserHasPressed = false;
private boolean mIsSkipped = false, mIsCorrect = false;
private String mQuestionText, mGivenAnsText, mCorrectAnsText, mCategoryId;
private ArrayList<ResultModel> mResultList;

private BeatBox mBeatBox;
private List<SoundUtilities> mSounds;
private boolean isSoundOn;


@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);

//TODO: initializeRewardedAds();
//TODO: loadRewardedVideoAds();

initVar();
initView();
loadData();
initListener();





private void initVar()
mActivity = QuizActivity.this;
mContext = mActivity.getApplicationContext();

Intent intent = getIntent();
if (intent != null)
mCategoryId = intent.getStringExtra(AppConstants.BUNDLE_KEY_INDEX);


mItemList = new ArrayList<>();
mOptionList = new ArrayList<>();
mBackgroundColorList = new ArrayList<>();
mResultList = new ArrayList<>();

mBeatBox = new BeatBox(mActivity);
mSounds = mBeatBox.getSounds();


private void initView()
setContentView(R.layout.activity_quiz);

imgFirstLife = (ImageView) findViewById(R.id.firstLife);
imgSecondLife = (ImageView) findViewById(R.id.secondLife);
imgThirdLife = (ImageView) findViewById(R.id.thirdLife);
imgFourthLife = (ImageView) findViewById(R.id.fourthLife);
imgFifthLife = (ImageView) findViewById(R.id.fifthLife);
btnSpeaker = (ImageButton) findViewById(R.id.btnSpeaker);
btnNext = (Button) findViewById(R.id.btnNext);

tvQuestionText = (TextView) findViewById(R.id.tvQuestionText);
tvQuestionTitle = (TextView) findViewById(R.id.tvQuestionTitle);

mRecyclerQuiz = (RecyclerView) findViewById(R.id.rvQuiz);
mRecyclerQuiz.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

mAdapter = new QuizAdapter(mContext, mActivity, mOptionList, mBackgroundColorList);
mRecyclerQuiz.setAdapter(mAdapter);

initToolbar(true);
setToolbarTitle(getString(R.string.quiz));
enableUpButton();
initLoader();



@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void loadData()
showLoader();

isSoundOn = AppPreference.getInstance(mActivity).getBoolean(AppConstants.KEY_SOUND, true);
setSpeakerImage();

loadJson();


@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void setSpeakerImage()
if (isSoundOn)
btnSpeaker.setImageResource(R.drawable.ic_speaker);
else
btnSpeaker.setImageResource(R.drawable.ic_speaker_not);




public void initListener()
btnSpeaker.setOnClickListener(new View.OnClickListener()
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View view)
isSoundOn = !isSoundOn;
AppPreference.getInstance(mActivity).setBoolean(AppConstants.KEY_SOUND, isSoundOn);
setSpeakerImage();

);

btnNext.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
if (!mUserHasPressed)
FragmentManager manager = getSupportFragmentManager();
DialogUtilities dialog = DialogUtilities.newInstance(getString(R.string.skip_text), getString(R.string.skip_prompt), getString(R.string.yes), getString(R.string.no), AppConstants.BUNDLE_KEY_SKIP_OPTION);
dialog.show(manager, AppConstants.BUNDLE_KEY_DIALOG_FRAGMENT);
else
updateResultSet();
setNextQuestion();


);

mAdapter.setItemClickListener(new ListItemClickListener()
@Override
public void onItemClick(int position, View view)
if (!mUserHasPressed)
int clickedAnswerIndex = position;
if (mItemList.get(mQuestionPosition).getCorrectAnswer() != -1)
for (int currentItemIndex = 0; currentItemIndex < mOptionList.size(); currentItemIndex++)
if (currentItemIndex == clickedAnswerIndex && currentItemIndex == mItemList.get(mQuestionPosition).getCorrectAnswer())
mBackgroundColorList.set(currentItemIndex, AppConstants.COLOR_GREEN);
mScore++;
mIsCorrect = true;
if (isSoundOn)
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_ZERO_INDEX));

else if (currentItemIndex == clickedAnswerIndex && !(currentItemIndex == mItemList.get(mQuestionPosition).getCorrectAnswer()))
mBackgroundColorList.set(currentItemIndex, AppConstants.COLOR_RED);
mWrongAns++;
if (isSoundOn)
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_SECOND_INDEX));

decreaseLifeAndStatus();
else if (currentItemIndex == mItemList.get(mQuestionPosition).getCorrectAnswer())
mBackgroundColorList.set(currentItemIndex, AppConstants.COLOR_GREEN);
((LinearLayoutManager) mRecyclerQuiz.getLayoutManager()).scrollToPosition(currentItemIndex);


else
mBackgroundColorList.set(clickedAnswerIndex, AppConstants.COLOR_GREEN);
mScore++;
mIsCorrect = true;
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_ZERO_INDEX));


mGivenAnsText = mItemList.get(mQuestionPosition).getAnswers().get(clickedAnswerIndex);
mCorrectAnsText = mItemList.get(mQuestionPosition).getAnswers().get(mItemList.get(mQuestionPosition).getCorrectAnswer());

mUserHasPressed = true;
mAdapter.notifyDataSetChanged();



);






public void decreaseLifeAndStatus()
mLifeCounter--;
setLifeStatus();


void increaseLifeAndStatus()
if (mLifeCounter < AppConstants.BUNDLE_KEY_MAX_LIFE)
mLifeCounter++;
setLifeStatus();



public void setLifeStatus()
switch (mLifeCounter)
case 1:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.GONE);
imgThirdLife.setVisibility(View.GONE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
case 2:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.GONE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
case 3:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.VISIBLE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
case 4:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.VISIBLE);
imgFourthLife.setVisibility(View.VISIBLE);
imgFifthLife.setVisibility(View.GONE);
break;
case 5:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.VISIBLE);
imgFourthLife.setVisibility(View.VISIBLE);
imgFifthLife.setVisibility(View.VISIBLE);
break;
default:
imgFirstLife.setVisibility(View.GONE);
imgSecondLife.setVisibility(View.GONE);
imgThirdLife.setVisibility(View.GONE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;





public void setNextQuestion()
if (isSoundOn)
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_FIRST_INDEX));

mUserHasPressed = false;
if (mQuestionPosition < mItemList.size() - 1 && mLifeCounter > 0)
mQuestionPosition++;
updateQuestionsAndAnswers();
else if (mQuestionPosition < mItemList.size() - 1 && mLifeCounter == 0)
FragmentManager manager = getSupportFragmentManager();
DialogUtilities dialog = DialogUtilities.newInstance(getString(R.string.reward_dialog_title), getString(R.string.reward_dialog_message), getString(R.string.yes), getString(R.string.no), AppConstants.BUNDLE_KEY_REWARD_OPTION);
dialog.show(manager, AppConstants.BUNDLE_KEY_DIALOG_FRAGMENT);
else
ActivityUtilities.getInstance().invokeScoreCardActivity(mActivity, ScoreCardActivity.class, mQuestionsCount, mScore, mWrongAns, mSkip, mCategoryId, mResultList, true);
AppPreference.getInstance(mActivity).setQuizResult(mCategoryId, mScore);



public void updateQuestionsAndAnswers()
mOptionList.clear();
mBackgroundColorList.clear();
((LinearLayoutManager) mRecyclerQuiz.getLayoutManager()).scrollToPosition(AppConstants.BUNDLE_KEY_ZERO_INDEX);

mOptionList.addAll(mItemList.get(mQuestionPosition).getAnswers());
mBackgroundColorList.addAll(mItemList.get(mQuestionPosition).getBackgroundColors());
mAdapter.notifyDataSetChanged();

mQuestionText = mItemList.get(mQuestionPosition).getQuestion();

tvQuestionText.setText(Html.fromHtml(mQuestionText));
tvQuestionTitle.setText(getString(R.string.quiz_question_title, mQuestionPosition + 1, mQuestionsCount));


public void quizActivityClosePrompt()
FragmentManager manager = getSupportFragmentManager();
DialogUtilities dialog = DialogUtilities.newInstance(getString(R.string.exit), getString(R.string.cancel_prompt), getString(R.string.yes), getString(R.string.no), AppConstants.BUNDLE_KEY_CLOSE_OPTION);
dialog.show(manager, AppConstants.BUNDLE_KEY_DIALOG_FRAGMENT);


private void loadJson()
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try
br = new BufferedReader(new InputStreamReader(getAssets().open(AppConstants.QUESTION_FILE)));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
catch (IOException e)
e.printStackTrace();
finally
try
br.close();
catch (Exception e)
e.printStackTrace();


parseJson(sb.toString());


public void parseJson(String jsonData)
try

JSONObject jsonObjMain = new JSONObject(jsonData);
JSONArray jsonArray = jsonObjMain.getJSONArray(AppConstants.JSON_KEY_QUESTIONNAIRY);

for (int i = 0; i < jsonArray.length(); i++)
JSONObject jsonObj = jsonArray.getJSONObject(i);

String question = jsonObj.getString(AppConstants.JSON_KEY_QUESTION);
int correctAnswer = Integer.parseInt(jsonObj.getString(AppConstants.JSON_KEY_CORRECT_ANS));
String categoryId = jsonObj.getString(AppConstants.JSON_KEY_CATEGORY_ID);

Log.d("TAG", categoryId.toString());

JSONArray jsonArray2 = jsonObj.getJSONArray(AppConstants.JSON_KEY_ANSWERS);
ArrayList<String> contents = new ArrayList<>();
ArrayList<String> backgroundColors = new ArrayList<>();
for (int j = 0; j < jsonArray2.length(); j++)
String item_title = jsonArray2.get(j).toString();
contents.add(item_title);
backgroundColors.add(AppConstants.COLOR_WHITE);

if (mCategoryId.equals(categoryId))
mItemList.add(new QuizModel(question, contents, correctAnswer, categoryId, backgroundColors));



mQuestionsCount = mItemList.size();
Collections.shuffle(mItemList);

hideLoader();
updateQuestionsAndAnswers();

catch (JSONException e)
e.printStackTrace();
showEmptyView();



@Override
public boolean onOptionsItemSelected(MenuItem item)
switch (item.getItemId())
case android.R.id.home:
quizActivityClosePrompt();
return true;

return super.onOptionsItemSelected(item);


@Override
public void onBackPressed()
quizActivityClosePrompt();


@Override
public void onComplete(Boolean isOkPressed, String viewIdText)
if (isOkPressed)
if (viewIdText.equals(AppConstants.BUNDLE_KEY_CLOSE_OPTION))
ActivityUtilities.getInstance().invokeNewActivity(mActivity, MainActivity.class, true);
else if (viewIdText.equals(AppConstants.BUNDLE_KEY_SKIP_OPTION))
mSkip++;
mIsSkipped = true;
mGivenAnsText = getResources().getString(R.string.skipped_text);
mCorrectAnsText = mItemList.get(mQuestionPosition).getAnswers().get(mItemList.get(mQuestionPosition).getCorrectAnswer());
updateResultSet();
setNextQuestion();
else if (viewIdText.equals(AppConstants.BUNDLE_KEY_REWARD_OPTION))
//TODO: mRewardedVideoAd.show();

else if (!isOkPressed && viewIdText.equals(AppConstants.BUNDLE_KEY_REWARD_OPTION))
ActivityUtilities.getInstance().invokeScoreCardActivity(mActivity, ScoreCardActivity.class, mQuestionsCount, mScore, mWrongAns, mSkip, mCategoryId, mResultList, true);
AppPreference.getInstance(mContext).setQuizResult(mCategoryId, mScore);
AppPreference.getInstance(mContext).setQuizQuestionsCount(mCategoryId, mQuestionsCount);



public void updateResultSet()
mResultList.add(new ResultModel(mQuestionText, mGivenAnsText, mCorrectAnsText, mIsCorrect, mIsSkipped));
mIsCorrect = false;
mIsSkipped = false;


@Override
protected void onDestroy()
super.onDestroy();
mBeatBox.release();




QUIZ ADAPTER


import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import com.vn.iambulance.prototype_20.R;
import com.vn.iambulance.prototype_20.listeners.ListItemClickListener;


public class QuizAdapter extends RecyclerView.Adapter<QuizAdapter.ViewHolder>

private Context mContext;
private Activity mActivity;

private ArrayList<String> mItemList;
private ArrayList<String> mColorList;
private ListItemClickListener mItemClickListener;

public QuizAdapter (Context mContext, Activity mActivity, ArrayList<String> mItemList, ArrayList<String> mColorList)
this.mContext = mContext;
this.mActivity = mActivity;
this.mItemList = mItemList;
this.mColorList = mColorList;


public void setItemClickListener(ListItemClickListener itemClickListener)
this.mItemClickListener = itemClickListener;



@Override
public QuizAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_quiz, parent, false);
return new QuizAdapter.ViewHolder(view, viewType, mItemClickListener);


public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener

private TextView tvItemTitle;
private CardView lytContainer;
private ListItemClickListener itemClickListener;


public ViewHolder(View itemView, int viewType, ListItemClickListener itemClickListener)
super(itemView);

this.itemClickListener = itemClickListener;
// Find all views ids
tvItemTitle = itemView.findViewById(R.id.answer_text);
lytContainer = itemView.findViewById(R.id.card_view);

lytContainer.setOnClickListener(this);



@Override
public void onClick(View view)
if (itemClickListener != null)
itemClickListener.onItemClick(getLayoutPosition(), view);




@Override
public int getItemCount()
return (null != mItemList ? mItemList.size() : 0);



@Override
public void onBindViewHolder(QuizAdapter.ViewHolder mainHolder, int position)
final String model = mItemList.get(position);
final String model1 = mColorList.get(position);

// setting data over views
mainHolder.tvItemTitle.setText(Html.fromHtml(model));
mainHolder.tvItemTitle.setBackgroundResource(mActivity.getResources().getIdentifier(model1, "drawable", mActivity.getPackageName()));





QUIZ MODEL


import android.os.Parcel;
import android.os.Parcelable;

import java.util.ArrayList;

public class QuizModel implements Parcelable
String question;
ArrayList<String> answers;
int correctAnswer;
String questinCategoryId;
ArrayList<String> backgroundColors;

public QuizModel (String question, ArrayList<String> answers, int correctAnswer, String questinCategoryId, ArrayList<String> backgroundColors)
this.question = question;
this.correctAnswer = correctAnswer;
this.answers = answers;
this.questinCategoryId = questinCategoryId;
this.backgroundColors = backgroundColors;


public String getQuestion()
return question;


public int getCorrectAnswer()
return correctAnswer;


public ArrayList<String> getAnswers()
return answers;


public String getQuestingCategoryId()
return questinCategoryId;


public void setBackgroundColors(ArrayList<String> backgroundColors)
this.backgroundColors = backgroundColors;


public ArrayList<String> getBackgroundColors()
return backgroundColors;


@Override
public int describeContents()
return 0;


@Override
public void writeToParcel(Parcel dest, int flags)
dest.writeString(question);
dest.writeList(answers);
dest.writeInt(correctAnswer);
dest.writeString(questinCategoryId);
dest.writeList(backgroundColors);


protected QuizModel (Parcel in)
question = in.readString();
in.readList(answers, QuizModel.class.getClassLoader());
correctAnswer = in.readInt();
questinCategoryId = in.readString();
in.readList(backgroundColors, QuizModel.class.getClassLoader());


public static Creator<QuizModel> getCREATOR()
return CREATOR;


public static final Creator<QuizModel> CREATOR = new Creator<QuizModel>()
@Override
public QuizModel createFromParcel(Parcel source)
return new QuizModel(source);


@Override
public QuizModel newArray(int size)
return new QuizModel[size];

;




and JSON database



"question": "Тривале перебування в умовах спеки викликало у людини спрагу. Сигналiзацiя вiд яких рецепторiв, перш за все, зумовила її розвиток? ",
"answers": [
" Натрiєвi рецептори гiпоталамусу",
" Осморецептори печiнки",
" Глюкорецептори гiпоталамусу",
" Барорецептори дуги аорти",
" Осморецептори гiпоталамусу"
],
"correct_answer":4,
"question_category":"1"
,



Source code



https://drive.google.com/open?id=1zJ-dap6zvThs4lnj8ujwG0qTBjkT_WbD



Thank you!!!




2 Answers
2



You can place Collections.shuffle (list) directly in the constructor something like that:


Collections.shuffle (list)


public QuizModel (String question, ArrayList<String> answers, int correctAnswer, String questinCategoryId, ArrayList<String> backgroundColors)
this.question = question;
this.correctAnswer = correctAnswer;
this.answers = answers;
Collections.shuffle(this.answers);
this.questinCategoryId = questinCategoryId;
this.backgroundColors = backgroundColors;



Or else you can define a separate method for this purpose:


public void shuffleAnswers()
Collections.shuffle(this.answers);



And call it from any place in your code where you've instantiated QuizModel:


quizModel.shuffleAnswers();






First metod don't work and second too. Sorry

– Vlad Bulan
Sep 9 '18 at 19:28







where i must to initialize the method quizModel.shuffleAnswers(); ???

– Vlad Bulan
Sep 10 '18 at 12:06







Place it in the constructor that doesn't have parcelable argument to shuffle answers before initialization.

– mpoznyak
Sep 10 '18 at 15:56


public class QuizModel implements Parcelable {
String question;
ArrayList<String> answers;
int correctAnswer;
String questinCategoryId;
ArrayList<String> backgroundColors;
String trueAnswer;


public QuizModel (String question, ArrayList<String> answers, int correctAnswer, String questinCategoryId, ArrayList<String> backgroundColors)
this.question = question;
this.correctAnswer = correctAnswer;
this.answers = answers;
shuffleAnswers();
this.questinCategoryId = questinCategoryId;
this.backgroundColors = backgroundColors;
this.trueAnswer = answers.get(correctAnswer);


private void shuffleAnswers()
Collections.shuffle(answers);
correctAnswer = answers.indexOf(trueAnswer);


public boolean isCorrect(String answer)
return trueAnswer.equals(answer);



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)