根据共享首选项设置图像视图的可见性

时间:2017-07-22 08:35:30

标签: java android uiimageview sharedpreferences visibility

我编写了一个测验应用程序。我已经设置了如果高分超过10,将永久显示ImageView。在重新启动应用程序时也能正常工作,唯一的问题是,如果用户达到例如11的高分,并且在测验开始后直接回答正确然后错误,则ImageView将消失。共享首选项位于主要活动(测验活动)中,并且将是Menu2(第二个活动)中的calles。

测验活动java:

  RuntimeError                              Traceback (most recent call 
  last)
  <ipython-input-15-4b8522aa1eb0> in <module>()
         3 url = 'http://localhost:9000/spend_api'
         4 files = {'file': ('Test_data_final.csv')}
   ----> 5 r = request.post(url,files=files)
         6 
         7 

      C:\Users\pavansubhash_t\AppData\Local\Continuum\Anaconda2\lib\site -
    packages\werkzeug\local.pyc in __getattr__(self, name)
         345         if name == '__members__':
    346             return dir(self._get_current_object())
--> 347         return getattr(self._get_current_object(), name)
    348 
    349     def __setitem__(self, key, value):

C:\Users\pavansubhash_t\AppData\Local\Continuum\Anaconda2\lib\site-packages\werkzeug\local.pyc in _get_current_object(self)
    304         """
    305         if not hasattr(self.__local, '__release_local__'):
--> 306             return self.__local()
    307         try:
    308             return getattr(self.__local, self.__name__)

C:\Users\pavansubhash_t\AppData\Local\Continuum\Anaconda2\lib\site-packages\flask\globals.pyc in _lookup_req_object(name)
     35     top = _request_ctx_stack.top
     36     if top is None:
---> 37         raise RuntimeError(_request_ctx_err_msg)
     38     return getattr(top, name)
     39 

RuntimeError: Working outside of request context.

菜单2:

       @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);
    }

}

}

2 个答案:

答案 0 :(得分:0)

在您updateScore中保存数据,无论得分是多少,因此您删除旧值并使用新值进行更改,因此您需要阅读旧分数并将其与mScore进行比较这个:

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();
}

答案 1 :(得分:0)

这是因为你有以下代码

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

}

检查&#34; currentScore&#34;因此,如果用户在第二次播放时只找到1个答案,那么它将变为1,因此图像不会显示。 我注意到你有一个当前得分的sharedPref,你也有意图传递它。你还有另一个sharedPref?我的建议是只有意图传递它,然后检查它是否为高分,然后将其保存到sharedPref。并且只有一个sharedPref。

修改

从updateScore

中删除以下代码
SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("currentscore", mScore);
editor.apply();

然后使用类似

的内容删除/编辑菜单2中的所有共享首选代码
SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);

//first time high score
if (sharedPreferences.getInt("highScore", 0) == 0)
{
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("highScore", mScore );
    editor.apply();
}
else
{
    int oldScore = sharedPreferences.getInt("highScore", 0);

    //new high score
    if (mScore  > oldScore)
    {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("highScore", mScore );
        editor.apply();
    }
}