简体   繁体   English

Android 共享首选项

[英]Android sharedpreferences

I've been following this tutorial and i am stuck.我一直在关注教程,但我被卡住了。

public class Main extends Activity {

    SharedPreferences mPrefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        firstRunPreferences();

        if(getFirstRun())
        {
            Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
            setRunned();  
        }
        else
        {           
            Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
        }

    }

    public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }
    public void setRunned() {  
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }
    public void firstRunPreferences() {
        Context mContext = Main.this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); 
     }

}`

Everytime i run it in Eclipse it says "not firstrun".每次我在 Eclipse 中运行它时,它都会显示“不是首次运行”。 I guess the preferences reset every time the app is reinstalled, so what is wrong with the code?我猜每次重新安装应用程序时都会重置首选项,那么代码有什么问题? As far as i remember, i saw once "firstrun".据我记得,我曾经看过一次“firstrun”。

Thanks谢谢

I am assuming you are using the Emulator to run your app.我假设您正在使用模拟器来运行您的应用程序。 Are you closing the emulator between runs?你在运行之间关闭模拟器吗?

Check if you have the "Wipe User Data" checkbox ticked in the Target tab of your Debug run configuration in Eclipse.检查您是否在 Eclipse 的调试运行配置的目标选项卡中勾选了“擦除用户数据”复选框。

SharedPreferences are not cleaned by uninstall. SharedPreferences 不会被卸载清除。

If you want something cleaned after reinstall, put a field in your database.如果您想在重新安装后清理某些内容,请在数据库中放置一个字段。

Stéphane斯蒂芬妮

I'm not sure but I think SharedPreferences are removed when uninstalling, but not when updating an app.我不确定,但我认为 SharedPreferences 在卸载时会被删除,但在更新应用程序时不会。

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

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