how to use SharedPreferences outside of oncreate? - java

How to use SharedPreferences in a class without oncreate ?
I get null pointer when accessing it.
public class Ftr extends Activity
{
SharedPreferences preferences;
Context ab=this;
public void ft()
{
preferences = PreferenceManager.getDefaultSharedPreferences(ab);
String result = preferences.getString("F","");
}
}
I'm calling Function ft() from another activity Ftr is just a class not an activity.
How can I use SharedPreferences in this condition?

You can take in Common method or Utils So use in All Method.
public static void SaveInPreference(Context mContext, String key, String objString) {
SharedPreferences.Editor editor = mContext.getSharedPreferences(mContext.getString(R.string.app_name),
Context.MODE_PRIVATE).edit();
editor.putString(key, objString);
editor.commit();
}
public static String getPrefString(Context mContext, final String key, final String defaultStr) {
SharedPreferences pref = mContext.getSharedPreferences(mContext.getString(R.string.app_name),
Context.MODE_PRIVATE);
return pref.getString(key, defaultStr);
}

Related

How to use sharedPrefrence putString?

I want to use sharedprefrence string form another activity but the value is not being passed it always passes the default value?
Creation of variable toast Shows inp value but value is not being passed
name_next = (Button) findViewById(R.id.name_next);
sp= getSharedPreferences("name_pref",Context.MODE_PRIVATE);
name_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inp = nameInput.getText().toString();
SharedPreferences.Editor editor= sp.edit();
editor.putString(inp,nameInput);
editor.commit();
Toast.makeText(com.calmo.name.this,"welcome "+inp,Toast.LENGTH_LONG).show();
Intent intent = new Intent(name.this,MainActivity.class);
startActivity(intent);
}
});```
**Calling **
**The Value is always returned as error that is default**
``` SharedPreferences sp=getApplicationContext().getSharedPreferences("name_pref",Context.MODE_PRIVATE);
String name_in =sp.getString("inp","Error");
name.setText(name_in);
public class AppSharedPreferences {
public static final String TAG = "AppSharedPreferences";
private static SharedPreferences sharedPref;
private String demo_string = "demo string's key"
public AppSharedPreferences() {
}
public static void init(Context context)
{
if(sharedPref == null)
sharedPref = context.getSharedPreferences(
context.getPackageName(), Activity.MODE_PRIVATE);
}
public static void setDemoString(String demoString) {
Editor prefs = sharedPref.edit();
prefs.putString(demo_string, demoString);
prefs.apply();
}
public static String getDemoString() {
return sharedPref.getString(demo_string, "");
}}
Put this wherever u want to use shared prefs:
AppSharedPreferences.init(this);
You can exchange this for activity or context, depending on where you use the code.
To set value in preference, use this code:
AppSharedPreferences.setDemoString("Some Text");
To get the value from preference:
String text = AppSharedPreferences.getDemoString();
Remove
inp = nameInput.getText().toString();
under onclick
and change
editor.putString(inp,nameInput);
to
editor.putString("inp",nameInput.getText().toString());

how to save changes using SharedPreferences?

