How to auto-saved address of user? - android

Currently I have an EditText field which requires user to input their address. First time user has to input the address. How do I auto complete it when the same user use the app again ?

Use SharedPreferences. Here is a complete example

Use SharedPreferences
Call this to save:
SharedPreferences.Editor prefsEditor = getPreferences(MODE_PRIVATE).edit();
prefsEditor.putString("address", address.getText().toString());
prefsEditor.apply();
Call this to load:
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
address.setText(mPrefs.getString("address", ""));
Your going to want to add some further code to this such as:
Null checks

Related

Get last login details without webservicing

need an idea to get last login details(DATE OF LAST LOGIN) on login without webservicing concept
Store Last login date into SQLLITE database when you need last login detail fetch this values from SQLLITE database.
instead of sqlite use SharedPreferences
you will have to create an object of shared preference and an editor
it will be similiar to this:
SharedPreferences sp;
SharedPreferences.Editor ed;
ed=sp.edit();
ed.putBoolean("username",username);
ed.commit(); //**DONT FORGET TO COMMIT**
sp = getSharedPreferences("MenuData", MODE_PRIVATE);
if(!sp.contains(null))
{
username=sp.getBoolean("username",defaultvalue);// you need to add an default value
if(username.equals("admin")){
//do watever u like
}
}
soloved the problem,
setting the value before even putting;
min=c.get(Calendar.MINUTE);
seconds=c.get(Calendar.SECOND);
SharedPreferences prefs1 = getSharedPreferences(
"DATE", MODE_PRIVATE);
datee = prefs1.getString("SUBDATE", null);
DATE1.setText(datee);
SharedPreferences.Editor editor = getSharedPreferences("DATE", MODE_PRIVATE).edit();
editor.putString("SUBDATE", min+" "+seconds+" ");
editor.commit();

Can't get SharedPreferences with activity

