Recover information from a sharedPreference Android

Asked

Viewed 277 times

1

Good evening, I have some information saved in Sharedpreferences(email and password) and need to recover them in several places for use. I created a Fragment so the user can 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, but how can I do for example recover the email information (pref_user_email)? Grateful.

2 answers

1


As you want to use it in several places, you can create a static method that returns the string you want. Create a class and create this static method within 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, can do to return the other data too.

To use: Preferencias_Usuario.getEmail(Main_Activity.this)

In the Main_Activity.this pass the Activity you are using.

0

try it 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
    }
}

I hope it helps

Browser other questions tagged

You are not signed in. Login or sign up in order to post.