Liam W
Liam W

Reputation: 1163

NullPointerException in android app on sharedpreferences declaration?

So, making an app. I added loads of new code, and now it FC's on open :(

Here is the logcat:

07-25 16:59:12.490: D/AndroidRuntime(26121): Shutting down VM
07-25 16:59:12.495: W/dalvikvm(26121): threadid=1: thread exiting with uncaught exception (group=0x40a641f8)
07-25 16:59:12.495: E/AndroidRuntime(26121): FATAL EXCEPTION: main
07-25 16:59:12.495: E/AndroidRuntime(26121): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.liamwli.smsbusy/com.liamwli.smsbusy.Sms_busyActivity}: java.lang.NullPointerException
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1993)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.app.ActivityThread.access$600(ActivityThread.java:132)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.os.Looper.loop(Looper.java:137)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.app.ActivityThread.main(ActivityThread.java:4575)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at java.lang.reflect.Method.invokeNative(Native Method)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at java.lang.reflect.Method.invoke(Method.java:511)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at dalvik.system.NativeStart.main(Native Method)
07-25 16:59:12.495: E/AndroidRuntime(26121): Caused by: java.lang.NullPointerException
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:371)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:366)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at com.liamwli.smsbusy.Sms_busyActivity.<init>(Sms_busyActivity.java:23)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at java.lang.Class.newInstanceImpl(Native Method)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at java.lang.Class.newInstance(Class.java:1319)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
07-25 16:59:12.495: E/AndroidRuntime(26121):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1984)
07-25 16:59:12.495: E/AndroidRuntime(26121):    ... 11 more
07-25 16:59:12.940: I/dalvikvm(26121): threadid=3: reacting to signal 3
07-25 16:59:12.950: I/dalvikvm(26121): Wrote stack traces to '/data/anr/traces.txt'
07-25 16:59:13.040: I/dalvikvm(26121): threadid=3: reacting to signal 3
07-25 16:59:13.045: I/dalvikvm(26121): Wrote stack traces to '/data/anr/traces.txt'

Line 23 of Sms_busyActivity.java is:

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

I don't understand what I am getting this error.

The rest of the activity is below (It is quite large):

package com.liamwli.smsbusy;

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.content.IntentFilter;
import android.content.SharedPreferences;

public class Sms_busyActivity extends Activity {
    IntentFilter intentFilter;
    ToggleButton endis;
    EditText message;
    Button smessage;
    SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    SharedPreferences.Editor editor = getPrefs.edit();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Intent i = new Intent("com.liamwli.smsbusy.PREFS");
        // startActivity(i);
        setContentView(R.layout.main);

        endis = (ToggleButton) findViewById(R.id.enableddis);

        smessage = (Button) findViewById(R.id.savemess);

        message = (EditText) findViewById(R.id.message);

        // ---intent to filter for SMS messages received---
        intentFilter = new IntentFilter();
        intentFilter.addAction("SMS_RECEIVED_ACTION");

        endis.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(Sms_busyActivity.this, "App state changed",
                        Toast.LENGTH_LONG).show();
                if (endis.isChecked()){
                    editor.putBoolean("enabled", true);
                    editor.commit();
                }else {
                    editor.putBoolean("enabled", false);
                    editor.commit();
                }

                editor.putString("message", message.getText().toString());
                editor.commit();

            }
        });

        smessage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                editor.putString("message", message.getText().toString());
                editor.commit();

            }
        });

    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
                && keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            Log.d("CDA", "onKeyDown Called");
            onBackPressed();
        }

        return super.onKeyDown(keyCode, event);
    }

    public void onBackPressed() {
        Log.d("CDA", "onBackPressed Called");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super.onCreateOptionsMenu(menu);
    }

}

Please can someone help me?

Upvotes: 0

Views: 2910

Answers (4)

Luke Taylor
Luke Taylor

Reputation: 9599

Don't initialize SharedPreferences.Editor editor; before the Activity has been initialized, so I'd suggest you move the initialization statement getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); into the onCreate() method.

Upvotes: 0

Raghav Sood
Raghav Sood

Reputation: 82543

You need to split that declartion so that you actually access the preferences only in or after onCreate(), as only then will you get a valid context. Try changing the declaration from:

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

to

SharedPreferences getPrefs;

And adding the following to your onCreate()

getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

Upvotes: 1

Joel
Joel

Reputation: 4762

You should not try to initialize your SharedPreferences at your instance variable declaration. You should do that in onCreate or some other method. It is trying to get the preferences for the activity context, which does not yet exist before onCreate is called.

Upvotes: 0

Dheeraj Vepakomma
Dheeraj Vepakomma

Reputation: 28697

Move the following code to within the onCreate() method.

getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

The reason being, in your existing code, you're using the context (getBaseContext()) before it could be fully created by a call to super.onCreate().

Upvotes: 7

Related Questions