0

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;
    }
Vucko
  • 7,371
  • 2
  • 27
  • 45
alex czernenk
  • 193
  • 1
  • 8

2 Answers2

3

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

Community
  • 1
  • 1
Vucko
  • 7,371
  • 2
  • 27
  • 45
0

Just replace these lines:

main main = new main();
Context context = main.getApplicationContext();
sharedPref = context.getSharedPreferences("alexcz", main.MODE_PRIVATE);

with:

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

getActivity().MODE_PRIVATE will show a warning for accessing static member via instance.

Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64