I understand what SharedPreferences do but still struggling to get my head round what this piece of code is trying to do.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
if (sharedPref.getBoolean("login", false)) {
edtUser.setText(sharedPref.getString("user", ""));
edtPass.setText(sharedPref.getString("pass", ""));
new SigninTask().execute("user=" + edtUser.getText(), "pass=" + edtPass.getText());
}
I understand that the first line is accessing the default SharedPreferences file. However I am still confused, what does this set code do exactly?. What information is it trying to get?. What does the last line do? (new SigninTask())..
sharedPref.getString("user", "") tries to get a preference with the key user from the SharedPreferences. If it's not found, it returns an empty String. This value is loaded to a Text control (I assume, since you didn't include the definition of edtUser).
The same is done with the value of pass, which probably represents a password.
Basically, this app probably stores in SharedPreferences the user and password that were entered by the user of the app in a previous launch of the app, so that the user doesn't have to enter them again every time the app is launched.
There should be additional code that would store the entered user and pass in the SharedPreferences, and store the login preference with the value true.
Related
I found a problem with Shared Preferences which happens only for some devices and only with Android 9 (Pie) o above.
To encrypt my database I create a key and store it to my sharedPreferences.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String content = sharedPreferences.getString(-nameOfTheKey-, "");
if (content == null || content.isEmpty()){
// Create and store the new key
content = restoreApplicationKey(context);
}
As you can see, first I check for the availability then I create if not exist or empty. This key isn't created in any other place. That is the only point.
When I try to first install the app on my device, the condition return false because the key-value is already present in my SharedPreferences. This is impossibile!
I found online that the solution is to set allowBackup="false" into the Manifest and reinstall the app but I don't understand this behavior. How is it possible that the kay-value is pre setted?
Also, before setting allowBackup to false, I noticed that if forcing the initialization and uninstall the app, after the reinstall the key is still present but the value is changed. Every time with the same string but different from the saved one. All others key are fine, except this one.
As I said, the above code is the only entry point and it's called only at the app launch. Also the restoreApplicationKey(context) is called only at this point.
Is there a way for me to set a integer variable to 0, but it will only do this on the first time the app is opened by a device?
Create a shared preference. Query the shared preference int value (for example) at the start of the application. If it's a first time boot up we get the default 0 value where we change the shared preference value which helps us keep track that it isn't a first time start in the future start of the application.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
In your splash (or wherever necessary) check for a specific key of the shared preference like this :
//Check for the key "tracker", if it does not exist consider the default value as 0
int appStartTracker = pref.getInt("tracker", 0);
if(appStartTracker == 0){
// It means you started the app for the first time. Do what you have to
// and set the preference to 1 or increment the appStartTracker to keep
//track of how many times the app has been started.
appStartTracker++;
editor.putInt("tracker", appStartTracker);
editor.commit();
}else{
// Not a first time start.
//Do the following if you need to keep track of total app starts else ignore
appStartTracker++;
editor.putInt("tracker", appStartTracker);
editor.commit();
Log.d("TAG", "App has been started for the " + appStartTracker +"time");
}
P.S The shared preference is cleared when the user clears data.
I know there must be douzens of answers to this question out there, but either i cant't find them or I don't understand them.
The Question:
How do I get my app to exactly start as it was left?
F.e. dynamicly added checkBoxes shouldn't dissapear!
There is no "out of the box" way of doing it. You could save the current state of your Activity in some way (More on persistence)
Then you need to be able to rebuild the desired state of the persisted state in your Activity lifecycle
You could save and load with the shared preferences for example:
public void saveState(YourState state) {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
sharedPreferences.edit()
.putString("CustomAtt", state.getCustomAtt())
}
public YourState loadState() {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
String customAtt = sharedPreferences.getString("CustomAtt", "DefaultValue")
return new YoutState(customAtt)
}
And use it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
YourState state = loadState();
// Rebuild your activity based on state
someView.setText(state.getCustomAtt())
}
You can store such values in SharedPreferences.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
It is using key-value approach for saving. So you can save some values and read it from SharedPreferences whenever you want to.
This is the best approach for small data, that can be used on the app launch. So you can quit your app and the data is still present - so can be read on the next app launch.
Or save the condition of your program to a text file, so that the program can "translate" it back into conditions before it stops, or what I do not recommend, it saves every object created with ObjectOutputStream.
I have a blank-ish Android Project and what I want to do is take the user to a different "page/screen" if it is their first time only.
I know the logic for this but since I'm new to Android, I'm unsure of how to code this.
Below are the steps I believe I need to take in order to accomplish this:
App loads. If Local storage contains setting "FirstTimeUser", then it is not their first time using the app. Show the MainActivity page. If FirstTimeUser setting does not exist, it is their first time using the app (or they have uninstalled and reinstalled it), so instead, show WelcomeActivity page.
After viewing Welcome activity page, create FirstTimeUser setting and set to False.
But how do I code this for an Android app?
Use shared preferences as shown:
//declare as global
SharedPreferences prefs = null;
//and in your onCreate method:
prefs = getSharedPreferences("packageNameHere", MODE_PRIVATE);
if (prefs.getBoolean("firstrun", true)) {
//do stuff here if first run
//make sure to flag the boolean as false
prefs.edit().putBoolean("firstrun", false).commit();
}
else{
//if not first run, do something else
}
There is something called "SharedPreferences" that i believe your looking for.
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html
I want to pass strings to all pages in my android app. When the user logs in I save userName and others to strings. I want to send the strings over multiple pages. How can I do that?
I have tried to send it through Intent
Intent myIntent = new Intent(view.getContext(), Help.class);
myIntent.putExtra("userName", userNameString);
startActivityForResult(myIntent, 0);
But when I go to another page I dont want to keep sending the data through Intent every time.
I have tried to get it from the class where I parse and put them in strings
HomeScreen home = new HomeScreen();
String userName= home.userNameString;
But since i am creating a new instance of the HomeScreen then userNameString is null
Any help will be greatly appreciated
Beware of using a static or instance variable to hold this state as the memory state of an Android application can be in flux. Data only stored in memory can be destroyed without your knowledge if your application process is killed while in the background.
The simplest mechanism would be to persist your data into SharedPreferences that you can access from any place in the application. So, first you save the string that you get from login (this is called inside an Activity, FYI):
//Write the username string to preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("userName", userNameString).commit();
Then elsewhere in your application (i.e. other Activity instances) can read that string:
//Read the username string
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userName = prefs.getString("userName", "");
With SharedPreferences, your values are actually persisted, meaning they will live forever on disk and won't go away just because your application's memory is reset (this is usually an advantage, especially for login information). Because of this, you will also need to remove the string when your user "logs out" like so:
//Remove the username string from preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().remove("userName").commit();
There are also methods like contains() to allow you to check if the value is currently saved (is the user logged in?), etc.
The calling Activity is not guaranteed to remain in memory... the Android system may destroy it at any time.
If the child Activity depends on the user name, then the correct means of passing the information is with an Intent.
Declare a static variable and use it from everywhere:
public class SomeClass
{
public static String userNameString;
}
Use it like:
Strign s = SomeClass.userNameString;
Change its value as:
SomeClass.userNameString = "new string";