Retrieve information from an Android sharedPreference

1

Good evening, I have some information saved in SharedPreferences (email and password) and need to retrieve them in several places for use. I created a fragment for the user to save the screen:

<?xml version="1.0" encoding="utf-8"?>

<EditTextPreference
    android:key="@string/pref_user_email"
    android:title="Email"
    android:inputType="textEmailAddress"/>

<EditTextPreference
    android:key="@string/pref_user_password"
    android:title="Senha"
    android:inputType="textPassword"/>

This is working perfectly, however how can I do for example retrieve email info (pref_user_email)? Thankful.

    
asked by anonymous 29.08.2018 / 04:49

2 answers

0

As you want to use in many places, you can create a static method that returns the string you want.   Create a class and create this static method inside it.

 public class Preferencias_Usuario
{
    public static String getEmail(Context pContext)
    {
        SharedPreferences settings = pContext.getSharedPreferences(pContext.getString(R.string.pref_user_email), Context.MODE_PRIVATE);
        String result = settings.getString(pContext.getString(R.string.pref_user_email), "");
        if (result.length() > 0)
            return result;
        return "";
    }
}

So return the email, you can do to return the other data as well.

To use: Preferencias_Usuario.getEmail(Main_Activity.this)

No Main_Activity.this pass the activity you are using.

    
29.08.2018 / 16:08
0

Try this o:

// ...
private SharedPreferences prefs;
//...
private void emUmMetodoQualquer(){
    //...
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    ppf = prefs.getString("ppftexto", "texto");
    // ppftexto eh a referencia, texto eh um valor default
    showTooltip = prefs.getBoolean("showtooltips", false);
    // no caso pega um valor booleano
    if (prefs.getString("ppftexto", "texto").equals("TextoquequeroA")) {
        // faz algo aqui
    }
}

Hope it helps

    
29.08.2018 / 14:39