Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Preferences in Android?

I'm a novice Android developer who are currently trying hard to build a Login Screen.

I need to find the easiest way to store the username and password in 1 class and retrieve it from another class. See Google has provided several ways: http://developer.android.com/guide/topics/data/data-storage.html

which one is the most efficient and easy to code?

thanks!

like image 712
Hendra Anggrian Avatar asked Dec 15 '22 19:12

Hendra Anggrian


1 Answers

For Login screen tasks like storing username and password you can use Shared Preferences. Here I had made custom methods for using shared preferences. Call savePreferences() method and put your Key and Value(as savePreferences() is based on XML), similarly call Load with your Key. And lastly don't forgot to call deletePreferences() on LOGOUT.

/**
 *   Method used to get Shared Preferences */

public SharedPreferences getPreferences() 
{
    return getSharedPreferences(<PREFRENCE_FILE_NAME>, MODE_PRIVATE);
}
/**
 *  Method used to save Preferences */
public void savePreferences(String key, String value) 
{
    SharedPreferences sharedPreferences = getPreferences();
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
}
/**
 *  Method used to load Preferences */
public String loadPreferences(String key) 
{
    try {
        SharedPreferences sharedPreferences = getPreferences();
        String strSavedMemo = sharedPreferences.getString(key, "");
        return strSavedMemo;
    } catch (NullPointerException nullPointerException) 
    {
        Log.e("Error caused at  TelaSketchUtin loadPreferences method",
                ">======>" + nullPointerException);
        return null;
    }
}
/**
 *  Method used to delete Preferences */
public boolean deletePreferences(String key)
{
    SharedPreferences.Editor editor=getPreferences().edit();
    editor.remove(key).commit();
    return false;
}

Hope this should help you. Don't Forget to do +1.

like image 176
Akhilesh Mani Avatar answered Jan 08 '23 00:01

Akhilesh Mani