java 单击android studio时设置片段崩溃

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42851746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:54:23  来源:igfitidea点击:

Settings fragment crash on click android studio

javaandroid

提问by DEVANDRIN KUNI

I used the template "Settings Activity" in android studio, I created my own settings Fragment, added the code to the Java file.

我在android studio中使用了模板“设置活动”,我创建了自己的设置片段,将代码添加到Java文件中。

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class LocationServicesPreferenceFragment extends PreferenceFragment{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_location_services);
        setHasOptionsMenu(true);
        bindPreferenceSummaryToValue(findPreference("location_services"));
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            startActivity(new Intent(getActivity(), SettingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

And I edited this method

我编辑了这个方法

protected boolean isValidFragment(String fragmentName) {
    return PreferenceFragment.class.getName().equals(fragmentName)
            || GeneralPreferenceFragment.class.getName().equals(fragmentName)
            || DataSyncPreferenceFragment.class.getName().equals(fragmentName)
            || NotificationPreferenceFragment.class.getName().equals(fragmentName)
            || LocationServicesPreferenceFragment.class.getName().equals(fragmentName);
}

This is the result rendered

这是渲染的结果

Settings

设置

but this is what happens when I click my option, Other 3 options work perfectly

但这就是当我单击我的选项时发生的情况,其他 3 个选项完美运行

Crash

碰撞

Any ideas to fix this problem??

任何想法来解决这个问题?

LogCat

日志猫

   03-17 11:36:44.582 4178-4178/com.example.devandrin.myapplication I/art: Not late-enabling -Xcheck:jni (already on)
    03-17 11:36:44.583 4178-4178/com.example.devandrin.myapplication W/art: Unexpected CPU variant for X86 using defaults: x86
    03-17 11:36:44.708 4178-4178/com.example.devandrin.myapplication W/System: ClassLoader referenced unknown path: /data/app/com.example.devandrin.myapplication-1/lib/x86
    03-17 11:36:44.713 4178-4178/com.example.devandrin.myapplication I/InstantRun: Starting Instant Run Server for com.example.devandrin.myapplication
    03-17 11:36:45.392 4178-4178/com.example.devandrin.myapplication W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
    03-17 11:36:45.791 4178-4207/com.example.devandrin.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
    03-17 11:36:45.791 4178-4207/com.example.devandrin.myapplication D/OpenGLRenderer: Swap behavior 1
    03-17 11:36:45.791 4178-4207/com.example.devandrin.myapplication W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
    03-17 11:36:45.791 4178-4207/com.example.devandrin.myapplication D/OpenGLRenderer: Swap behavior 0
    03-17 11:36:45.916 4178-4178/com.example.devandrin.myapplication W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
    03-17 11:37:31.093 4178-4207/com.example.devandrin.myapplication D/OpenGLRenderer: endAllActiveAnimators on 0x9b4fe900 (RippleDrawable) with handle 0xa1f03f20
    03-17 11:37:34.305 4178-4207/com.example.devandrin.myapplication W/OpenGLRenderer: Points are too far apart 4.000001
    03-17 11:37:36.027 4178-4207/com.example.devandrin.myapplication W/OpenGLRenderer: Points are too far apart 4.000001
    03-17 11:37:49.258 4178-4183/com.example.devandrin.myapplication I/art: Do partial code cache collection, code=29KB, data=29KB
    03-17 11:37:49.265 4178-4183/com.example.devandrin.myapplication I/art: After code cache collection, code=22KB, data=26KB
    03-17 11:37:49.265 4178-4183/com.example.devandrin.myapplication I/art: Increasing code cache capacity to 128KB
    03-17 11:37:49.274 4178-4178/com.example.devandrin.myapplication D/AndroidRuntime: Shutting down VM
    03-17 11:37:49.276 4178-4178/com.example.devandrin.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                       Process: com.example.devandrin.myapplication, PID: 4178
                                                                                       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.devandrin.myapplication/com.example.devandrin.myapplication.SettingsActivity}: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
                                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                        Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
                                                                                           at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:225)
                                                                                           at com.example.devandrin.myapplication.SettingsActivity.bindPreferenceSummaryToValue(SettingsActivity.java:122)
                                                                                           at com.example.devandrin.myapplication.SettingsActivity.access
public class SettingsActivity extends AppCompatPreferenceActivity {
    /**
     * A preference value change listener that updates the preference's summary
     * to reflect its new value.
     */
    private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();

