title: Android Using SharedPreferences to save and retrieve values - Counter
body: <p>Hello I am new to android and actually i am developing a application whereby the user would be clicking on a button and the button should record the click event -  the counter should be incremented at each time the button is clicked. The button would be displayed in one activity and once the user has clicked the button, another activity would be displayed whereby the results would be shown.</p>
  
  <p>Actually i am having problems in assigning the sharedPreferences to the button and then displaying it into the next activity hence having the number of clicks.</p>
  
  <p>The code i am using is as follows:</p>
  
  <p>MainActivity.java</p>
  
  <pre><code>import android.app.Activity;
  import android.content.Intent;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Button;
  
  public class MainActivity extends Activity {
      /** Called when the activity is first created. */
  
      /** Declare the variables being used */
      public static final String GAME_PREFERENCES = "GamePrefs";
  
       public static final String GAME_PREFERENCES_SCORE = "Score"; // Integer
      int counter;
      Button add;
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          counter = 0;
          add = (Button) findViewById (R.id.bAdd);
          add.setOnClickListener(new View.OnClickListener() {
  
              public void onClick(View v) {
                  // TODO Auto-generated method stub
                  counter++;
  
                  Intent openClickActivity2 = new Intent("com.android.jay.Results");
                  startActivity(openClickActivity2);
  
              }
          });
         }
  }
  </code></pre>
  
  <p>Results.java</p>
  
  <pre><code>import android.content.Context;
  import android.content.SharedPreferences;
  import android.os.Bundle;
  import android.widget.TextView;
  public class Results extends MainActivity{
  
      public void onCreate(Bundle savedInstanceState) {
  
          SharedPreferences mGameSettings;
          super.onCreate(savedInstanceState);
          mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
          setContentView(R.layout.results);
  
          final TextView DisplayResults =
                  (TextView) findViewById(R.id.bAdd);
                  if (mGameSettings.contains(GAME_PREFERENCES_SCORE)) {
                  DisplayResults.setText(mGameSettings.getString(GAME_PREFERENCES_SCORE, “counter”));
                  }
          }
  
  }
  </code></pre>
  
  <p>Any help to guide me would be much appreciated.Thank you </p>