I'm working on an application and I have to save changes made by the user ... the user going to click on an image, it's going to change the color. And I want to save that change.
I'm not sure how to do that actually. Here is where I want to make the change.
All I know is I need to use SharedPreferences .
private ImageView bookmark;
bookmark = (ImageView) findViewById(R.id.imageView_bookmark_readIt);
bookmark.setOnClickListener(new View.OnClickListener(){
private boolean bookmarking = true;
public void onClick(View v){
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
});
So does anybody have an idea of how to save changes made to the above code?
Note : I'm not using database
In shared preferences data is stored in the “key-value” format. As far as I understand, you need to save two fields and it will be something like this:
“booking: true”
“bookmarkImageResource: 15670341274”
Here is a convenient way to do it:
Step one – create a new class SharedPrefs:
public class SharedPrefs {
private static final String SHARED_PREFERENCES_NAME = "user_prefs";
private static final String BOOKING_INFO = "booking";
private static final String BOOKMARK_IMAGE_RESOURCE_INFO = "bookmarkImageResource";
private final SharedPreferences prefs;
public SharedPrefs(Context context) {
prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public boolean saveBookingInfo(String bookingInfo, String bookmarkImageResource) {
return prefs.edit()
.putString(BOOKING_INFO, bookingInfo)
.putString(BOOKMARK_IMAGE_RESOURCE_INFO, bookmarkImageResource)
.commit();
}
public Pair<String, String> getBookingInfo() {
return new Pair<String, String>(
prefs.getString(BOOKING_INFO, ""),
prefs.getString(BOOKMARK_IMAGE_RESOURCE_INFO, ""));
}
public void clearAll() {
prefs.edit().clear().apply();
}
}
Step two - use your class wherever you need to save, get or clear data!
In you case:
SharedPrefs prefs = new SharedPrefs(this); // or getActivity() instead of this if we are in a fragment
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
}
prefs.saveBookingInfo(String.valueOf(bookmarking), String.valueOf(bookmark));
Hope this will help you =)
Have a good day & happy coding!
/**
* Get a shared preferences file named Const.SHARED_PREFERENCES_FILE_NAME, keys added to it must be unique
*
* #param ctx
* #return the shared preferences
*/
public static SharedPreferences getSharedPreferences(Context ctx) {
return ctx.getSharedPreferences(Const.SHARED_PREFERENCES_FILE_NAME, Context.MODE_PRIVATE);
}
public static void cacheBoolean(Context ctx, String k, Boolean v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putBoolean(k, v).apply();
}
public static Boolean getCachedBoolean(Context ctx, String k, Boolean defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getBoolean(k, defaultValue);
}
public static void cacheString(Context ctx, String k, String v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putString(k, v).apply();
}
public static String getCachedString(Context ctx, String k, String defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getString(k, defaultValue);
}
public static void cacheInt(Context ctx, String k, int v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putInt(k, v).apply();
}
public static int getCachedInt(Context ctx, String k, int defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getInt(k, defaultValue);
}
public static void clearCachedKey(Context context, String key) {
getSharedPreferences(context).edit().remove(key).apply();
}
Using SharedPreferences is very easy. You need to define a key which you will use to retrieve the data later. You can store Strings, ints, floats, booleans... You need to provide the context.
Context context = getApplicationContext();
To write data, use this code.
SharedPreferences mPrefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("color", "blue");
editor.apply();
To retrieve data, use this
SharedPreferences mPrefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
String color = mPrefs.getString("color", "defaultValue");
You can easily change the type from String to other types that might best suit your needs.
Hope it helps.
Hope its help you
SharedPreferences sharedPrefs = getSharedPreferences("SharedPreferences_Name", Context.MODE_PRIVATE);
private ImageView bookmark;
bookmark = (ImageView) findViewById(R.id.imageView_bookmark_readIt);
private boolean bookmarking = sharedPrefs.getBoolean("bookmarking",true);//To get value that saved in SharedPreferences
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
}
else{
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
bookmark.setOnClickListener(new View.OnClickListener(){
// private boolean bookmarking = true;
public void onClick(View v){
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
SharedPreferences.Editor editor = getSharedPreferences("SharedPreferences_Name", 0).edit();
editor.putBoolean("bookmarking", bookmarking);
editor.apply();
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getSharedPreferences("SharedPreferences_Name", 0).edit();
editor.putBoolean("bookmarking", bookmarking);
editor.apply();
}
});

sharedpreferences why doesn't return any values

I using sharedPrefrence in my app but it's not return any value
this is code :
public class SharedPrefManager {
public final String MY_PREFS_NAME = "name";
private Context context;
SharedPreferences sp;
public SharedPrefManager(Context context){
this.context = context;
sp = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Log.d(TAG, "database is created");
}
public void saveInfoUser(String username ,int numRow){
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString("username", username);
editor.putInt("numberRow",numRow);
editor.commit();
}
public String getUsename(){
String username = sp.getString("username","");
return username;
}
public void logout(){
sp.edit().clear().commit();
}
}
but when call method getUsename() return "" and not return values
this is place of called method :
enter image description here
Make sure you are using the same shared preference for saving as you are retrieving.
Your read is using private shared pref by key MY_PREFS_NAME
but your write is using default shared pref with no key.
The critical part of the code is this:
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
That line of code should be this:
SharedPreferences.Editor editor = sp.edit();
Once you obtain the SharedPreferences object in your class constructor you should use it to create the editor.
public class SharedPrefManager {
public final String MY_PREFS_NAME = "name";
private final String MY_PREFS_USERNAME = "username";
private final String MY_PREFS_NUMBER_ROW = "numberRow";
SharedPreferences sp;
public SharedPrefManager(Context context){
sp = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Log.d(TAG, "database is created");
}
public void saveInfoUser(String username ,int numRow){
SharedPreferences.Editor editor = sp.edit();
editor.putString(MY_PREFS_USERNAME , username);
editor.putInt(MY_PREFS_NUMBER_ROW ,numRow);
editor.commit();
}
public String getUsename(){
String username = sp.getString(MY_PREFS_USERNAME ,"");
return username;
}
public void logout(){
sp.edit().clear().commit();
}
}

How to save textfield response without clearing

I am trying to create a simple to do list style app. I have successfully saved the string using SharedPreferences, as I am able to refer to it in the Logs, but I would like to make it so that the string stays attached to the textfield instead of being cleared every time app is reopened (until changed or deleted by the user). Any other suggestions would be appreciated.
(MainActivity)
public void go(View view) {
Intent intent1 = new Intent(SecondActivity.this, myPreferences.class);
String passGoal1 = goal1.getText().toString();
intent1.putExtra("goal1", passGoal1);
startActivity(intent1);
}
Also implemented myPreferences class as referenced in the first answer.
public class myPreferences {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private Context context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "MyPreferencesName";
public final static String KEY_NAME = "key_value";
public myPreferences(Context context) {
this.context = context;
pref = context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
editor = pref.edit();
}
public void setFunction(String data) {
editor.putString(KEY_NAME, data);
}
}
In your shared preferences make a get function that fetch the stored data and view it every time in textfield
public class MyPreferences {
private SharedPreferences pref;
// Editor for Shared preferences
private SharedPreferences.Editor editor;
// Context
private Context context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyPreferencesName";
public final static String KEY_NAME = "key_value";
public MyPreferences(Context context) {
this.context = context;
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFunction(String data) {
editor.putString(KEY_NAME, data);
editor.commit();
}
public String getFunction() {
return pref.getString(KEY_NAME, "");
}
}
And in your activity initialize SharedPreferences and do the following:
private MyPreferences myPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPreferences = new MyPreferences(this);
//To set EditText data from SavedPreferences
textField.setText(myPreferences.getFunction());
}
//To save the latest data from EditText.
#Override
protected void onStop() {
Log.d("LifeCycle", "onStop: ");
super.onStop();
myPreferences.setFunction(editText.getText().toString());
}

Using SharedPreferences and Editor as members

I have a Settings class, that uses SharedPreferences to load and save settings. To make it readable, I made the Editor and SharedPreferences objects members of that class and call on them set read and write settings. However, this doesn't seem to work well.
This is the Settings class:
public class Settings {
protected Context ctx;
protected SharedPreferences sp;
protected Editor edit;
public Settings(Context c) {
ctx = c;
sp = ctx.getSharedPreferences("app_settings", Context.MODE_PRIVATE);
edit = sp.edit();
}
public void setString(String name, String value) {
edit.clear();
edit.putString(name, value);
edit.commit();
}
public String getString(String name, String def) {
return sp.getString(name, def);
}
}
And I call like this (from my from Application extended MyApplication's onCreate:
Settings s = new Settings(getApplicationContext());
s.setString("foo", "bar");
When I reread that value, I always get the default value:
String value = s.getString("foo", "default");
It is because of edit.clear()
change this method
public void setString(String name, String value) {
edit.clear();
edit.putString(name, value);
edit.commit();
}
as follows
public void setString(String name, String value) {
edit.putString(name, value);
edit.commit();
}
Try this code.
private final String LANGUAGE = "Language";//Key to identify field in sharedPrefrence file.
private final String PREFS_NAME = "SharedPreferenceFile";//Shared Preference file name.
public String getLanguageFromSharedPreference() {
sharedPreferences = this.getSharedPreferences(PREFS_NAME, 0);
return sharedPreferences.getString(LANGUAGE, "en");
}
public void setLanguageToSharedPreference(String newlang) {
sharedPreferences = this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LANGUAGE, newlang);
editor.commit();
}

Categories