Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Access SharedPreferences once application is stopped/destroyed

I implementing notifications together with a periodical alarm and on IntentService i need to validate some values on SharedPreferences to decide if I will show a notifications or not.

When the application is on pause i have context, and everything goes ok, the problem comes when i destroy(remove from "recent apps" list) my application. In this case, the alarm is still running (which is ok), but when it tries to load my shared preferences gives me NullPointerException.

IntentService:

public class MyIntentService extends IntentService {

    private final PreferencesManager prefs;

    public SchedulingService() {
        super("MyIntentService");
        prefs = PreferencesManager.getInstance(this); //Error here
    }

    @Override
    protected void onHandleIntent(Intent intent) {
       // Do some checking with prefs variable ...
    }
}

SharedPreferences

public class PreferencesManager {

    public static final String SHARED_PREFERENCES_NAME = "PREFERENCES_PROJECT";
    private static PreferencesManager preferencesManager = null;
    private SharedPreferences sharedPreferences;

    private PreferencesManager(Context context) {
        sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    }

    public static PreferencesManager getInstance(Context context) {
        if (preferencesManager == null) {
            preferencesManager = new PreferencesManager(context);
        }
        return preferencesManager;
    }

    //....
}

How can retrieve the values from my PreferencesManager when the application is not running?

like image 593
Bugdr0id Avatar asked May 24 '26 06:05

Bugdr0id


1 Answers

Move your prefs = PreferencesManager.getInstance(this) line to onHandleIntent(), or into an onCreate() method after the super.onCreate() call.

why dont i have context on constructor?

You do have a Context. It is not fully initialized yet. Never attempt to use a Context before the inherited onCreate() of the relevant component has completed. In this case, the component is a Service, so once super.onCreate() is over, then it is safe to use the Service to retrieve a SharedPreferences object.

like image 124
CommonsWare Avatar answered May 26 '26 19:05

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!