Java 共享首选项中的值存储

Java 共享首选项中的值存储,java,android,android-studio,Java,Android,Android Studio,嗨,我想通过共享首选项保存我的高分值。但当我参加另一项活动,然后又参加同一项活动时,我的高分值又从零开始。我知道这很简单,但我不知道我犯了什么错误。下面是示例代码 private static final String FORMAT = "%02d:%02d:%02d"; int count = 0, high; int seconds , minutes; SharedPreferences sharedPreferences; @SuppressLin

嗨,我想通过共享首选项保存我的高分值。但当我参加另一项活动,然后又参加同一项活动时,我的高分值又从零开始。我知道这很简单,但我不知道我犯了什么错误。下面是示例代码

    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

    }


}

我建议你为共同的偏好设置一个不同的课程。我已经使用这种方式很长时间了,它非常容易维护共享首选项。这是我的共享偏好代码

    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);
        }
}
要在共享首选项中保存值,请创建get和set方法,如代码末尾所示。让代码的所有其他方法保持原样

要在类中使用此代码,只需在类中创建一个共享首选项实例,如下所示

appSharedPreferences= AppSharedPreferences.getsharedprefInstance(YourActivity.this) ;
<application
    android:name=".AppConfig">
 </application>

我认为您检索和更改共享首选项的方式可能是问题所在。尝试获取共享首选项的实例,如下所示

 sharedPreferences=context.getSharedPreferences(Constants.MYUSERPREF, 0); //the 0 in the initialization is for private mode.
另外,要做的一件重要事情是在更改值并调用
editor.commit()之后

同时调用
editor.apply()要保存对SharedReferences的更改,请按照以下步骤为应用程序创建公共类:

第1步:

创建应用程序级类

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

第二步:

在应用程序标记中将此类定义为Manifest.xml,如下所示

appSharedPreferences= AppSharedPreferences.getsharedprefInstance(YourActivity.this) ;
<application
    android:name=".AppConfig">
 </application>

我看到的唯一问题是,您没有使用
savedPref
执行任何操作:

int savedPref = sharedPreferences.getInt("HighScore", 0);
我认为应该是:

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

您的IDE是否会触发一个警告,指出
savedPref
是无用的?

在OnCreate方法中,我刚刚错过了这些。。谢谢大家

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

对我来说,这个代码很好用。如果我多次启动此活动,我就能够获得存储的值。可能您正在重置第二个活动中的值。第二个活动与此无关。。我不知道为什么不保存值。您在哪里使用savedPref?对不起,我在一个移动屏幕上,我看不到更好的,但我想你没有初始化。我的代码中有错误吗?重新启动应用程序后,高值再次设置为零。我认为,您的值设置代码工作不正常,因为当您尝试获取它时,它会返回默认值。您可以尝试使用我提供的代码,看看它是否工作正常。这是一个正确的方法和简单的维护我不知道如何实现这个代码在我的项目。。。我的意思是我不知道如何使用那个代码,只是创建一个新类并复制粘贴那个代码。还要创建新的get和set方法,正如我在代码中为您要存储的值所提供的那样,到底发生了什么?您是否已调用
editor.apply()提交的所有地方?是的,我提交了,但仍然没有工作。。我不知道为什么它没有保存价值你能更新你的问题代码以准确反映现在正在做什么吗?我想我已经弄明白了。。您正在检查
是否(计数>高){}
但变量高尚未初始化。您正在将从共享首选项获得的值分配给
int savedPref
。可能将其更改为
inthigh=SharedReferences.getInt(“HighScore”,0)会成功的@shubhankars只要想一想,如果你做了
int-high
你是在声明一个局部变量。。。除了这个小细节(去掉
int
)之外,我完全同意。