简体   繁体   English

共享首选项中存储的值

[英]value storing in Shared Preferences

hi I want to save my high score value through shared preferences. 您好,我想通过共享的首选项保存我的高分值。 but when I go to another activity and then get into same activity my high score value again begins with zero. 但是当我参加另一项活动然后又参加同一项活动时,我的高分值又从零开始。 I know its simple but I don't know what mistake I am doing. 我知道它很简单,但是我不知道自己在犯什么错误。 here is the example code. 这是示例代码。

    private static final String FORMAT = "%02d:%02d:%02d";
    int count = 0, high;
    int seconds , minutes;
    SharedPreferences sharedPreferences;
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        sharedPreferences = getPreferences(MODE_PRIVATE);
        int savedPref = sharedPreferences.getInt("HighScore", 0);

        final TextView counter=(TextView)findViewById(R.id.taptimes);
        final TextView countdown=(TextView)findViewById(R.id.countdown);
        final TextView highScore = (TextView)findViewById(R.id.highScore);
        final Button b1=(Button)findViewById(R.id.keypress);

        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                countClick();
            }

            private void countClick() {
                // TODO Auto-generated method stub
                count++;
                counter.setText(String.valueOf(count));
                if (count > high){

                    highScore.setText(Integer.toString(count));
                    high = count;

                    sharedPreferences = getPreferences(MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putInt("HighScore", high);
                    editor.commit();
                }
            }
        });


        new CountDownTimer(10000, 1000) {//CountDownTimer(edittext1.getText()+edittext2.getText()) also parse it to long

             public void onTick(long millisUntilFinished) {
                 countdown.setText("Time remaining: " + millisUntilFinished / 1000);
              //here you can have your logic to set text to edittext
             }

             public void onFinish() {
                 countdown.setText("Time Over!");
                 b1.setEnabled(false);
             }
            }
            .start();

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }


}

The only problem I see, is that you're not doing anything with savedPref : 我看到的唯一问题是,您没有对savedPref做任何事情:

int savedPref = sharedPreferences.getInt("HighScore", 0);

I think it should be: 我认为应该是:

high  = sharedPreferences.getInt("HighScore", 0);

Doesn't your IDE trigger a warning that savedPref is useless? 您的IDE不会触发警告savedPref无效吗?

I would suggest you to make a different class for shared preferences. 我建议您为共享首选项设置一个不同的类。 I have been using this way for long time now and it is very easy maintenance for shared preferences. 我已经使用这种方法很长时间了,对于共享首选项非常容易维护。 Here is my shared preference code 这是我的共享首选项代码

    public class AppSharedPreferences {

            private SharedPreferences appSharedPrefs;
            private SharedPreferences.Editor prefsEditor;
            private static AppSharedPreferences appSharedPrefrence;

            public AppSharedPreferences(Context context) {
            this.appSharedPrefs = context.getSharedPreferences("sharedpref", Context.MODE_PRIVATE);
            this.prefsEditor = appSharedPrefs.edit();
        }

        public AppSharedPreferences() {

        }

        public static AppSharedPreferences getsharedprefInstance(Context con) {
            if (appSharedPrefrence == null)
                appSharedPrefrence = new AppSharedPreferences(con);
            return appSharedPrefrence;
        }

        public SharedPreferences getAppSharedPrefs() {
            return appSharedPrefs;
        }

        public void setAppSharedPrefs(SharedPreferences appSharedPrefs) {
            this.appSharedPrefs = appSharedPrefs;
        }

        public SharedPreferences.Editor getPrefsEditor() {
            return prefsEditor;
        }

        public void Commit() {
            prefsEditor.commit();
        }

        public void clearallSharedPrefernce() {
            prefsEditor.clear();
            prefsEditor.commit();
        }
    public void setHelperId(int helperId)
    {
        this.prefsEditor=appSharedPrefs.edit();
        prefsEditor.putInt("helper_id", helperId);
        prefsEditor.commit();
    }
        public int getHelperId()
        {
            return appSharedPrefs.getInt("helper_id",0);
        }
}

