How to remove a question/image that was answered correctly the next time user opens the app/comes to the home screen in Android?

Viewed 45

I'm currently creating a mobile guessing game in Android Studio.

I'm struggling with, how will the image that was answered correctly will not show again when the activity is return to the home page or exits the application.

The code below is for the play activity, I used hashmap for the image and arraylist for the answers.

heroList.add("abaddon"); 
heroList.add("alchemist"); 
heroList.add("axe"); 
heroList.add("beastmaster"); 
heroList.add("brewmaster");

map.put(heroList.get(0), R.drawable.ic_s_abaddon); 
map.put(heroList.get(1), R.drawable.ic_s_alchemist);
map.put(heroList.get(2), R.drawable.ic_s_axe);
map.put(heroList.get(3), R.drawable.ic_s_beastmaster);
map.put(heroList.get(4), R.drawable.ic_s_brewmaster);
   
Collections.shuffle(heroList);
generateImage();

Generate image method:

private void generateImage(int index) {
    ArrayList<String> heroListTemp = (ArrayList<String>) heroList.clone();
    String cAns = heroList.get(index);
    heroListTemp.remove(cAns);
    Collections.shuffle(heroListTemp);
    ArrayList<String> newList = new ArrayList<>();
    newList.add(heroListTemp.get(0));
    newList.add(heroListTemp.get(1));
    newList.add(heroListTemp.get(2));
    newList.add(cAns);
    Collections.shuffle(newList);

    heroImage.setImageResource(map.get(heroList.get(index)));
}

Code for the button to check if the answer is right or wrong:

public void checkAnswer(View view){
    String answer = heroAns.getText().toString().toLowerCase().replaceAll("\\s","");
    String cAnswer = heroList.get(index);

    if(answer.equals(cAnswer)){
        index++;
        if(index > heroList.size() - 1){
            Toast.makeText(PlayEasy.this,"You Guessed it all!!!!", Toast.LENGTH_SHORT).show();
            finish();

        }
        else{
            Toast.makeText(PlayEasy.this,"Nice!", Toast.LENGTH_SHORT).show();
            heroAns.setText("");
            generateImage();
        }
    }
    else{
        Toast.makeText(PlayEasy.this,"Nope -_-", Toast.LENGTH_SHORT).show();
    }
}
1 Answers

You can achieve this multiple ways, one good way to start would be to use SharedPreferences. Once a player has answered a question, save a boolean value in SharedPreferences against a key for that question. Load all the keys from SharedPreferences when your app loads or resumes :)

Related