簡體   English   中英

SharedPreferences。 Android,Java

[英]SharedPreferences. Android, Java

抱歉,我有一個新問題,但是我認為這是可以的,因為我是Android開發的新手(正在開發中)。 我正在學習如何保存我的首選項。 我有一個簡單的應用程序:

package com.foxysoft.prefssimple;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    final static String LOG_TAG = "myLogs";

    TextView tvInfo;
    SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvInfo = (TextView) findViewById(R.id.tvInfo);

        sp = PreferenceManager.getDefaultSharedPreferences(this);
    }

    @Override
    protected void onResume() {
        Log.d(LOG_TAG, "onResume");
        Boolean notif = sp.getBoolean("notif", false);
        String address = sp.getString("address", "");
        String text = "Notifications are " + ((notif) ? "enabled, address = " + address : "disabled");
        tvInfo.setText(text);
        super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem mi = menu.add(0, 1, 0, "Prefs");
        mi.setIntent(new Intent(this, PrefActivity.class));
        return super.onCreateOptionsMenu(menu);
    }
}

如您所見,我有一個小菜單,我的首選項(PrefActivity.class)有一個活動,我的首選項活動有prefs.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference
        android:key="notif"
        android:summary="Enable notifications"
        android:title="Notifications">
    </CheckBoxPreference>
    <EditTextPreference
        android:key="address"
        android:summary="Address for notifications"
        android:title="Address">
    </EditTextPreference>
</PreferenceScreen>

所以,我的問題是。 我的onResume中有兩行:

Boolean notif = sp.getBoolean("notif", false);
String address = sp.getString("address", "");

如果我理解正確,那么每次調用onResume時,都應該將我的“ notif”復選框設置為false,並將“ address”字符串“”(空)設置為..或?..如果沒有-為什么? 這兩行肯定是在說“請勿假,地址為空”,對嗎?

不,您說的不對-您正在讀取 存儲的偏好設置。

當沒有首選項名為“ notif”時; 然后使用您提供給該方法調用的默認值 和false將返回。 但是,如果存在已保存的首選項“ notif”,則將返回為其保存的

只需閱讀該方法的相應javadoc即可 它說:

defValue布爾值:如果此首選項不存在,則返回的值。

返回首選項值(如果存在)或defValue。

換句話說:如果您之前存儲的是true ,那么將返回該值。

此外,這里的真正答案是:您無需假設 Android API調用的工作方式-所有這些都得到了很好的記錄。 因此,如果有疑問,請轉到Javadoc。 (當然-雖然我們試圖回答問題時要真正准確的-你仍然可以在這里得到一個錯誤的答案, 真正唯一重要的是API文檔說什么!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM