Search code examples
androidandroid-sharedpreferences

Android One-time Login screen using SharedPreferences


I am Wondering about One-time screens... I know, I should use something like SharedPreferences or stuff like that.

If someone has a simple solution for one-time login screen. And a little example.

My login contains: weight, name , height, age and gender (spinner)


Solution

  • You can take a look at Android User info and Sign in :

    https://developer.android.com/training/sign-in/index.html

    Or you can use login with Facebook API.

    Otherwise, I would use Shared prefs.

    Create a shared prefs file

    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    

    This will create a private file for the current activity. You can use MODE_WORLD_READABLE and MODE_WORLD_WRITABLE if it fits your needs.

    You can also provide a file name as the first parameter if needed :

    SharedPreferences sharedPreferences = getPreferences("com.example.stackoverflow.myfile", Context.MODE_PRIVATE);
    

    Write a shared pref

    SharedPreferences.Editor editor = sharedPreferences.edit();
    
    editor.putString("USERNAME", "test");
    
    editor.commit();
    

    You can put any primitive type : int, string, boolean, etc.

    It is a key/value set. the key string "USERNAME" will then have a value of "test".

    Read shared pref

    String username = sharedPreferences.getString("USERNAME", "NO NAME");
    

    The second parameter is a default value to use if the key "USERNAME" didn't get any value.