how can I retrieve values from an EditTextPreference?

2

I'm working with Preferences in android and I have a problem, I have a fragment that is a PreferenceFragment, in that fragment I have several options one of them when I click it opens a dialogue box with a field to place text inside as shown in the following image:

Clicking on the option to change user shows the following:

I want to know how I can recover the text that you enter in that EditTextPreference to later save it as a new login name: the code is as follows:

This is the fragment layout:

<PreferenceCategory>

    <EditTextPreference
        android:key="opcion1"
        android:summary="Da clic aqui para cambiar el nombre de usuario que fue registrado."
        android:title="Cambiar usuario" />

</PreferenceCategory>

<PreferenceCategory>

    <EditTextPreference
        android:key="opcion2"
        android:summary="Da clic aqui para cambiar el nombre de usuario que fue registrado."
        android:title="Cambiar contraseña" />

</PreferenceCategory>

<PreferenceCategory>

    <SwitchPreference
        android:key="opcion3"
        android:summary="Deseas rescibir notificaciones?"
        android:title="Notificaciones" />

</PreferenceCategory>

and this is the code of the fragment :

package com.example.enriq.persistencia_en_android_enrique_espinosa;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.widget.TextView;
import android.widget.Toast;

public class ConfiguracionesFragment extends PreferenceFragment {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.configuraciones);

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    String nomreusuario = preferences.getString("opcion1", "");

    if(nomreusuario != null){
        Toast.makeText(getActivity(),"El nuevo nombre de usuario es: "+nomreusuario, Toast.LENGTH_SHORT).show();
    }

}

}
    
asked by Kike hatake 22.01.2018 в 17:38
source

1 answer

2

To obtain the preference values, if you are using a PreferenceFragment you can do it this way by obtaining the preference file:

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);

and then the value by means of the defined key, as an example obtaining the value of EditTextPreference with android:key="opcion1"

String valor = pref.getString("opcion1", "");

For a SwitchPreference it's a bit different since you actually get a value boolean , an example using android:key="opcion3" :

boolean valorSwitch = pref.getBoolean("opcion3",true);
    
answered by 22.01.2018 / 17:58
source