I want to know if its possible to keep information about an app in a while for example.
I have an app that access this file and get information about the choices that the user have made. For example:
I have a button for many events (event is a model), and i want to know if the user clicked in the button even after the application restarts.
I know that it is possible to keep information about login and password. Is possible to do something like this with other information?
Use Shared Preferences. Like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPrefValue()
{
SharedPreferences sp = getSharedPreferences("preferenceName", 0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPref(String thePreference)
{
SharedPreferences.Editor pref =getSharedPreferences("preferenceName",0).edit();
pref.putString("myStore", thePreference);
pref.commit();
}
You could call them like this:
// when they click the button:
writeToPref("theyClickedTheButton");
if (getPrefValue().equals("theyClickedTheButton"))
{
// they have clicked the button
}
else if (getPrefValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// this preference has not been created (have not clicked the button)
}
else
{
// this preference has been created, but they have not clicked the button
}
Explanation of the code:
"preferenceName" is the name of the preference you're referring to and therefore has to be the same every time you access that specific preference. eg: "password", "theirSettings"
"myStore" refers to a specific String stored in that preference and their can be multiple.
eg: you have preference "theirSettings", well then "myStore" could be "soundPrefs", "colourPrefs", "language", etc.
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
You can use SharedPreference to save your data in Android.
To write your information
SharedPreferences preferences = getSharedPreferences("PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_Id",userid.getText().toString());
editor.putString("user_Password",password.getText().toString());
editor.commit();
To read above information
SharedPreferences prfs = getSharedPreferences("PREF", Context.MODE_PRIVATE);
String username = prfs.getString("user_Id", "");
In iOS NSUserDefaults is used to do the same
//For saving
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:your_username forKey:#"user_Id"];
[defaults synchronize];
//For retrieving
NSString *username = [defaults objectForKey:#"user_Id"];
Hope it helps.
Related
I basically have this function that validates the click of the user:
this.btnTryAgain.setOnClickListener {
viewModel.responsePictures.observeForever {
manageResponse(it)
}
clickcount += 1
if (clickcount == 3) {
findNavController().navigate(R.id.errorComprovante)
}
}
The observer is responsible for managing the response of the service. So if the users clicks the button 3 times and it doesn't get any success response, it goes to the errorComprovante.
The problem is that if i use this code with the observer, it simply doesn't work.
Is there a way i can store the number of clicks so that it doesn't get lost? Thanks
Further Reading on Shared Preferences
Store the data in Shared Preferences.
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putInt("count", clickCounter);
editor.commit();
Then get the data from the preferences using
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE)
You could store the value in a hidden field, that way it would be kept on the client side and would stay as long the the page is not re-rendered.
Shared preferences, database, files. All ways to persist data.
*I'm new in learning android
I'm searching for any website that show on how to accept user detail for example name and age, and display it in another activity using sharedpreferences in newer version of code? Do you have any? The another activity will have a Back button pointing to the first activity. All I found was in older version and not matched in my Android Studio so, I've cancelled the program. Anyone?
In the first activity, you can save the user name and age like this:
private void saveUserInformation(String userName, int age) {
//In this activity save the name in the shared preference
SharedPreferences sharedPreferences = getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("user_name", userName).putInt("user_age", age).apply();
}
In the second activity, to get the user information, do this:
private void getUserInformation() {
//In the second activity or any other activity, you can get the userName and age like thi
SharedPreferences sharedPreferences = getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
String userName = sharedPreferences.getString("user_name", null);
int userAge = sharedPreferences.getInt("user_age", 0);
}
From your question and comment in other answers, i guess you need more explanation on how a shared preference works. When you save data in a sharedpreference, it gets saved in a file on the user device. After saving you can access that data from any activity as long as the activity has access. All you just have to do is put it in a shared preference using a unique key and get it where you need it using that same unique key. Hope it helps. If i my answer helps, don't forget to upvote. Thanks.
this is how you create a sharedpref
SharedPreferences sp=getSharedPreferences("MYPREFNAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit;
this is how you put data in it
editor.putString(key,string);
this.is how you retrieve that string back
sp.getString(key,DefaultString);
//in your first activity use
SharedPreferences sharedPreferences=getSharedPreferences("your_packagename", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("name","name_value").apply();
sharedPreferences.edit().putInt("age",age_value).apply();
//and now in your second activity to retrieve data
SharedPreferences sharedPreferences=getSharedPreferences("your_packagename", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("name","");
int age =sharedPreferences.getInt("age",0);
How can I save the the settings of my app? Right now, for example, I have a togglebutton to turn on/off. But if I restart my phone, the toggle button is turned back on. Its not saving the settings if I completely close the app. Can I like the save the settings to the phone as cookies?
Use Shared Preferences. Like so:
Put this at the top of your class: public static final String myPref = "preferenceName";
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPreferenceValue()
{
SharedPreferences sp = getSharedPreferences(myPref,0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPreference(String thePreference)
{
SharedPreferences.Editor editor = getSharedPreferences(myPref,0).edit();
editor.putString("myStore", thePreference);
editor.commit();
}
You could call them like this:
writeToPreference("on"); // stores that the preference is "on"
writeToPreference("off"); // stores that the preference is "off"
if (getPreferenceValue().equals("on"))
{
// turn the toggle button on
}
else if (getPreferenceValue().equals("off"))
{
// turn the toggle button off
}
else if (getPreferenceValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// a preference has not been created
}
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
Here is a link to a pastie with the code above modified to store a boolean instead: http://pastie.org/8400737
You need to use SharedPreferences to save the settings of your app locally. Refer this link for more details : http://developer.android.com/reference/android/content/SharedPreferences.html
Use SharedPreferences as,
To Save:
SharedPreferences settings;
SharedPreferences.Editor editor;
public static final String PREFS_NAME = "app_pref";
public static final String KEY_p_id = "KEY_test";
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
editor.putString(Login_screen.KEY_test, values.get(0));
editor.commit();
To Remove:
editor.remove("KEY_test").commit();
You should check out SharedPreferences. It's Android's way of persisting simple values. Or you could create a full database.
Use SharedPreferences to save small chunk of app data.
Check the developer's website for this.
Also check out this Tutorial for step by step guide.
You can use local DB like SQlite for for your app.
I've been trying to create a user profile section for my app where the user enters his information (Name, DoB, height, weight etc) and clicks submit. After this he's taken to the main menu of the app.
The problem I have is that if I close the app and run it again, this will obviously result in the app displaying the user profile section again and asks the user to enter his information.
I've been trying to look for a way in which the app saves the information that the user enters and remembers it. So for example when the user first uses the app, he gets the user profile section and enters his information. When the user closes the app and opens it again it should take him straight away to the main menu.
I know I could achieve this slightly with Preferences, but I'd rather use a normal layout(LinearLayout) so that it gives me more options such as TextView etc.
Is there a way where I could achieve this using just LinearLayout instead of Preferences?
I've also been looking at creating custom Preferences, but none of the things I found was particularly useful.
Thanks in advance.
Use SharedPreferences.
Check the application for First Run and display layout which you want to enter user's profile.
After store boolean flag for first Run in shared Preference which will prevent your Profile Screen to display again.
Look at Check if application is on its first run
Update:
Put this FirstRun() code in your onCreate() of Main Activity.
private void FirstRun()
{
SharedPreferences settings = this.getSharedPreferences(MainActivity.PREFS_NAME, 0);
boolean firstrun = settings.getBoolean("firstrun", true);
if (firstrun)
{
// Checks to see if we've ran the application b4
SharedPreferences.Editor e = settings.edit();
e.putBoolean("firstrun", false);
e.commit();
// Display User Profile Screen
}
}
use sharedPreference to store information by this way..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("userid", "success");
editor.commit();
and to get the value from it use below code..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref2.getString("userid", null);
or try to use SqliteDatabase or may be Application Class..this will store the information as you want.
#Override
public boolean saveUserData(UserModel userModel, Context context) {
email = userModel.getEmail();
firstName = userModel.getFirstName();
lastName = userModel.getLastName();
twitterId = userModel.getTwitterId();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor setUserDataPreference = userData.edit();
setUserDataPreference.putString(EMAIL, email);
setUserDataPreference.putString(FIRST_NAME, firstName);
setUserDataPreference.putString(LAST_NAME, lastName);
setUserDataPreference.putString(TWITTER_ID, twitterId);
setUserDataPreference.commit();
return true;
}
#Override
public UserModel getUserData(Context context) {
UserModel userModel = new UserModel();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
email = userData.getString(EMAIL, "");
firstName = userData.getString(FIRST_NAME, "");
lastName = userData.getString(LAST_NAME, "");
twitterId = userData.getString(TWITTER_ID, "");
userModel.setEmail(email);
userModel.setFirstName(firstName);
userModel.setLastName(lastName);
userModel.setTwitterId(twitterId);
return userModel;
}
I'm a novice Android developer who are currently trying hard to build a Login Screen.
I need to find the easiest way to store the username and password in 1 class and retrieve it from another class. See Google has provided several ways: http://developer.android.com/guide/topics/data/data-storage.html
which one is the most efficient and easy to code?
thanks!
For Login screen tasks like storing username and password you can use Shared Preferences. Here I had made custom methods for using shared preferences. Call savePreferences() method and put your Key and Value(as savePreferences() is based on XML), similarly call Load with your Key. And lastly don't forgot to call deletePreferences() on LOGOUT.
/**
* Method used to get Shared Preferences */
public SharedPreferences getPreferences()
{
return getSharedPreferences(<PREFRENCE_FILE_NAME>, MODE_PRIVATE);
}
/**
* Method used to save Preferences */
public void savePreferences(String key, String value)
{
SharedPreferences sharedPreferences = getPreferences();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
/**
* Method used to load Preferences */
public String loadPreferences(String key)
{
try {
SharedPreferences sharedPreferences = getPreferences();
String strSavedMemo = sharedPreferences.getString(key, "");
return strSavedMemo;
} catch (NullPointerException nullPointerException)
{
Log.e("Error caused at TelaSketchUtin loadPreferences method",
">======>" + nullPointerException);
return null;
}
}
/**
* Method used to delete Preferences */
public boolean deletePreferences(String key)
{
SharedPreferences.Editor editor=getPreferences().edit();
editor.remove(key).commit();
return false;
}
Define some statics to store the preference file name and the keys you're going to use:
public static final String PREFS_NAME = "MyPrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";
You'd then save the username and password as follows:
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, username)
.putString(PREF_PASSWORD, password)
.commit();
So you would retrieve them like this:
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
if (username == null || password == null) {
//Prompt for username and password
}
Alternatively, if you don't want to name a preferences file you can just use the default:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
For your purpose both, SQLite Database and SharedPreferences will work. But I would suggest SharedPreferences as they are very easy to use. Some ppl like to create a class to hold variables like this but the benefit of SQLite and SharedPreferences file is that the user login name and password information will be with you even if the app goes in background and gets destroyed. So when the user comes back to your app, you can sign them in again without asking for password. If user explicitly decides to logout, you can simply remove the login information from shared preferences file
The easiest way of retrieving log in information from other activities is using "SharedPreferences". I strongly recommend this method for storage and retrieval of Username and Password. Because you can access this information from anywhere in the application without any complications. The log in information may have to use repeatedly in an application.
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) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of the 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) 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 mode 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.
(2) The recommended way is to use by the default mode, without specifying the file name:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
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 the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value 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 activities 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 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.
For more info, check this link:
Making data persistent in android