            if (preference instanceof ListPreference) {
                // For list preferences, look up the correct display value in
                // the preference's 'entries' list.
                ListPreference listPreference = (ListPreference) preference;
                int index = listPreference.findIndexOfValue(stringValue);

                // Set the summary to reflect the new value.
                preference.setSummary(
                        index >= 0
                                ? listPreference.getEntries()[index]
                                : null);

            } else if (preference instanceof RingtonePreference) {
                // For ringtone preferences, look up the correct display value
                // using RingtoneManager.
                if (TextUtils.isEmpty(stringValue)) {
                    // Empty values correspond to 'silent' (no ringtone).
                    preference.setSummary(R.string.pref_ringtone_silent);

                } else {
                    Ringtone ringtone = RingtoneManager.getRingtone(
                            preference.getContext(), Uri.parse(stringValue));

                    if (ringtone == null) {
                        // Clear the summary if there was a lookup error.
                        preference.setSummary(null);
                    } else {
                        // Set the summary to reflect the new ringtone display
                        // name.
                        String name = ringtone.getTitle(preference.getContext());
                        preference.setSummary(name);
                    }
                }

            } else {
                /*
                For all other preferences, set the summary to the value's
                simple string representation.
                */
                preference.setSummary(stringValue);
            }
            return true;
        }
    };

    /**
     * Helper method to determine if the device has an extra-large screen. For
     * example, 10" tablets are extra-large.
     */
    private static boolean isXLargeTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
    }

    /**
     * Binds a preference's summary to its value. More specifically, when the
     * preference's value is changed, its summary (line of text below the
     * preference title) is updated to reflect the value. The summary is also
     * immediately updated upon calling this method. The exact display format is
     * dependent on the type of preference.
     *
     * @see #sBindPreferenceSummaryToValueListener
     */
    private static void bindPreferenceSummaryToValue(Preference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

        /*
        Trigger the listener immediately with the preference's
        current value.
        */
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActionBar();
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    private void setupActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (!super.onMenuItemSelected(featureId, item)) {
                NavUtils.navigateUpFromSameTask(this);
            }
            return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onIsMultiPane() {
        return isXLargeTablet(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.pref_headers, target);
    }

    /**
     * This method stops fragment injection in malicious applications.
     * Make sure to deny any unknown fragments here.
     */
    protected boolean isValidFragment(String fragmentName) {
        return PreferenceFragment.class.getName().equals(fragmentName)
                || GeneralPreferenceFragment.class.getName().equals(fragmentName)
                || DataSyncPreferenceFragment.class.getName().equals(fragmentName)
                || NotificationPreferenceFragment.class.getName().equals(fragmentName)
                || LocationServicesPreferenceFragment.class.getName().equals(fragmentName);
    }

    /**
     * This fragment shows general preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class GeneralPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_general);
            setHasOptionsMenu(true);

            // Bind the summaries of EditText/List/Dialog/Ringtone preferences
            // to their values. When their values change, their summaries are
            // updated to reflect the new value, per the Android Design
            // guidelines.
            bindPreferenceSummaryToValue(findPreference("example_text"));
            bindPreferenceSummaryToValue(findPreference("example_list"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * This fragment shows notification preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class NotificationPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_notification);
            setHasOptionsMenu(true);

            // Bind the summaries of EditText/List/Dialog/Ringtone preferences
            // to their values. When their values change, their summaries are
            // updated to reflect the new value, per the Android Design
            // guidelines.
            bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class LocationServicesPreferenceFragment extends PreferenceFragment{
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_location_services);
            setHasOptionsMenu(true);
            bindPreferenceSummaryToValue(findPreference("location_services"));
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
    /**
     * This fragment shows data and sync preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class DataSyncPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_data_sync);
            setHasOptionsMenu(true);

            // Bind the summaries of EditText/List/Dialog/Ringtone preferences
            // to their values. When their values change, their summaries are
            // updated to reflect the new value, per the Android Design
            // guidelines.
            bindPreferenceSummaryToValue(findPreference("sync_frequency"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
}
0(SettingsActivity.java:38) at com.example.devandrin.myapplication.SettingsActivity$LocationServicesPreferenceFragment.onCreate(SettingsActivity.java:250) at android.app.Fragment.performCreate(Fragment.java:2336) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:949) at android.app.BackStackRecord.setLastIn(BackStackRecord.java:860) at android.app.BackStackRecord.calculateFragments(BackStackRecord.java:900) at android.app.BackStackRecord.run(BackStackRecord.java:728) at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578) at android.app.FragmentController.execPendingActions(FragmentController.java:371) at android.app.Activity.performStart(Activity.java:6695) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)? at android.app.ActivityThread.-wrap12(ActivityThread.java)? at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)? at android.os.Handler.dispatchMessage(Handler.java:102)? at android.os.Looper.loop(Looper.java:154)? at android.app.ActivityThread.main(ActivityThread.java:6119)? at java.lang.reflect.Method.invoke(Native Method)? at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)? at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)?

Code

代码

private static void bindPreferenceSummaryToValue(Preference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

        /*
        Trigger the listener immediately with the preference's
        current value.
        */
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getBoolean(preference.getKey(), true));
    }

采纳答案by Kiran Benny Joseph

Try to replace bindPreferenceSummaryToValuemethod with this

尝试bindPreferenceSummaryToValue用这个替换方法

##代码##

You are casting the string to boolean. try .getBoolean(preference.getKey(), true);instead of .getString(preference.getKey(), "")

您正在将字符串转换为布尔值。尝试.getBoolean(preference.getKey(), true);代替.getString(preference.getKey(), "")