Best place for storing user login credentials in Android

后端 未结 3 1222
南笙
南笙 2020-12-08 03:24

I am creating an android app, and i cannot(?) find any information on authenticating a user of the app on Google App Engine (without using the user\'s Google Account).Is it

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 03:52

    Consider SharedPreferences for this, like...

    public class PrefUtils {
        public static final String PREFS_LOGIN_USERNAME_KEY = "__USERNAME__" ;
        public static final String PREFS_LOGIN_PASSWORD_KEY = "__PASSWORD__" ;
    
        /**
         * Called to save supplied value in shared preferences against given key.
         * @param context Context of caller activity
         * @param key Key of value to save against
         * @param value Value to save
         */
        public static void saveToPrefs(Context context, String key, String value) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            final SharedPreferences.Editor editor = prefs.edit();
            editor.putString(key,value);
            editor.commit();
        }
    
        /**
         * Called to retrieve required value from shared preferences, identified by given key.
         * Default value will be returned of no value found or error occurred.
         * @param context Context of caller activity
         * @param key Key to find value against
         * @param defaultValue Value to return if no data found against given key
         * @return Return the value found against given key, default if not found or any error occurs
         */
        public static String getFromPrefs(Context context, String key, String defaultValue) {
            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
            try {
                return sharedPrefs.getString(key, defaultValue);
            } catch (Exception e) {
                 e.printStackTrace();
                 return defaultValue;
            }
        }
    }
    

    Simply use these methods like,

    // Saving user credentials on successful login case
    PrefUtils.saveToPrefs(YourActivity.this, PREFS_LOGIN_USERNAME_KEY, username);
    PrefUtils.saveToPrefs(YourActivity.this, PREFS_LOGIN_PASSWORD_KEY, password);
    
    // To retrieve values back
    String loggedInUserName = PrefUtils.getFromPrefs(YourActivity.this, PREFS_LOGIN_USERNAME_KEY);
    String loggedInUserPassword = PrefUtils.getFromPrefs(YourActivity.this, PREFS_LOGIN_PASSWORD_KEY);
    

    I think its much clearer now...:)

提交回复
热议问题