Android Using SharedPreferences to save and retrieve values - Counter

孤人 提交于 2019-12-21 21:49:08

问题


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.

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.

The code i am using is as follows:

MainActivity.java

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

            }
        });
       }
}

Results.java

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

}

Any help to guide me would be much appreciated.Thank you


回答1:


You will have to set GAME_PREFERENCES_SCORE in MainActivity. Do something like this after counter++:

getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE).edit().setInt(GAME_PREFERENCES_SCORE, counter). commit();




回答2:


Simply make a Preferences class

public class Preferences {

String MASTER_NAME = "mysticmatrix_master";
SharedPreferences mysticMatrixPref;

Preferences(Context context) {
    mysticMatrixPref = context.getSharedPreferences(MASTER_NAME, 0);
}

public void setAddCount(int count) {
    SharedPreferences.Editor prefEditor = mysticMatrixPref.edit();
    prefEditor.putInt("count", count);
    prefEditor.commit();

}

public int getAddCount() {
    return mysticMatrixPref.getInt("count", 0);
}
}

and in your MainActivity.java put this code

public class MainActivity extends Activity implements OnClickListener {

ImageButton add;
Preferences cpObj;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    preferences = new Preferences(getApplicationContext());

    /*
     * getting the count variable and adding 1 in that to check the condition of showing rate activity and adds
     */
     add = (Button) findViewById (R.id.bAdd);
    add.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
         cpObj = new Preferences(getApplicationContext());
         cpObj.setAddCount(cpObj.getAddCount() + 1);

        }
    });
    }
    }

And in your result activity just get the count's value

import android.content.Context;
public class Results extends MainActivity{
Preferences cpObj;

public void onCreate(Bundle savedInstanceState) {

     preferences = new Preferences(getApplicationContext());
    setContentView(R.layout.results);

    final TextView DisplayResults =
            (TextView) findViewById(R.id.bAdd);
            DisplayResults.setText(cpObj.getAddCount());
            }
    } }

By this you will get the default value of result as '0' and you can set that in your Preferences class




回答3:


Use a method like this:

    public static void SavePreference(Context context, String key, Integer value) {
    SharedPreferences.Editor editor = PreferenceManager
            .getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE)
            .edit();
    editor.putInt(key, value);
    editor.commit();
}

and in you onclick after counter++ add this:

SavePereference(context, "GAME_PREFERENCES_SCORE", counter);


来源:https://stackoverflow.com/questions/12872032/android-using-sharedpreferences-to-save-and-retrieve-values-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!