for saving values in shared preference create get and set method as shown at end of code. 如要在共享首选项中保存值,请创建get和set方法,如代码结尾所示。 Let all other methods of the code as it is. 让代码的所有其他方法保持不变。

And to use this code in your class just create an instance of shared preference in your class like this 并在您的班级中使用此代码,只需在您的班级中创建一个共享首选项的实例,如下所示

appSharedPreferences= AppSharedPreferences.getsharedprefInstance(YourActivity.this) ;

i think the way you are retrieving and changing shared preferences might be the issue. 我认为您检索和更改共享首选项的方式可能是问题。 Try fetching an instance of shared preferences as follows 尝试如下获取共享首选项的实例

 sharedPreferences=context.getSharedPreferences(Constants.MYUSERPREF, 0); //the 0 in the initialization is for private mode.

Also, an important thing to do is after you change the values and call editor.commit(); 同样,重要的是在更改值并调用editor.commit(); also call editor.apply(); 还调用editor.apply(); to save the changes to sharedPreferences 将更改保存到sharedPreferences

Please create common class for your Application Follow bellow Steps : 请为您的应用程序创建通用类,按照以下步骤操作:

Step 1: 第1步:

Create Application level Class 创建应用程序级别的类

public class AppConfig extends Application {

private static AppConfig appInstance;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor sharedPreferencesEditor;
private static Context mContext;

@Override
public void onCreate()
{
    super.onCreate();
    appInstance = this;
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferencesEditor = sharedPreferences.edit();
    setContext(getApplicationContext());

}

public static Context getContext() {
    return mContext;
}

public static void setContext(Context mctx) {
    mContext = mctx;
}


public static AppConfig getAppInstance() {
    if (appInstance == null)
        throw new IllegalStateException("The application is not created yet!");
    return appInstance;
}

/**
 * Application level preference work.
 */
public static void preferencePutInteger(String key, int value) {
    sharedPreferencesEditor.putInt(key, value);
    sharedPreferencesEditor.commit();
}

public static int preferenceGetInteger(String key, int defaultValue) {
    return sharedPreferences.getInt(key, defaultValue);
}

public static void preferencePutBoolean(String key, boolean value) {
    sharedPreferencesEditor.putBoolean(key, value);
    sharedPreferencesEditor.commit();
}

public static boolean preferenceGetBoolean(String key, boolean defaultValue) {
    return sharedPreferences.getBoolean(key, defaultValue);
}

public static void preferencePutString(String key, String value) {
    sharedPreferencesEditor.putString(key, value);
    sharedPreferencesEditor.commit();
}

public static String preferenceGetString(String key, String defaultValue) {
    return sharedPreferences.getString(key, defaultValue);
}

public static void preferencePutLong(String key, long value) {
    sharedPreferencesEditor.putLong(key, value);
    sharedPreferencesEditor.commit();
}

public static long preferenceGetLong(String key, long defaultValue) {
    return sharedPreferences.getLong(key, defaultValue);
}

public static void preferenceRemoveKey(String key) {
    sharedPreferencesEditor.remove(key);
    sharedPreferencesEditor.commit();
}

public static void clearPreference() {
    sharedPreferencesEditor.clear();
    sharedPreferencesEditor.commit();
}

} }

Step 2: 第2步:

Define this class into Manifest.xml in Application tag like this 像这样在Application标签中的Manifest.xml中定义此类。

<application
    android:name=".AppConfig">
 </application>

Step 3: 第三步:

You can use below code into your activity 您可以在活动中使用以下代码

AppConfig.preferencePutInteger("HighScore",yourScore);
AppConfig.preferenceGetInteger("HighScore", 0)

In the OnCreate method I just missed these.. thanks for everyone 在OnCreate方法中,我只是错过了这些..谢谢大家

high = sharedPreferences.getInt("HighScore", 0);
 highScore.setText(Integer.toString(high));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM