如何永久存储首选项屏幕中的值?

发布于 2024-12-26 16:22:14 字数 2719 浏览 1 评论 0原文

我是 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 上设置的值。

你能帮助我理解我做错了什么吗?

非常感谢。

I am a newbie in Android and I'm just trying to permanently store a string.

I want to get this string from a PreferenceActivity and then update the text of a TextView.

I was reading about the available options for persistent storage: http://developer.android.com/guide/topics/data/data-storage.html#pref

I've tried to use SharedPreferences but it's very unclear for me on how it should work.

I have created a very simple test app.

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>

The text of the TextView never changes, it is always set to the value I set on strings.xml.

Can you please help me to understand what am I doing wrong?

Thank you very much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

计㈡愣 2025-01-02 16:22:14

您非常接近我的建议:

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 ();

You're extremely close to what I'd recommend:

1) Define some shared preferences:

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

2) Read from shared preferences

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

3) Save/update a shared preferences:

    Editor editor = myPreferences.edit ();
    editor.putString (SOME_PREFERENCE, "abc");
    editor.commit ();
暮倦 2025-01-02 16:22:14

将用户名、密码保存/写入首选项的快速示例。

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);   


Quick example of saving/writing username, password into preferences.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

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

Quick example of reading username, password from preferences.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);    

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

你与昨日 2025-01-02 16:22:14

我刚刚意识到与 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);

非常感谢你们的帮助:)

I just realized my code related to SharedPreferences is correct, but the TextView never updates because I tried to edit directly the string itself, not the TextView!

Just resolved this way:

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

Many thanks for your help guys :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文