Shared preference - android

I developed one app in that I want to send URI from Class1 editText to another class containing editText.
Can anyone tell me how to do that?

SharedPreferences are the wrong way to do that. Use the Bundle feature every Intent can have: http://developer.android.com/reference/android/content/Intent.html
On the second activity you can call getExtra() and there you go...

Assuming you want to use the SharedPreferences to transfer the URI, you could try this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putString("my-uri", "http://google.com/").commit();
And to retrieve the URI:
prefs.getString("my-uri", "default URI");
If your two classes are Activities, and if one of them starts the other one, you should probably pass the URI as an intent extra.
Also, read the FAQ and accept some answers!

you can use System.setProperty/get Property as well.

don't you like to add putExtra in intent
like this
Intent i = new Intent(getApplicationContext(), Audit_FSD_Tab.class);
i.putExtra("UsrID", UsrID);
i.putExtra("Store", Store);
i.putExtra("location", location);
startActivityForResult(i, 0);
now in other activity access these extra
Bundle UsrVal = null;
UsrVal = this.getIntent().getExtras();
UsrID = UsrVal.getString("UserId");
Store = UsrVal.getString("Store");
location = UsrVal.getString("location");

Try to store Uri in the edit text inside shared preferences in first activity and then on create method of second activity retrieve Uri value from the shared preferences and display that in edit text.simple...

It can be possible by using Shared Preferences, for example
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
data=pref.getString("key_name5", null);
editText.setText(data);
You can follow tutorial here
http://firstcode.info/android-sharedpreferences-basics/

Related

Passing Value in 3 activities in Main activity

I have 3 buttons in main activity, this 3 buttons opens another activity, it is easy, medium and hard game type. i want to get the scores of each level of difficulties and store it in main activity, any example for this one? any help would greatly appreciated thank you!
The easiest way to do this would be to pass variable you want to share to the main activity in the Intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("EXTRA_SESSION_ID", variable);
startActivity(intent);
Access that intent on next activity
String variable= getIntent().getStringExtra("EXTRA_SESSION_ID");
The docs for Intents has more information (look at the section titled "Extras").
You can store variable to any variable you want in MainActivity and use it.
You can create a Util Class, in that Class create a static variable named difficulty.
Assign it according to Button pressed.
Inside OnClickListener assign it, later retrieve it.
Thanks.
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences("MyPref",
MODE_PRIVATE).edit();
editor.putInt("begginer", 120); // put begginer level score here
editor.putInt("medium", 37); // put the medium level score here
editor.putInt("hard", 12); // put hard level score here
editor.apply();
To Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
int begginer_score = prefs.getInt("begginer", 0); //0 is the default value.
int medium_score = prefs.getInt("medium", 0); //0 is the default value.
int hard_score = prefs.getInt("hard", 0); //0 is the default value.

Android: remember string when opening new activity

