1

I am making a game like logo quiz. I have the question activity and the levels activity so when users answer correctly they score 1. Then I want to put the score in the levels activity so in that way users could unlock the next level, but I don't want users leave the question activity and until now I have only found this method:

Intent resultIntent = new Intent(this, NextActivity.class);

resultIntent.putExtra("score", score);

startActivity(resultIntent);

However, with this method the user goes to the levels activity.

I will leave my code for reference:

public class Big extends Activity {

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

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true); }

    public boolean onOptionsItemSelected(MenuItem item){
        Intent myIntent = new Intent(getApplicationContext(), Level1.class);
        startActivityForResult(myIntent, 0);
        return true;

    }


    private Button buttonSaveMem1;
    private EditText escrive; 
    private TextView respuest;
    private String [] answers;
    int score=0;
    int HighScore;

    private String saveScore = "HighScore";

    private int currentQuestion;



         public void init()
         {

            answers = new String[]{"Big"};      
            buttonSaveMem1 = (Button)findViewById(R.id.button1);     
            respuest = (TextView) findViewById(R.id.textView2); 

            escrive = (EditText) findViewById(R.id.editText1);
            buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);

            LoadPreferences();
           }

         Button.OnClickListener buttonSaveMem1OnClickListener
            = new Button.OnClickListener(){

             @Override    
                public void onClick(View arg0) {    
                    checkAnswer();


                    // TODO Auto-generated method stub
                       SavePreferences();
                       LoadPreferences();
             }};









         public boolean isCorrect(String answer)    
         {     
             return (answer.equalsIgnoreCase(answers[currentQuestion]));
             } 


         public void checkAnswer()  {     
                String answer = escrive.getText().toString();  
                if(isCorrect(answer)) {
                    update();

                    respuest.setText("You're right!" + "   The Answer is " + answer + "    your score is:" + score +"  " +
                            "HighScore:  " + HighScore);
                    score =1;



                }
                else {
                    respuest.setText("Sorry, The answer is not right!");

                }




            }
         private void update() {
         if (score > HighScore)
            { HighScore = score; }
            }


         private void SavePreferences(){
                SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("MEM1", respuest.getText().toString());
                sharedPreferences.edit().putInt(saveScore, HighScore).commit();
                editor.commit();
               }

               private void LoadPreferences(){
                SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
                String strSavedMem1 = sharedPreferences.getString("MEM1", "");
                HighScore = sharedPreferences.getInt(saveScore, 0);
                respuest.setText(strSavedMem1);

               }









    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

And here is the levels activity:

public class Level extends Activity {

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


    Button salir = (Button) findViewById(R.id.button3); 
    salir.setOnClickListener( new View.OnClickListener() { 


        @Override public void onClick(View v) {
            startActivity(new Intent(Level.this, MainActivity.class)); }
    }
            )
            ;


Button leve2 = (Button) findViewById(R.id.button1); 
    leve2.setOnClickListener( new View.OnClickListener() { 


        @Override public void onClick(View v) {
            startActivity(new Intent(Level.this, Level2.class)); }
    }
            )
            ;  }   
    Button leve1 = (Button) findViewById(R.id.button1); 
    leve1.setOnClickListener( new View.OnClickListener() { 


        @Override public void onClick(View v) {
            startActivity(new Intent(Level.this, Level1.class)); }
    }
            )
            ; 



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.level, menu);
        return true;
    }

}

Thanks for the help!

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
user3310885
  • 21
  • 1
  • 4
  • It looks like you're already using the SharedPreferences to save the User's high score, why not use them to store the score earned on the question and then fetch that score when the user returns to the levels activity? – dsrees Feb 17 '14 at 00:44
  • 3
    Jesus... Format your code please. – Michael Yaworski Feb 17 '14 at 00:55

4 Answers4

0

You can make make the score as static and then modify it from the other activity class. IT would automatically change it in the original.

ucsunil
  • 7,378
  • 1
  • 27
  • 32
  • 1
    Declaring the variable as static and allowing it to be directly modified from another file is bad form. It might work, and is easy in small cases, but can lend to very buggy code which can be a nightmare to fix. – dsrees Feb 17 '14 at 00:47
0

In your questions activity, store the score of the user in the SharedPreferences

    SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    prefs.edit.putLong(USER_SCORE, score).commit();

And then when you return to your level's activity, you can fetch from the preferences.

    SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    long userScore = prefs.getLong(USER_SCORE, 0);

USER_SCORE is just a string key like USER_SCORE = "user_score" to allow the device to find the date you stored in the prefs.

Shared preferences are saved to the phone and not accessible except through the app that they belong to. So upon starting the app again, you can get the User's score that was saved last time they used the app.

dsrees
  • 6,116
  • 2
  • 26
  • 26
  • 1
    His very requirement is that you should not got to the other activity to see this change. – ucsunil Feb 17 '14 at 00:53
  • Thank you it helped me a lot, but now do you know how can I put all the scores in one, I have tried: SCORE = (userScore + userScore1 + userScore2) but it doesn't work – user3310885 Feb 18 '14 at 03:21
  • 1
    Each time you add a score to the prefs using the key USER_SCORE it overrides the data that was previously there. Try keeping the total score in the preferences by pulling from the prefs, adding the new score to the total score, and storing that back into the prefs – dsrees Feb 18 '14 at 04:36
0

Store the score in a SharedPreferences instead of passing it to Level in an intent. You can then retrieve that score within the levels Activity (or any other for that matter), whenever the user may navigate there. You already use SharedPreferences in your code with:

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);

However that returns a Shared Preference using the calling Activity's class name as the Shared Preference name, i.e. those preference values are private to your Activity 'Big'. To use preference values that have application scope, use getSharedPreferences(), providing a Shared Preferences name:

SharedPreferences sharedPreferences = getSharedPreferences("MYPREFS", Activity.MODE_PRIVATE);

Create an Editor from that and store the value of 'score'. Then retrieve it your Level activity, most likely in its onCreate().

NigelK
  • 8,255
  • 2
  • 30
  • 28
0

After looking here and there, I've finally found out my answer to this question by following other answers and I basically used the following combination of codes to do so.

  1. In a first activity:

    • import:

      import android.content.Context;
      
      import android.content.SharedPreferences;
      
    • declare:

      public static int totalCount;
      
    • and add onCreate():

      SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = prefs.edit();
      
      totalCount = prefs.getInt("counter", 0);`
      totalCount++;`
      editor.putInt("counter", totalCount);`
      editor.apply();`
      
  2. Then, on a second activity:

    • import:

      import static com.example.myapp.totalCount
      
    • and add onCreate():

      ((TextView) findViewById(R.id.text_view_id)).setText(String.valueOf(totalCount));
      
  3. In the layout for the second activity:

    • place a TextView with:

      android:id="@+id/text_view_id"
      

And pay attention to what the documentation says about naming shared preferences.

When naming your shared preference files, you should use a name that's uniquely identifiable to your app. An easy way to do this is prefix the file name with your application ID. For example: "com.example.myapp.PREFERENCE_FILE_KEY"

JorgeAmVF
  • 1,660
  • 3
  • 21
  • 32