alex czernenk alex czernenk - 1 year ago 97
Android Question

Using shared preferences between fragment and activity

Im trying to use shared prefernces between my first activity and a fragment stationed on my second activity. The code shows what I have done so far but I am having problems getting the context. I also think what I am doing wont work so just want some quick help. Thanks

Attempt to invoke virtual method 'android.content.Context
android.content.Context.getApplicationContext()' on a null object


sharedPreferences = getSharedPreferences("alexcz", MODE_PRIVATE);
String drawableString = sharedPreferences.getString("PARTICLE_TYPE", "null")


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_particle_type, container, false);

white_blur = (ImageButton)view.findViewById(;
green_blur = (ImageButton)view.findViewById(;
orange_blur = (ImageButton)view.findViewById(;
pink_blur = (ImageButton)view.findViewById(;
yellow_blur = (ImageButton)view.findViewById(;
blue_blur = (ImageButton)view.findViewById(;

main main = new main();
Context context = main.getApplicationContext();

sharedPref = context.getSharedPreferences("alexcz", main.MODE_PRIVATE);
editor = sharedPref.edit();

editor.putString("PARTICLE_TYPE", "white_blur");

return view;

Answer Source

Never do this : main main = new main();. Instead do:

Context context = getActivity().getApplicationContext();

If you wish to access applicationContext inside of the fragment. When you initialize Android activities with a constructor, everything gets messed up, just don't do it. Refer to this question

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download