0
private static String geturl() {
        Context applicationContext = configActivity.getContextOfApplication();
//        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);

        SharedPreferences prefs =applicationContext.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
        String url = prefs.getString("url", "No name defined");
        return url;
    }

This method is in a non-activity class i tried to have my string from a non-activity class i tried to do like someone say there :Android - How to use SharedPreferences in non-Activity class?

but i have this error :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
Ahmed feki
  • 31
  • 7
  • Pass the context of the activity through a constructor, and then reference that context in your class – lyncx May 24 '21 at 04:20

1 Answers1

0

The problem is in the first line of code, the method getContextOfApplication() is returning a null value:

Context applicationContext =configActivity.getContextOfApplication();

Since the Context may have come to the end of its lifecycle, it is generally recommended to not store Context or Activity objects as static variables as it may cause memory leaks. Instead, you should wrap a Context or Activity in a WeakReference and when needed, check to see if the context is not null after unwrappping.

In the example below, an activity is stored as a WeakReference and unwrapped with get() in the postExecute() method when required. Since the activity may have ended before the AsyncTask ends, this ensures no memory leaks and no NullPointer exceptions.

private class MyAsyncTask extends AsyncTask<String, Void, Void> {

    private WeakReference<Activity> mActivity;

    public MyAsyncTask(Activity activity) {
        mActivity = new WeakReference<Activity>(activity);
    }

    @Override
    protected void onPreExecute() {
        final Activity activity = mActivity.get();
        if (activity != null) {
            ....
        }
    }

    @Override
    protected Void doInBackground(String... params) {
        //Do something
        String param1 = params[0];
        String param2 = params[1];
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        final Activity activity = mActivity.get();
        if (activity != null) {
            activity.updateUI();
        }
    }
} 
alkonz
  • 11
  • 2