1

Have values in shared perference in activity1

like this

prefs=getSharedPreferences(prefName, MODE_PRIVATE);
        SharedPreferences.Editor edtior=prefs.edit();
        edtior.putString(VALUE_KEY,check.toString());
        edtior.commit();

And i have need to get the value in another activity. i have tried like this

SharedPreferences prefs=getSharedPreferences(prefName, Context.MODE_PRIVATE);
        edittext.setText(prefs.getString(VALUE_KEY,""));

This works fine.

Like this i need to get the same value in DBHelper class. How to get shared perferences value in DBHelper.

I have tried like this in DBHelper

SharedPreferences prefs=getSharedPreferences(prefName, Context.MODE_PRIVATE);
            String key =(prefs.getString(VALUE_KEY,""));

What's wrong with Syntax?

AngocA
  • 7,545
  • 5
  • 38
  • 52

3 Answers3

1

Try this

SharedPreferences prefs= context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
        String key =(prefs.getString(VALUE_KEY,""));

And you must have to pass context to DBHelper.

Chirag Ghori
  • 4,135
  • 2
  • 18
  • 34
0

For accessing getSharedPreferences method in DBHelper class you will need to pass Context using DBHelper class constructor as:

 private context;

 public DBHelper(Context context){
  this.context=context;
 }

Now use context to call getSharedPreferences method as:

SharedPreferences prefs=context.getSharedPreferences(prefName, 
                                               Context.MODE_PRIVATE);
String key =(prefs.getString(VALUE_KEY,""));
ρяσѕρєя K
  • 130,641
  • 51
  • 193
  • 212
0

Try this. It may be help you..

 SharedPreferences  _sPrefs =getSharedPreferences("myPrefs", Context.MODE_PRIVATE); 
        String temp = _sPrefs.getString("VALUE_KEY", "");
Anjali Tripathi
  • 1,477
  • 9
  • 28