Setting up the visibility of an Image View depending on Shared Preferences

Viewed 250

I Programm a Quiz App. I already set up that if the highscore is over 10, an ImageView will be shown permanently. That works very fine also on restart of the app, the only problem is that if the user reachs a highscore of for example 11 and directly later on the beginning of the quiz answers correctly and then false, the ImageView disappears. The shared preference is in the Main Activity (Quiz activity) and will be calles in Menu2 (second Activity).

Quiz Activity java:

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


    //Randromizes the row of the questions
    QuestionLibrary q = new QuestionLibrary();
    System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
            q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
    q.shuffle();
    System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
            q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
    mQuestionLibrary.shuffle();
    //End randomizer

    //We need this for the NAVIGATION DRAWER
    mToolbar = (Toolbar) findViewById(R.id.nav_action);

    setSupportActionBar(mToolbar);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Able to see the Navigation Burger "Button"


    NavigationView mNavigationView = (NavigationView) findViewById(R.id.nv1);
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem){
            switch (menuItem.getItemId()){
                case(R.id.nav_stats): //If nav stats selected Activity 2 will show up
                    Intent accountActivity = new Intent(getApplicationContext(),Menu2.class);
                    startActivity(accountActivity);
            }
            return true;
        }
    });

        //Initialise

        mScoreView = (TextView) findViewById(R.id.score_score);
        mQuestionView = (TextView) findViewById(R.id.question);
        mButtonChoice1 = (Button) findViewById(R.id.choice1);
        mButtonChoice2 = (Button) findViewById(R.id.choice2);
        mButtonChoice3 = (Button) findViewById(R.id.choice3);


        updateQuestion(); //New question appears

        //Start of Button Listener1 -> if true, next question appears +score +1[] Else menu 2 will show
        mButtonChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice1.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();



                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();


                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score",mScore); //pass score to Menu2
                    startActivity(intent);




                }
            }


        });
        //End of Button Listener1

        //Start of Button Listener2
        mButtonChoice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice2.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();




                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Oh... wrong your score is 0", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score",mScore); //pass score to Menu2
                    startActivity(intent);




                }
            }


        });
        //End of Button Listener2

        //Start of Button Listener3
        mButtonChoice3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice3.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();




                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Come on, that was not so hard...", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score",mScore); //pass score to Menu2
                    startActivity(intent);




                }
            }


        });
        //End of Button Listener3

    }


    private void updateQuestion() {
    //If the max. number of questions is reached, menu2 will be open if not  
    //a  new quiz selection appears
    if (mQuestionNumber < mQuestionLibrary.getLength()) {

    mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));

    mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));

    mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));

    mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));

        mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
        mQuestionNumber++;
    }
    else {
        Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(QuizActivity.this, Menu2.class);
        intent.putExtra("score",mScore); //pass score to Menu2
        startActivity(intent);


    }

}

private void updateScore ( int point){
    mScoreView.setText("" + mScore);
    //Shared preferences = a variabe (mScore) gets saved and call up in another activity
    SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putInt("currentscore", mScore);
    editor.apply();
}

    @Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
    public boolean onOptionsItemSelected (MenuItem item){
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

Menu 2:

      public class Menu2 extends AppCompatActivity {




private DrawerLayout mDrawerLayout2;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private Button popup;
private PopupWindow popupWindow;private LayoutInflater layoutInflater; //Alows to add a new layout in our window



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

    SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
    int applyView =sharedpreferences.getInt("currentscore",0);
     TextView txtScore = (TextView) findViewById(R.id.textScore2);
     TextView txtHighScore = (TextView)findViewById(R.id.textHighScore);
     ImageView imgTrophyView1 = (ImageView)findViewById(R.id.trophy1);
     ImageView imgTrophyView2 = (ImageView) findViewById(R.id.trophy2);
     Button bttPOPUP =(Button)findViewById(R.id.enablePOPUP);

    Intent intent = getIntent();
    int mScore = intent.getIntExtra ("score",0);
    txtScore.setText("Your score is: " + mScore);




    SharedPreferences mypref =getPreferences(MODE_PRIVATE);
    int highScore = mypref.getInt("highScore", 0);
    if (highScore>= mScore)
        txtHighScore.setText("High score: " + highScore);


    else{
        txtHighScore.setText("New highscore: " + mScore);

        SharedPreferences.Editor editor = mypref.edit();
        editor.putInt("highScore",mScore);
        editor.apply();

    }

    if (applyView >=10) {
        imgTrophyView1.setVisibility(View.VISIBLE);
        bttPOPUP.setVisibility(View.VISIBLE);
    }
        if (applyView >= 20){
            imgTrophyView2.setVisibility(View.VISIBLE);

    }


    popup = (Button)findViewById(R.id.enablePOPUP);
    popup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            layoutInflater =(LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
            ViewGroup container = (ViewGroup)layoutInflater.inflate(R.layout.popup_menu2_1,null);
            popupWindow = new PopupWindow(container,1000,980,true); //400,400=popUp size, true = makes that we can close the pop up by simply click out of the window
            popupWindow.showAtLocation(mDrawerLayout2, Gravity.CENTER, 0, 0);
            mDrawerLayout2.setAlpha((float) 0.1);

            container.setOnTouchListener(new View.OnTouchListener(){

                @Override

                        public boolean onTouch(View view, MotionEvent motionEvent  ){
                        mDrawerLayout2.setAlpha((float) 1);
                              popupWindow.dismiss();

                        return true;

                }

            });


            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

                @Override
                public void onDismiss() {
                    mDrawerLayout2.setAlpha((float) 1);
                    popupWindow.dismiss();

                }
            });
        }
    });





    mToolbar = (Toolbar)findViewById(R.id.nav_action);
    setSupportActionBar(mToolbar);
    mDrawerLayout2 = (DrawerLayout) findViewById(R.id.drawerLayout2);

    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout2, R.string.open, R.string.close);
    mDrawerLayout2.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    NavigationView mNavigationView = (NavigationView) findViewById(nv2);
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem){
            switch (menuItem.getItemId()){
                case(R.id.nav_home2):
                    Intent accountActivity2 = new Intent(getApplicationContext(),QuizActivity.class);
                    startActivity(accountActivity2);

            }
            return true;
        }
    });}

            public void onClick(View view) {

                Intent intent = new Intent(Menu2.this, QuizActivity.class);
                startActivity(intent);

}




@Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
public boolean onOptionsItemSelected(MenuItem item) {
    if (mToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);


}

}

2 Answers
Related