Как я могу сохранить значение на экране настроек? - PullRequest
1 голос
/ 12 января 2012

Я новичок в Android, и я просто пытаюсь навсегда сохранить строку.

Я хочу получить эту строку из PreferenceActivity, а затем обновить текст TextView.

Я читал о доступных опциях постоянного хранения: http://developer.android.com/guide/topics/data/data-storage.html#pref

Я пытался использовать SharedPreferences, но мне очень непонятно, как оно должно работать.

Я создал очень простое тестовое приложение.

MainActivity.java

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

/* method that starts preferences */
public void openPreferences(View v) {
    Intent i = new Intent(this, Preferences.class);
    startActivity(i);
}

@Override
protected void onStart(){
    super.onStart();

    // Get preferences
    SharedPreferences preferences = getPreferences(0);
    String name = preferences.getString("name","Empty string!");

    // Create a RemoteViews layout
    RemoteViews views = new RemoteViews(getPackageName(),R.layout.main);       
    // set new text for labels
    views.setTextViewText(R.string.name, name);
}

@Override
protected void onStop(){
    super.onStop();

    // We need an Editor object to make preference changes.
    // All objects are from android.context.Context
    SharedPreferences preferences = getPreferences(0);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("name", "This is a test");
    // Commit the edits!
    editor.commit();
}
}

Preferences.java

public class Preferences extends PreferenceActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
}

AndroidManifest.xml

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".MainActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Preferences" 
              android:label="@string/preferences_title">
    </activity>

</application>

Текст TextView никогда не изменяется, для него всегда устанавливается значениеЯ установил на strings.xml.

Не могли бы вы помочь мне понять, что я делаю не так?

Большое спасибо.

Ответы [ 3 ]

4 голосов
/ 12 января 2012

Вы очень близки к тому, что я бы порекомендовал:

1) Определите некоторые общие настройки:

    public static final String MY_PREFERENCES = "MyPreferences";
    ...
    public static final SOME_PREFERENCE = "SomePreference";

2) Чтение из общих настроек

    SharedPreferences myPreferences;
    ...
    myPreferences = getSharedPreferences (MY_PREFERENCES, Context.MODE_PRIVATE);

3) Сохранить / обновить общие настройки:

    Editor editor = myPreferences.edit ();
    editor.putString (SOME_PREFERENCE, "abc");
    editor.commit ();
1 голос
/ 12 января 2012

Быстрый пример сохранения / записи имени пользователя, пароля в настройках.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

Editor edit = preferences.edit();        
edit.putString("username", "abcd");        
edit.putString("password", "abcd#");        
edit.commit();

Быстрый пример чтения имени пользователя, пароля из настроек.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);    

String strUsername = preferences.getString("username", null);   
String strPassword = preferences.getString("password", null);   

0 голосов
/ 13 января 2012

Я только что понял, что мой код, связанный с SharedPreferences, верен, но TextView никогда не обновляется, потому что я пытался редактировать непосредственно саму строку, а не TextView!

Просто решил так:

    /* Update text of TextView */
    TextView t = (TextView) this.findViewById(R.id.name);
    // previously was R.string.name - not correct!
    t.setText(name);

Большое спасибо за вашу помощь, ребята:)

...