PreferenceActivity # findPreference () returns null

1

Could anyone help with the error below?

I'm a beginner with android and I could not identify where I went wrong.

Thank you!

Log Error

01-22 11:45:32.722 13037-13037/com.example.android.sunshine.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.sunshine.app, PID: 13037
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.sunshine.app/com.example.android.sunshine.app.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.preference.Preference.setOnPreferenceChangeListener(android.preference.Preference$OnPreferenceChangeListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2491)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2564)
at android.app.ActivityThread.access$800(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1441)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5576)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.preference.Preference.setOnPreferenceChangeListener(android.preference.Preference$OnPreferenceChangeListener)' on a null object reference
at com.example.android.sunshine.app.SettingsActivity.bindPreferenceSummaryToValue(SettingsActivity.java:40)
at com.example.android.sunshine.app.SettingsActivity.onCreate(SettingsActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6041)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2564) 
at android.app.ActivityThread.access$800(ActivityThread.java:170) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1441) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5576) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751) 

strings.xml

<string name="app_name">Sunshine</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="action_refresh" translatable="false">Refresh</string>
<string name="title_activity_detail">Details</string>
<string name="title_activity_settings">Settings</string>


<string name="pref_location_label" >Location</string>

<string name="pref_location_key" translatable="false">location</string>

<string name="pref_location_default" translatable="false">94043</string>

SettingsActivity.java

import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class SettingsActivity extends PreferenceActivity
        implements Preference.OnPreferenceChangeListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.pref_general);

        bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
    }

    private void bindPreferenceSummaryToValue(Preference preference) {

        preference.setOnPreferenceChangeListener(this);

        onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

    @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 (since they have separate labels/values).
            ListPreference listPreference = (ListPreference) preference;
            int prefIndex = listPreference.findIndexOfValue(stringValue);
            if (prefIndex >= 0) {
                preference.setSummary(listPreference.getEntries()[prefIndex]);
            }
        } else {
            // For other preferences, set the summary to the value's simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
    }

}

pref_general.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    >

    <EditTextPreference
        android:key="pref_location_key"
        android:title="@string/pref_location_label"
        android:defaultValue="@string/pref_location_default"
        android:inputType="text"
        android:singleLine="true" />
</PreferenceScreen>
    
asked by anonymous 22.01.2017 / 11:53

1 answer

0

This line of logcat

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 
'void android.preference.Preference.setOnPreferenceChangeListener(android.preference.Preference$OnPreferenceChangeListener)' 
on a null object reference

indicates that the error is NullPointerException , it happens on the line

preference.setOnPreferenceChangeListener(this);

and that the reason is to be calling the setOnPreferenceChangeListener() method on a null object ( preference ).

The object preference is returned by calling the findPreference() method on the line     bindPreferenceSummaryToValue (findPreference (getString (R.string.pref_location_key)));

Make sure R.string.pref_location_key matches key of Preference or replace getString(R.string.pref_location_key) with "pref_location_key" :

bindPreferenceSummaryToValue(findPreference("pref_location_key"));

Using resources of type String allows you to centralize the declaration of constants of type string, allowing, when necessary, to change them in a single local You only have to be careful to use the feature in all places where string is used.

So, in xml that declares Preference, you should use it in the android:key attribute:

<EditTextPreference
    android:key="@string/pref_location_key"
    android:title="@string/pref_location_label"
    android:defaultValue="@string/pref_location_default"
    android:inputType="text"
    android:singleLine="true" />
    
22.01.2017 / 12:14