简体   繁体   中英

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;
    }

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

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 .

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