Sorry for my bad English.
On my application, I save token (it's a web app) in shared preferences. In first activity I do this:
(token = 123)
SharedPreferences sp = getPreferences(MODE_PRIVATE);
Editor ed = sp.edit();
ed.putString("token", Main.getToken());
ed.commit();
Log.d("Recieved token: ", sp.getString("token", "null")); // Recieved token: 123
As you see, shared prefs are saved.
I have another activity, which may be called from browser to share link.
Code:
sp = getPreferences(MODE_PRIVATE);
Log.d("Token recieved: ", sp.getString("token", "null")); // null
But on another activity shared prefs return null.
What can I do?
To explain the reason why getPreferences() didn't work for you:
When you call getPreferences() without specifying a Shared Preferences name, it returns a Shared Preference using the calling Activity's class name as the Shared Preference name. That's why you are getting null in your other activity - it's actually a different Shared Preference set that you are referring to.
Use getSharedPreferences instead, using whatever preferences name you like:
getSharedPreferences("my_prefs", Activity.MODE_PRIVATE);
That will then be available throughout your application. However using getPreferences() is suitable where you don't need to refer to the data stored outside of a particular Activity.
use like following,,
SharedPreferences mAppSettings = getSharedPreferences("SharedPref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = mAppSettings.edit();
prefEditor.putString(""token, "");
prefEditor.commit();
for retrieving,,,
final SharedPreferences mAppSettings1 = getSharedPreferences(
"SharedPref", MODE_PRIVATE);
String token= mAppSettings1.getString("token", "");

Storing data in SharedPreferences accessible to all activities

I want to store and retrieve data that is accessible to all activities in my app using SharedPreferences. Is that possible? Up until now I have been doing it such that the data is stored for a particular activity.
Yes. SharePreferences do exactly this.
In every activity you can this:
SharedPreferences prefs = getSharedPreferences(ApplicationConstants.PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(name, value);
editor.commit();
And then retrieve values in other activty doing this:
mPrefs.getString(name, "");
This is the documentation:
http://developer.android.com/reference/android/content/SharedPreferences.html
And this is a good example to start with:
http://myandroidsolutions.blogspot.it/2012/03/android-preferenceactivity.html
Yes, that's the whole purpose of it.
Here's how you should write to it, via Editor
final SharedPreferences shp = ctx.getSharedPreferences(ctx.getString(R.string.app_name), Context.MODE_PRIVATE);
final SharedPreferences.Editor ed = shp.edit();
ed.putString("var1", "var1");
ed.putString("var2", "var2");
And to load it:
shp.getString("var1", "defvalue");
I have a better version. As sometimes when you try to do getSharedPreferences you might get an error as it could not be found.
This is how I store values in my Android projects.
Add
SharedPreferences sharedPreferences=this.getSharedPreferences("packagename", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("username", "specify name here").apply();
Package Name can be directly copied from top of the activity ex: com.example.name.projectname
Retrieve
String username = sharedPreferences.getString("username","");
If you want to access values in all of your activities I think the better way is storing in a custom Application class and later in activities you can:
((CustomApplication)getApplication()).getStoredValue()
Shared preferences are stored in files and this file access is slower.
Is my example for create function for set and get an object data called "USER"
For set sharePreference data
public void saveUser(User usuario) {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", usuario.getNombre());
editor.putString("username", usuario.getUsername());
editor.putString("pass", usuario.getContrasena());
editor.putString("roll",usuario.getRol());
editor.commit();
}
For get sharePreference data
public Usuario getUser() {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
User usuario = new User();
usuario.setNombre(sharedPref.getString("name", "null"));
usuario.setUsername(sharedPref.getString("username", "null"));
usuario.setContrasena(sharedPref.getString("pass", "null"));
usuario.setRol(sharedPref.getString("roll", "null"));
return usuario;
}
Important: set name to sharePreference in this case "A"

sharedpreferences makes all the variables same

I am using shared preferences to save 3 string fields. I am opening shared preferences everytime with following code in another class. I am calling this class via a function to save it.
mPrefs=context.getSharedPreferences(id, Context.MODE_PRIVATE);
After doing this, I am saving 3 fields which are id, name and surname of a person. Save process is successful. I am holding all of those 3 variables in an object which is called person. I can get info from shared memory. When I get the info for the first person with his Id, I can do it. I am writing it out to Log. it is successful. But after getting second person info with second person's id, first person object is also second person. Shared preferences assigns all the variables to same value.
Any helps will be appreciated. Thanks
EDIT
personGet.setId(mPrefs.getString("id", null));
personGet.setName(mPrefs.getString("name", null));
personGet.setSurname(mPrefs.getString("surname", null));
// This is for saving to shared preferences.
mPrefs = context.getSharedPreferences(person.getId(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("name", person.getName());
editor.putString("surname", person.getSurname());
editor.putString("id", person.getId());
// This is for saving. the "id" is unique for all users –
SharedPreferences is just a Map of Key Value pairs
Yes this will save your id under the key "id":
editor.putString("id", "abc");
But doing this will override it as the key "id" is the same:
editor.putString("id", "zxy");
So when you ask for the sharedPreference "id" you will get
zxy
EDIT
Don't forget to call commit(); on your sharedpreferences
when we get data from preferences we write it like this
personGet.setId(mPrefs.getString("id", ""));
When you edit or save something in shared preferences, you need to call "commit()".
It will be like that,
mPrefs = context.getSharedPreferences(person.getId(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("name", person.getName()).commit();

Remember me function between sessions

When I click on the 'remember me' checkbox, based on the codes it will save the username and password by sharepreferences. However, when I exit my application and go back, the username and password will disappear.
How do I save the username and password between sessions?
// Remember me function
CheckBox cbRemember = (CheckBox) findViewById(R.id.chkRememberPassword);
if (cbRemember.isChecked()) {
// save username & password
SharedPreferences mySharedPreferences = getSharedPreferences(
"PREFS", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putString("UserName",
String.valueOf(txtLogin.getText().toString()));
editor.putString("Password",
String.valueOf(txtPassword.getText().toString()));
editor.commit();
}
Same as you have put username and password strings inside the shared preference, you can retrieve the same by doing as below:
SharedPreferences settings = getSharedPreferences("PREFS",0);
settings.getString("UserName", "");
settings.getString("user", "");
But i think for implementing remember me functionality, just put a boolean flag whenever the login is successful:
editor.putBoolean("login",true);
and retrieve whenever app is re-started next time:
settings.getBoolean("login", false);
When you exit the app and go back, the onResume() method will be called. It's the place where you should put Paresh Mayani's codes to retrieve the username and password. Check here to understand the lifecycle of an activity in Android.
I think the problem is with the Activity.MODE_PRIVATE flag use instead getSharedPreferences("PREFS", MODE_WORLD_WRITEABLE) flag.

Categories

Resources