我是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中設置的值。
你能幫我理解我做錯了什麼嗎?
非常感謝。
我覺得你與sharedpreferences代碼是正確的。也許與刷新remoteviews有關。你記錄了preferences.getString嗎?它顯示錯誤的價值? – nandeesh 2012-01-12 18:44:42