简体   繁体   中英

Attempt to invoke virtual method 'Context.getSharedPreferences()' on a null object reference

I try to access my sharedpreference from a fragment in my app like this:

SharedPreferences sp_app_prefs = getActivity().getSharedPreferences(getActivity().getPackageName(), MODE_PRIVATE);

String path = sp_app_prefs.getString("path", "");

but I am getting a NullPointerException:

Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

I really don't understand why, it doesn't make sense to me. Calling this sharedpreference from an activity works totaly fine. What am I missing?

Here is the full string method:

public String getFilePath(int i) {

        File filePath;


        SharedPreferences sp_app_prefs = getActivity().getSharedPreferences(getActivity().getPackageName(), MODE_PRIVATE);
        String path = sp_app_prefs.getString("path", "");

        filePath = new File(path);


    }


    return String.valueOf(filePath);
}

Hope someone can help me

Although your question is ambiguous. but i guess you are putting code in onCreateView() method body. instead you should put your code in onViewCreated() method body.

use following code in onViewCreated() method...

    SharedPreferences sharedPreferences = getContext().getSharedPreferences("filename", MODE_PRIVATE);
        SharedPreferences.Editor editor=  sharedPreferences.edit();

        editor.putString("key", "value");
        editor.apply();

        String text = sharedPreferences.getString("key", null);

        Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM