0

I am developing an application for android and I am new to it, For getting the value from SharedPreferences, I copied and pasted this piece of code below :

SharedPreferences prefs =  PreferenceManager.getDefaultSharedPreferences(getActivity());
                String myValue = prefs.getString(getString(R.string.my_key),
                        getString(R.string.my_default_key));

Obviously this is done inside an Activity, but for storing the key value into SharedPreferences I have some issues it should be done inside a Class which is not an Activity therefore the above code is not working.

Question: I need to know if there is any way that I can use to store and the key value pair inside a class, so that I could retrieve the key value in anActivity with the code above or do I have to modify my code and changed it something like the answered question in this link?

How to use SharedPreferences in Android to store, fetch and edit values

Community
  • 1
  • 1
Siavosh
  • 2,314
  • 4
  • 26
  • 50

3 Answers3

2

Of course! You can use the SharedPreferences inside of your own classes, just pass the context to the class constructor (or however you want to do it) and you should be able to use it normally!

public YourClass(Context c) {
    this.ctx = c;
}

You pass it then when creating the instance of the class:

YourClass cls = new YourClass(getApplicationContext());

Then you can use SharedPreferences inside of your class!

Vedran Kopanja
  • 1,259
  • 12
  • 23
0

Yes, you can. In your class, pass in an (application) Context, then:

SharedPreferences prefs =  PreferenceManager.getDefaultSharedPreferences(context);
xizzhu
  • 895
  • 6
  • 9
0

You can write some public static methods in your Application class, and you can set or get some values in your Activity.

Ellie Zou
  • 2,021
  • 2
  • 16
  • 21