Search code examples
androidandroid-preferences

PreferenceFragment: NullPointerException


I made a PreferenceActivity to control the settings of my app. Everytime I click on a preference the app crashes and creates a NullPointerException error.

Here's the PreferenceFragment:

public class SettingsFragment extends PreferenceFragment {

EditText enterPassword, newPassword;
public final String filename = "PasswordFile";
String myPassword;
static SharedPreferences myFolder;
public static String dataReturned = "";
Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.preferences_new);

Preference password_pref = (Preference) findPreference("password");
password_pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

    public boolean onPreferenceClick(Preference preference) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View text = inflater.inflate(R.layout.changepassword, null);
        final EditText currentPassword = (EditText)text.findViewById(R.id.currentPassword);
        final EditText newPassword = (EditText)text.findViewById(R.id.newPassword);

        final AlertDialog.Builder alert = new AlertDialog.Builder(context);
        alert.setTitle("Change Your Password");
        alert.setView(text);
        alert.setPositiveButton("Change", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                    String stringData = currentPassword.getText().toString().trim();
                    String stringNew = newPassword.getText().toString().trim();
                    dataReturned = myFolder.getString("passwordKey", "");
                    if(dataReturned.equals(stringData)) {                       
                        String newData = newPassword.getText().toString().trim();
                        SharedPreferences.Editor editor = myFolder.edit();
                        editor.putString("passwordKey", newData);
                        editor.commit();
                        dataReturned  = myFolder.getString("passwordKey", "couldn't load data");
                        Toast.makeText(context, "Password changed", Toast.LENGTH_SHORT).show();
                        currentPassword.setText("");
                        newPassword.setText("");
                    }

                    else {
                        Toast.makeText(context, "Incorrect Password", Toast.LENGTH_LONG).show();
                        currentPassword.setText("");
                        newPassword.setText("");
                    }
                }
            });
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.cancel();
            }
            });
        alert.show();
        ;

        return true;
    }

});

Preference notification_pref = (Preference) findPreference("notification");
notification_pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

    public boolean onPreferenceClick(Preference preference) {
        // TODO Auto-generated method stub
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.device_access_secure)
        .setOngoing(true)
        .setContentTitle("Obstruct")
        .setContentText("Start Stealth Mode");

        Intent resultIntent = new Intent();

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
        return true;
    }

});
}
}

Here's the logcat:

11-23 15:23:36.191: E/AndroidRuntime(17168): FATAL EXCEPTION: main
11-23 15:23:36.191: E/AndroidRuntime(17168): java.lang.NullPointerException
11-23 15:23:36.191: E/AndroidRuntime(17168):    at com.mshaw.avanos8.adfree.SettingsFragment$1.onPreferenceClick(SettingsFragment.java:42)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at android.preference.Preference.performClick(Preference.java:941)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:202)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at android.widget.AdapterView.performItemClick(AdapterView.java:292)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at android.widget.AbsListView.performItemClick(AbsListView.java:1071)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2527)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at  android.widget.AbsListView$1.run(AbsListView.java:3181)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at android.os.Handler.handleCallback(Handler.java:605)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at android.os.Looper.loop(Looper.java:154)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at android.app.ActivityThread.main(ActivityThread.java:4894)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at java.lang.reflect.Method.invokeNative(Native Method)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at java.lang.reflect.Method.invoke(Method.java:511)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-23 15:23:36.191: E/AndroidRuntime(17168):    at dalvik.system.NativeStart.main(Native Method)

I've tried everything to solve this problem. I suspect the context is to blame but I'm not sure for certain.


Solution

  • Looks like your variable context is null, try getActivity() instead of context or by passing the context of the activity that's opening preferences in the preferencefragment's constructor and assign it to your variable.