Any way to save the bundle data - java

I am getting some data using Intent from A activity to B activity. And I show the text in B activity. But When I go to C Activity and I want to come back to B activity, the text that I have show there, vanished. So I need to save the data at B Activity When I come back from C Activity to B Activity.

You can use SharedPreferences in this case. SharedPreferences offers a framework to save persistent data in key-value pairs. It works for any primitive data type which also means that it’s pretty simple to work with.
To get a SharedPreferences object:
SharedPreferences sharedPref =
context.getSharedPreferences("TheFileName",
Context.MODE_PRIVATE);
Write into your SharedPreferences:
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("test", false);
editor.apply();
Read from SharedPreferences:
boolean musicState = sharedPref.getBoolean("test", true);

Related

How can I CHANGE shared preferences values from another activity?

I got a few activities and one called SettingsActivity. I've created shared preferences there (just one Boolean value for now, but it'll be more).
I want to store values in there and access (not only access but actually change) the values of it in all of my other activities. How can I change this Boolean value from other activity?
Thank you so much!!!
When you have created a SharedPreference, its already available in all other activities for being accessed from them.
I hope while you are saving this, you are doing something like the following.
private SharedPreferences prefs;
prefs = getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
prefs.edit().putBoolean("SOME_KEY", booleanValue).apply();
Now when you are getting it from another activity you need to do something like the following.
private SharedPreferences prefs;
prefs = getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
prefs.getBoolean("SOME_KEY", defValue);
SharedPreference stores key-value pair and hence you can find the value against the key wherever you want to get it.
Now you can change it from any activity. Just use the same key for referencing it from other activities.
private SharedPreferences prefs;
prefs = getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
prefs.edit().putBoolean("SOME_KEY", otherBooleanValue).apply();

Deleting all SharedPreferences upon logout

I want my application to delete all preferences when the user logs out and bring up the LoginActivity after exiting the main screen. I've been following the suggestions here. In my way, I get only the default preferences.
The workflow of my app goes this way if it helps:
Login -> Save User Details to Preferences -> Start MainActivity -> Logout -> Clear Preferences -> Start LoginActivity
Is the problem caused by using the default preferences? Or is it because I called finish()? I've tried apply() and commit(). Neither worked. The preferences still exist when I tried accessing them in the LoginActivity. How do I clear my preferences?
private void logout(){
// clear preferences
SharedPreferences sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
sharedPreferences.edit().clear().apply();
Intent i = new Intent(this, LoginActivity.class);
startActivity(i); // call LoginActivity and finish this one.
finish();
}
Problem is that you are using getPreferences() instead of getSharedPreferences() or getDefaultSharedPreferences().
getPreferences() Retrieve a SharedPreferences object for accessing
preferences that are private to this activity. This simply calls the underlying ContextWrapper.getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
Since, getPreferences() uses class name as it's preference file name, thus you are inserting in one Activity pref file, and clearing another one.
See this for more detail: https://developer.android.com/reference/android/app/Activity#getPreferences(int)
Use commit
SharedPreferences sharedPreferences = getSharedPreferences("YourKey", MODE_PRIVATE);
sharedPreferences.edit().clear().commit();
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
I would suggest you to use a library like Easy Prefs to handle Sharedprefrences.
It has a method Prefs.clear() so basically this would clear all the shared prefs.
This would make it pretty easy for you to handle sharedPrefs.
Alternatively you can clear sharedpref by the following function-:
public void clearPrefs(){
SharedPreferences mySPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mySPrefs.edit();
editor.clear();
editor.apply();
}

Android: SharedPreferences loses 2 of its variables after closing app

i save a couple variables via SharedPreferences without a problem. However, 2 of these variables are reset after i restart the app. I think the problem happens while saving, not while loading, because if i change the default value for loading, it doesnt even use that value, it just goes to 0.
I call this method in onPause:
public void saveStats() {
SharedPreferences pref = getSharedPreferences(SHARED_PREFERENCES, this.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putLong(SECONDS_PLAYED_TOTAL_FILE, secondsPlayedTotal);
editor.putFloat(CURRENCY_GAINED_TOTAL_FILE, currencyGainedTotal);
editor.apply();
}
And load onResum:
SharedPreferences pref = getSharedPreferences(SHARED_PREFERENCES, this.MODE_PRIVATE);
SECONDS_PLAYED_TOTAL = pref.getLong(SECONDS_PLAYED_TOTAL_FILE, 0);
CURRENCY_GAINED_TOTAL = pref.getFloat(CURRENCY_GAINED_TOTAL_FILE, 0);
The variables are public and static.
I save and load similar public static variables without a problem, but those 2 are the only ones i save at onPause().
Any idea?
You could try replacingeditor.apply(); with editor.commit()
From the Android documentation:
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.
Link:
https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()

initaialize variable once in android app then use and save that for futher reuse

My question is this--
I have an app that should limit a button click ,say upto 5 clicks ,in whole lifetime of the app.
Preciously at 6th click of a certain button it should not read that OnClick event ,no matter how many times the app is opened or closed.
Guys im an average programmer and im enough aware of both android and java.Any help is appreciated. :)
You can use Shared Preferences to store the value and retrieve it.
// Write Shared Preferences
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putInt("ClickCounter", counter);
sharedPreferencesEditor.apply();
// Read Shared Preferences
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
int clickCounter = sharedPreferences.getInt("ClickCounter", 0);

How do I get the SharedPreferences from a PreferenceActivity in Android?

I am using a PreferenceActivity to show some settings for my application. I am inflating the settings via a xml file so that my onCreate (and complete class methods) looks like this:
public class FooActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.preference);
}
}
The javadoc of PreferenceActivity PreferenceFragment states that
These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this activity.
But how I get the name of the SharedPreference in another Activity? I can only call
getSharedPreferences(name, mode)
in the other activity but I need the name of the SharedPreference which was used by the PreferenceActivity. What is the name or how can i retrieve it?
import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);
Update
According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,
Many applications may provide a way to capture user preferences on the
settings of a specific application or an activity. For supporting
this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as
“Shared Preferences” across various activities in an application (note
currently it cannot be shared across processes). Or it can be
something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.
Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.
(1) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
(2) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is a nested interface in the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also supports methods like remove() and clear() to delete the preference values from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also the same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode) instead, you just have to pass in the right name.
Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity onCreate(), and seeing what preferencesName is.
String preferencesName = this.getPreferenceManager().getSharedPreferencesName();
The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences() and you should be good to go.
Declare these methods first..
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
Then call this when you want to put a pref:
putPref("myKey", "mystring", getApplicationContext());
call this when you want to get a pref:
getPref("myKey", getApplicationContext());
Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo
which simplifies everything even further
Example:
TinyDB tinydb = new TinyDB(context);
tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);
tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true);
tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...
public class global {
public static Activity globalContext = null;
and set it in the main activity create
#Override
public void onCreate(Bundle savedInstanceState) {
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
global.sdcardPath,
""));
super.onCreate(savedInstanceState);
//Start
//Debug.startMethodTracing("appname.Trace1");
global.globalContext = this;
also all preference keys should be language independent, I'm shocked nobody has mentioned that.
getText(R.string.yourPrefKeyName).toString()
now call it very simply like this in one line of code
global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);
if you have a checkbox and you would like to fetch it's value ie true / false in any java file--
Use--
Context mContext;
boolean checkFlag;
checkFlag=PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(KEY,DEFAULT_VALUE);`
Try following source code it worked for me
//Fetching id from shared preferences
SharedPreferences sharedPreferences;
sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");

Categories

Resources