2017-07-22 3 views
1

I Programm a Quiz App. J'ai déjà mis en place que si le highscore est supérieur à 10, un ImageView sera affiché en permanence. Cela fonctionne très bien aussi au redémarrage de l'application, le seul problème est que si l'utilisateur atteint un highscore de par exemple 11 et directement plus tard au début du quiz répond correctement, puis faux, le ImageView disparaît. La préférence partagée est dans l'activité principale (activité Quiz) et sera appelée dans Menu2 (deuxième activité).Configuration de la visibilité d'une vue d'image en fonction des préférences partagées

Quiz Activité 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); 


} 

}

Répondre

0

dans votre updateScore vous enregistrez les données, peu importe ce que le score est, de sorte que vous supprimez la valeur ancienne et changez-le avec le nouveau, donc vous devez lire le vieux score et le comparer avec le mScore comme ceci:

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

Bonjour! Où dois-je insérer ceci? – Alan

+0

Je l'insère sous updateScore mais maintenant l'image n'apparait même pas ... – Alan

+0

Salut son oeuvre parfaitement que si j'atteins par exemple le score 10 et directement après j'atteins un score de fx. 1 alors il reste en permanence .. Je veux qu'il apparaisse déjà quand le HIGHSCORE est "atteint" – Alan

0

Cela se produit parce que vous avez le code suivant

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

} 

qui vérifie la « currentScore » si l'utilisateur trouve seulement 1 réponse la deuxième fois qu'il joue, il va être 1 si l'image a gagné » t montrer. Je remarque que vous avez un sharedPref pour le score actuel et que vous le transmettez également avec intention. Vous avez également un autre sharedPref? Ma suggestion est de le passer seulement avec l'intention et ensuite vérifier si c'est un highscore, alors enregistrez-le dans sharedPref. Et seulement un sharedPref.

EDIT

Supprimer le code ci-dessous de updateScore

SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedpreferences.edit(); 
editor.putInt("currentscore", mScore); 
editor.apply(); 

Retirez ensuite/modifier tout le code pref partagé que vous avez dans le menu 2 avec quelque chose comme ça

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

Bonjour! Où dois-je insérer ce code Monsieur? Dans Menu2? et dois-je supprimer quelque chose? – Alan

+0

Oui, vous devez supprimer updateScore de votre QuizActivity puisque vous passez le score avec une intention, puis modifiez votre code sharedPref dans votre autre activité. Ou changer le apllyView dans votre Menu2 pour être highScore – nKalai

+0

Donc je dois supprimer le score de mise à jour dans Quiz Activity et dans Menu2 quel code dois-je insérer? Je ne sais pas où mettre dans ce code Sir – Alan