my activity has a string which gets its value from an intent
String myString = intent.getStringExtra("KEY");
in this activity I start another activity. From the new activity I want to return to the previous activity and still have the same value of myString. But when I open a the new activity the value of myString is deleted.
i looked into onSavedInstancState but that doesn't seem to work.
making myString static works but I think that this is not good programming.
So what would be the best way of doing this?
Use ShareDPreferences to store an object that you want to retrieve later:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("key", ""KEY");
editor.commit();
To retrieve it later:
pref.getString("key", null);
You can use SharedPreferences,
If you have a relatively small collection of key-values that you'd
like to save, you should use the SharedPreferences APIs.

How to bypass intent extras in Android?

I want to know if there is a way to pass all the extras to the new intent.
Is it possible? And is it a good idea?
The reason is that I want to save the login state as a json string, and pass it in between Activities. I don't want to store data with SQLite or anything. Can I bypass all the intent extras to the new intent ?
please consider Shared Preference :
// Declaration
public static String KEY = "SESSION";
public static void saveUserName(String username, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", username);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
You can store the login credentials to preference and retrieve them as well in any of your activity.
SaveUsername("Your text to save", Your_activity.this);
And to retrieve the value
String mUserName = getUserName(YourActivity.this);
It is recommended to have all your preference methods in your utils class to keep the code organized.
You can read more here
yes you can use Shared Preference to save the Login session of user here is handy example of managing session using shared preference http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/ I used it earlier and suggest you to have a look at it.
Any of the two may help you.
Saving it in the sharedPreference file.
If you want them to be accessable throught the application you can use the applicationClass, like a global singleton.

How to pass data between activities

My question is how to pass data like String between two activities. Normally I would do this:
Intent i = new Intent(thisclass.this,NextClass.class);
Bundle b = new Bundle();
i.putExtras(b);
b.putString("Name",Name);
StartActivity(i);
But this would make my Activity close and will open the next Activity, no? Is there any way that I can only pass data without opening the other activity?
I think you are looking for something with the SharedPreference see the documentation : SharedPreference
if it is what are looking for.
Try this:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna save your data:
String data = "yourData"
pref.edit().putString("myData", data).commit();
And the other Activity:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna take your data:
String dataFromFristActivity = pref.getString("myData", null);
Your calling activity does not close but is paused.
I am with #Egor on this. The called activity does not yet exist. Unless u are trying to send data between activities in two different apps. That is a whole different can of worms.

SharedPreferences

I'm creating a SharedPreferences and it's working only if I start Activity like this:
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
But my SharedPreferences is not working after I save it and hit back a few times, to go at menu page and go to the page where I want to get my preferences.
Anyone can help me with that?
Code below:
This is where I save my preferences:
String MYPREFS = "MyPref";
SharedPreferences mySharedPreferences;
SharedPreferences.Editor myEditor;
Inside onCreate:
mySharedPreferences = getSharedPreferences(MYPREFS,0);
myEditor = mySharedPreferences.edit();
Inside button onClickListener:
myEditor.putString("address", AddressET.getText().toString());
myEditor.putString("contact", ContactET.getText().toString());
myEditor.commit();
Intent myIntent = new Intent(myContext, nok_individual_particular.class);
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
This is the activity I pass to:
SharedPreferences mySharedPreferences;
Inside onCreate:
Intent myReceivingIntent = getIntent();
String myPREFName = myReceivingIntent.getStringExtra("prefName");
mySharedPreferences = getSharedPreferences(myPREFName, 0);
applySavedPreferences();
In the applySavedPreferences method:
String addressValue = mySharedPreferences.getString("address", "Jack Smith");
String contactValue = mySharedPreferences.getString("contact", "Jack Smith");
addressTV.setText(addressValue);
contactTV.setText(contactValue);
SharedPreferences: This is how it works
To save your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString("valueName", "value");
editor.commit();
To retrieve your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
String strMyData = sPrefs.getString("valueName", "default value");
The example above is how to set a string and retrieve it.
You are not using SharedPreferences. In your example, you are passing an extra to an activity, but this only makes available the value to the new activity, it doesn't save the value to SharedPreferences.
To use SharedPreferences, you have to do the following:
Save
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("prefName", "String to save").commit();
Get
String value = PreferenceManager.getDefaultSharedPreferences(this).getString("prefName"), "default value");
After mySharedPreferences.edit();
mySharedPreferences.commit();
should be your last line. This enables u to save and close the SharedPreferences file you have edited.
Well, you don't need to pass the sharedprefs in an intent and all. It will be available throughout your application in all activities.
Just call SharedPreferences my_prefs= getSharedPreferences("Pref_name", 0); and then u have a reference to that SharedPreferences file and then u can retrieve values from it.
I prefer using SharedPreferences to save my data and use it throughout my classes , plus they will be saved to the device , making them available even after the app is killed ... Here is an example for ya !
//Some String that I should remember, I am just using the package name for now
String app = this.getPackageName();/*This is going to be used more like a file to save my stuff to*/
//Setting our sharedpreferences
SharedPreferences sha = sha = getApplicationContext().getSharedPreferences(app, SherlockActivity.MODE_PRIVATE);
String myString = "This is the String that you want to save so you can use among your classes"
//Now we call in an editor for that SharedPreferences so we can write and delete stuff from it .
Editor edit = sha.edit();
//Now we insert our String.
edit.putString("Something_you_can_remember" , myString);//You will need the "Something_you_can_remember" a few lines ahead , so remember it !
edit.apply(); //Or we can use edit.commit() , but I prefer apply()
//Now our String is saved ! So lets read it !
String whatever = sha.getString("Something_you_can_remember" , "The String incase myString didn't even exist , saves you from a NullPointerException");
//Here we go ! Now we have our String saved and can be readable among the classes !
//Also , if you wanted to delete that String or whatever you "put" in there , you can call
edit.remove("Something_you_can_remember"); //or edit.clear() to remove all the values stored !
Hope this helps !
Save
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("valueName", "String to save");
sedt.commit();
Get
SharedPreferences sp = getSharedPreferences("key", 0);
String valueName = sp.getString("valueName","");
You do not need to pass SharedPrefences through intents, as SharedPreferences are available to the whole application and any activity has access to it.
You can refer to below example:
Either create SharedPreferences by giving them your choice of name:
SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
OR use default SharedPreferences:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Use your preference file anywhere in your code by getting them through any of the above methods. No need to pass to different activities.
Once you call any of the above method, if the preference file of that name does not exist for your application, android will create one for you.

Categories

Resources