XML defaultValue属性不适用于某些Android活动

时间:2015-12-16 16:58:14

标签: java android xml sharedpreferences

Android首选项及其XML defaultValue属性存在问题。当我在手机上启动相关活动时,应用程序崩溃,因为默认的sharedPreferences字符串(android:defaultValue)未加载。相反,实际加载的是作为sharedPreferences.getString()方法的第二个参数的字符串,这会导致String Tokenizer在代码中进一步抛出异常几行。

有趣的是,这个特定活动与我的其他活动共享相同的偏好加载代码,这些活动正常。

这是我的代码,我将不胜感激。

DoorSettingsActivity.java

package ilj.tel.fer.hr.smarthomemonitor;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;

public class DoorSettingsActivity extends PreferenceActivity {

    public static class DoorFragment extends PreferenceFragment {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings_door);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new DoorFragment()).commit();
    }
}

settings_door.xml

    <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <EditTextPreference
        android:key="DOOR_PERIOD_SELECT"
        android:title="@string/door_settings_period"
        android:defaultValue="@string/door_period_default_value"/>

</PreferenceScreen>

DoorActivity.java(相关部分)

public class DoorActivity extends AppCompatActivity {

    JSONArray resultJsonArray = new JSONArray();
    ArrayList<String> timestampsList = new ArrayList<>();

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

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        TextView doorTextView = (TextView) findViewById(R.id.door_main_textview);

        String jsonString = "", dataAddress;

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String doorViewPeriodPrefs = sharedPreferences.getString("DOOR_PERIOD_SELECT", "none");
        Log.v("DoorViewPrefs:", doorViewPeriodPrefs);

        // Splits the input time period string (delimited by ;) into "from" and "to" timestamps
        StringTokenizer tokens = new StringTokenizer(doorViewPeriodPrefs, ";");
        String doorViewFrom = tokens.nextToken();
        String doorViewTo = tokens.nextToken();

最后一行代码是应用程序崩溃的原因,因为&#34; none&#34;作为首选项而不是DOOR_PERIOD_SELECT加载。

0 个答案:

没有答案