alex czernenk alex czernenk - 4 months ago 30
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
reference


READ PREFS

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





WRITE PREF

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(R.id.white_blur);
green_blur = (ImageButton)view.findViewById(R.id.green_blur);
orange_blur = (ImageButton)view.findViewById(R.id.orange_blur);
pink_blur = (ImageButton)view.findViewById(R.id.pink_blur);
yellow_blur = (ImageButton)view.findViewById(R.id.yellow_blur);
blue_blur = (ImageButton)view.findViewById(R.id.blue_blur);

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

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

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

setOnClickListeners();
return view;
}

Answer

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

Comments