How to save user state in Android?

前端 未结 1 1412
后悔当初
后悔当初 2020-12-04 03:26

I have an application for my Nokia mobile. When I install that software and try to use it for the first time, it asks me for a password and to confirm that password. Then

相关标签:
1条回答
  • 2020-12-04 03:33

    As far as I understand the question is how to realize saving a "user state" in application. If so, you can use SharedPreferences (esspecially if you have only one user state) or database. If you launch app firs time it search data in shared preferances or db. If there is no information app asks user to enter and confirm password after that it writes data to SP or db.

    Prety simpe example how to use SP. Writing to SP:

        SharedPreferences mySharedPreferences = 
                context.getSharedPreferences("PASSWORD_PREFS", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
    
        editor.putString("PSSWORD", password);
        editor.commit();
    

    Reading SP:

        SharedPreferences mySharedPreferences = context.getSharedPreferences(PREFS, Activity.MODE_PRIVATE);
        String password = mySharedPreferences.getString(PASSWORD, null);
    

    You can use edit.apply() insted of commit(). It is recommended by Android team. But this method is for API Level 9. You can read about it here http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()

    0 讨论(0)
提交回复
热议问题