共享首选项出错,ImageView消失

时间:2017-07-22 10:57:46

标签: java android sharedpreferences visibility

我编写了一个测验应用程序,它以主要活动(测验活动)开始。我已经设置了如果高分超过10,ImageView将永久显示在Menu2 Activity中。在重新启动应用程序时也能正常工作,唯一的问题是,如果用户达到例如11的高分,则不会立即显示图片,如果用户直接点击后会显示例如3分的分数将永久显示。如何设置在达到高分时显示图片?

测验活动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 mypref =getPreferences(MODE_PRIVATE);
    int highScore = mypref.getInt("highScore", 0);
    if(mScore> highScore){
        SharedPreferences.Editor editor = mypref.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);
    }


}

菜单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);



    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.commit();


    }
    if (highScore >= 10) {
        imgTrophyView1.setVisibility(View.VISIBLE);
        bttPOPUP.setVisibility(View.VISIBLE);
    }
    if (highScore >= 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);






}

}

1 个答案:

答案 0 :(得分:0)

请编辑此行

SharedPreferences mypref = getPreferences(MODE_PRIVATE);

SharedPreferences mypref = getPreferences("MyPreferences",MODE_PRIVATE);