gi pi
gi pi

Reputation: 103

Is there a new function instead of getSharedPreferences?

I try Shared preferences for the first time and I am facing a problem. When i set my Shared Preferences:

SharedPreferences sp = getSharedPreferences(); 

The getSharedPreferences is red and there is also no suggestion from android studio to change it. Do I have to update my gradle file or is that function replaced by something else?

Upvotes: 0

Views: 419

Answers (4)

Sardaar54
Sardaar54

Reputation: 36

The below code helped me:

SharedPreferences sh = appCompatActivity.getApplicationContext().getSharedPreferences("MySharedPref", Context.MODE_PRIVATE);
    

Upvotes: 0

bhupathi turaga
bhupathi turaga

Reputation: 297

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

Editor editor = pref.edit();

editor.putString("key_name", "string value"); // Storing string

editor.commit();

Get String from your SharedPreferences

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);

String newval = pref.getString("key_name", null);

Upvotes: 2

Programmer007
Programmer007

Reputation: 398

You should use context like below

private val sharedPreferences: SharedPreferences? =
        context.getSharedPreferences("Preference", Context.MODE_PRIVATE)

Upvotes: 1

UrbanR
UrbanR

Reputation: 202

You have to call .getSharedPreferences() on the current context (for example getActivity().getPreferences(Context.MODE_PRIVATE);).

You can see some examples here: https://developer.android.com/training/data-storage/shared-preferences.

Upvotes: 2

Related Questions