Domanda

I've created an EditTextPreference and now I want to get the value from any other activity. I've been trying a lot of things but I cannot get it working. Where is this value stored? How can I retrieve it?

EDIT: I want to get the value from a different activity, not the Preferences activity.

settings.xml

<EditTextPreference
    android:title="EditText1"
    android:key="edit1"
    android:defaultValue="0"
    android:dialogIcon="@drawable/fleetespiar"
    android:inputType="number" />

Settings.java (How to do this in a different activity)

Preference edit1= findPreference("edit1");
EditTextPreference editt1 = (EditTextPreference) edit1;

System.out.println(String.valueOf(editt.getText().toString()));
È stato utile?

Soluzione

Your value will be stored in a shared preference file.

Check my little example below:

  1. Create a xml directory inside the res directory (resources) of your android project.

  2. Inside your new xml directory you must create a preference.xml file wich will contains your EditTextPreference.

        <?xml version="1.0" encoding="utf-8"?>
        <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
            <EditTextPreference
                android:dialogTitle="My preference"
                android:key="pref"
                android:summary="Enter Your Preference"
                android:title="Edit Text Preference" />
        </PreferenceScreen>
    
  3. Now create your Preferences class which extends PreferenceActivity.

        import android.content.SharedPreferences;
        import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
        import android.os.Bundle;
        import android.preference.EditTextPreference;
        import android.preference.Preference;
        import android.preference.PreferenceActivity;
    
            public class Preferences extends PreferenceActivity {
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                 super.onCreate(savedInstanceState);
                 addPreferencesFromResource(R.xml.preferences);
            }
        }
    
  4. Use a SharedPreference object to insert and get your String value.

Altri suggerimenti

First you need to create an instance of SharedPreferences, then you can call getString() on it, specifying the key for the value.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top