Save intent in shared preference - java

I have an application from which i can launch other apps installed on my phone, with a long click i get the app picker, in result i receive an intent data, how can i save it so the user when closes an comes back to my app has the same shortcuts setup?
i save other things like this
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putBoolean("FirstRun", firstRun);
editor.putString("Label2", label2S);
editor.commit();
But i can't do the same with the intent

Ok i found a way
I save the intent like this
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
SharedPreferences.Editor editor = settings.edit();
String uriString = data.toUri(requestCode);
editor.putString("Contacts_app", uriString);
editor.commit();
Then i retrieve it like this
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
String contactsApp = settings.getString("Contacts_app", null);
try {
telApp = Intent.parseUri(contactsApp, 0);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

You could serialize the object to a string, and save the resulting string in the preferences. An easy way would be to serialize it in json format, using Google Gson for example.

Related

sharedPreferences.getString() return null

Im trying to display the user email in a textView using SharedPreferences.
Shared preferences is created in loginActivity.
I try to access it from mainActivity.
My session using sharedPreference work well (with a login boolean saved in sharedPreferences files).
So what's wrong?
- A context error?
- Because I try to access the data from an another activity?
Please help :) Thanks a lot!
Here is the code im using :
Login Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
...
//Creating a shared preference in a login()
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
editor.putString(Config.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
...
Main Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
email_session = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Private");
usernameText.setText(email_session);
}
to read the stored preferences you need to do:
to save
SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("myTextViewValue", prefVal); //
editor.commit();
to read it
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
String storedPreference = preferences.getStr("myTextViewValue", null);
This happens because your value is not stored in the shared preferences.
SharedPreferences pref = getSharedPreferences("your Pref Name", 0) // 0 for Private Mode
String name = pref.getString("your key store when login", null); // null is the default value you can put it here "No value". then you will not get null pointer.

SharedPreferences Login

I'm trying to create something that needs to get information in the first time and save it. The app starts at the MainActivity, if it does not have the information needed, the app send you to the MotoActivity. Once the app has the information you don't need to go to the MotoActivity anymore. I know i'm wrong but I don't know how to do.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("valid", 0);
editor.commit();
int n = sp.getInt("valid", -1);
if(n == 0){
editor.putInt("valid", 1);
editor.commit();
startActivity(new Intent(MainActivity.this, MotoActivity.class));
MainActivity.this.finish();
}
First check for the very first time that, if "userLoggedBefore" is true or false from the SharedPreferences, if the user had used the application before and had entered the right credentials, we will save authenticated to true and if he hasn't we will set the default value as false.
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
boolean authenticated = sharedPref.getBoolean("userLoggedBefore", false);
then check -
if (authenticated){
//show your MainActivity
} else {
// show your MotoActivity
}
in your MotoActivity,
//if credentials matches
if(credentialMatches)
SharedPreferences sharedPref = getSharedPreferences(
"Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", true);
prefEditor.commit();
else{ // if credentials doesn't match
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", false);
prefEditor.commit();
}
Try this:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// app already has the needed info.
if(sp.getInt("valid", -1) == 1){
// do something
}
// app needs info. first, when you have got the info. in MotoActivity then set preferences key 'valid' to 1
else{
startActivity(new Intent(MainActivity.this, MotoActivity.class));
finish();
}

How to log out from google account in android ?

I am developing application that uses login using google Auth2.0 with android account manager. I am login successfully and fetching data from my google using different apis but I don't know about how to log out from my application and when logout want to shows login screen once again.
I don't think you can log-out, you will have to show the AccountChooser again
try
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[] {"com.google"}, false, null, null, null, null);
startActivityForResult(intent, SOME_REQUEST_CODE);
Usually i saved the account name on SharedPreferences and on log-out just remove the account name from the SharedPreferences. Saving the account name from onActivityResult
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
//do the rest after saving the account name on SharedPreferences
}
}
And log out(my log out occur on a different activity):
private void logOut(){
SharedPreferences sharedPreferences = getSharedPreferences("MainActivity",Context.MODE_PRIVATE);
if (sharedPreferences.getString(PREF_ACCOUNT_NAME,null)!=null){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(PREF_ACCOUNT_NAME);
editor.commit();
//here show the log-in screen again
}
}
While logging in you have saved data i.e. your access token in shared preferenes. So when you want to LogOut clear shared preferences. It is the only way to logout.

SharedPreferences not working as expected, cannot read nor write preferences

private void init() {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
// SET VALUE RECORD
record = prefs.getInt("record", 0);
prefs.edit().commit();
}
private void setRecord(int i ) {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
if(i > prefs.getInt("record", 0))
prefs.edit().putInt("record", i);
prefs.edit().commit();
}
private int getRecord() {
int rec;
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
rec = prefs.getInt("record", 0);
prefs.edit().commit();
Toast toast = Toast.makeText(this, rec+"", Toast.LENGTH_SHORT);
toast.show();
return rec;
}
this code should set an int and retrieve it, but it doesn't seem to ever set it... can you see why is that?
Think it is best to call the interface SharedPreferences.Editor to edit preferences instead of using prefs.edit().putInt("record", i);. The docs say...
Modifications to the preferences must go through an
SharedPreferences.Editor object to ensure the preference values remain
in a consistent state and control when they are committed to storage.
If you change your setMethod to the following it should work...
private void setRecord(int i ) {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if(i > prefs.getInt("record", 0))
editor.putInt("record", i);
editor.commit();
}
And I guess you are calling the above method setRecord somewhere in your code as I can't see it being called anywhere in the code snippet you pasted.
try
Editor editor = prefs.edit();
editor.putInt("record",i);
editor.commit();

How to launch activity only once when app is opened for first time after an update?

What would be the most logical way to go about launching an activity when an app is opened for the first time after an update. I understand that a sharedprefs would be the easiest way for this, but sharedprefs are persistent across application updates so it wouldn't seem that that option would work. Any ideas?
Make the shared pref store the version number of the app: if the version is different, update it and then launch your Activity.
EDIT: this is what I do in my what's new check. It loads up the app info, fetches the version number and if it has changed it pops open the Activity.
public static boolean show(Context c)
{
ApplicationInfo ai = c.getApplicationInfo();
String basis = ai.loadLabel(c.getPackageManager()).toString();
try {
PackageInfo pi = c.getPackageManager().getPackageInfo(c.getPackageName(), PackageManager.GET_META_
DATA);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
String lastVersion = prefs.getString("lastversion", null);
SharedPreferences.Editor edit = prefs.edit();
if(lastVersion == null){
// save the first installed version so we can check and see when it got installed
edit.putString("firstversion", String.valueOf(pi.versionCode));
edit.commit();
}
if(lastVersion == null || pi.versionCode > Integer.parseInt(lastVersion)){
edit.putString("lastversion", String.valueOf(pi.versionCode));
edit.commit();
// show it
Intent i = new Intent(c, WhatsNew.class);
c.startActivity(i);
return true;
}
} catch (Exception e) {
android.util.Log.v("WhatsNew", "Exception checking for release notes for [" + basis +
"]:" + e.getMessage(), e);
}
return false;
}

Categories

Resources