值存储在共享首选项中

时间:2016-01-31 15:12:25

标签: java android android-studio

嗨我想通过共享偏好保存我的高分值。但当我去另一个活动然后进入相同的活动时,我的高分值再次从零开始。我知道它很简单,但我不知道我在做什么错。这是示例代码。

    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

    }


}

5 个答案:

答案 0 :(得分:1)

我看到的唯一问题是你没有对savedPref做任何事情:

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

我认为应该是:

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

您的IDE是否会触发savedPref无用的警告?

答案 1 :(得分:0)

我建议您为共享偏好设置不同的课程。我一直在使用这种方式很长时间,它很容易维护共享首选项。这是我的共享偏好代码

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

答案 2 :(得分:0)

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

var ws_http_binding = new WSHttpBinding();

ws_http_binding.Security.Mode = SecurityMode.Transport;

ChannelFactory<IInternal> factory = 
    new ChannelFactory<IInternal>(
        ws_http_binding,
        new EndpointAddress("https://MyMachine:8733/IInternal"));

var channel = factory.CreateChannel();

此外,重要的是在更改值并调用 sharedPreferences=context.getSharedPreferences(Constants.MYUSERPREF, 0); //the 0 in the initialization is for private mode. 之后 也请调用editor.commit();将更改保存到sharedPreferences

答案 3 :(得分:0)

请为您的应用程序创建公共课程遵循以下步骤:

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

}

第2步:

将此类定义为Application标记中的Manifest.xml,如此

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

第3步:

您可以将以下代码用于您的活动

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

答案 4 :(得分:0)

在OnCreate方法中,我错过了这些......感谢所有人

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