Using shared preferences to store image URLs - android

I am trying to figure out how I would achieve storing image URLs via onClick of an item button so they can be accessed by another class.
I have looked around and saw that it would be best to achieve this using shared preferences.
I have never used shared preferences before so I am a little confused as how I will be able to achieve this because I would like to get the URL from the String I have called "mImageUrl"
I know my String "mImageUrl" will give me the URL of the image that is currently being viewed, so I like to somehow store the String/URL from my String to shared preferences so the specific URLs can used via another class.
Would using shared prefs be a good way to achieve my requirement,
Any guidance would be appreciated thanks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.SetWallpaper:
new SetWallpaperAsync(getActivity()).execute(mImageUrl);
break;
case R.id.SaveWallpaper:
new SaveWallpaperAsync(getActivity()).execute(mImageUrl);
break;
case R.id.FavouriteWallpaper:
//Use shared preferences here somehow:
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
SharedPreferenceUtil.setSharedPreference(context, "ImageKey", mImageUrl);
String url = SharedPreferenceUtil.getSharedPreference(context,"ImageKey",null);
if(url != null){
// set image source here..
}
break;
}
return super.onOptionsItemSelected(item);
}

Try this code:
Save in SharedPreferences :
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(contextActivity);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("imgUrl", UrlString);
editor.commit();
To retrive value:
prefs = PreferenceManager.getDefaultSharedPreferences(contextActivity);
prefs.getString("imgUrl", null);

try this
in one Activity :
SharedPreferences sp;
SharedPreferences.Editor edit;
sp = getSharedPreferences("enter", MODE_PRIVATE);
edit = sp.edit();
edit.putString("imagerul", user_validate);
edit.commit();
in next activity :
SharedPreferences sp = getSharedPreferences("enter", MODE_PRIVATE);
sp.getString("imageurl", "fdgf"));

You can simple implement a class that handles get/set operations of shared preferences.
I will provide a class so that you can easily integrate to your project.
Here is our SharedPreferenceUtil class
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreferenceUtil {
public static String getSharedPreference(Activity activity, String prefName, String key, String defaultValue){
SharedPreferences prefs = activity.getSharedPreferences(prefName,0);
String pref = prefs.getString(key, defaultValue);
return pref;
}
public static void setSharedPreference(Activity activity, String prefName, String key, String value){
SharedPreferences prefs = activity.getSharedPreferences(prefName,0);
SharedPreferences.Editor editor = prefs.edit();
// edit and commit
editor.putString(key, value);
editor.commit();
}
}
You can simply set/get preference from your activity with the following code sample.
// You can set your shared preferences like following.
SharedPreferenceUtil.setSharedPreference(this.getActivity(),"pref","yourImageKey","yourImageUrl");
// and you can get your shared preferences like following.
String url = SharedPreferenceUtil.getSharedPreference(this.getActivity(),"pref","yourImageKey",null);
if(url != null){
}
EDIT:
You can reach SharedPreferences from a Fragment by following
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
Hope this may help.

Try:
SharedPreferences pr=PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor r=pr.edit();
r.putString("name","yourlink");
r.commit();

Related

Android SharedPref not saving on restart

In my Android app I can display a popup when the app is updated (Based on versionCode). In the popup I have put a checkbox saying "dont show me again". When I click on that, it will save in the sharedpref the versionCode and wont display the popup anymore.
I have run against something odd behaviours where when I have saving the new Set<String>, it did indeed was saving it but when my app restarts the settings is lost.
Set<String> readAnnouncement = getReadAnnouncement(this);
readAnnouncement.add(String.valueOf(versionCode));
PreferenceManager.getDefaultSharedPreferences(this).edit().putStringSet(KEY_READ_ANN, readAnnouncement).apply();
If I break point on readAnnouncement.add, I can set for example the list having 2 items. When I execute the PreferenceManager.getDefaultSharedPrefer... and then execute getReadAnnouncement(this); the value is there, all good.
If I restart the app and check again getReadAnnouncement(this); the new value is gone.
By clearing the cache the problem disappeared... Why was is not saving? Is it possible the SharedPreference were full?
Try like this.
import android.content.Context;
import android.content.SharedPreferences;
/**
* #author VIVEK
* This class deals in with setting Cache value for complete app.
*/
public class SharedPrefUtil{
/*Set Boolean value in shared preferences */
public static void setSharedPref(Context context, String key, boolean value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
/*get Boolean value in shared preferences */
public static boolean getSharedPref(Context context, String key, boolean defaultVal) {
boolean prefToken = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
prefToken = sharedPreferences.getBoolean(key, false);
return prefToken;
}
/*Set String value in shared preferences */
public static void setSharedPref(Context context, String key, String value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
/*get String value in shared preferences */
public static String getSharedPref(Context context, String key, String defaultVal) {
String value = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
value = sharedPreferences.getString(key, defaultVal);
return value;
}
public static void cleanSharedPrefFile(Context context) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
} // End of main class over here ...
Now you want to set some value in Shared Pref then set like this
SharedPrefUtil.setSharedPref(MainActivity.this, "test", storeBuff);
Now when you need to get value from shared Pref then call like this
SharedPrefUtil.getSharedPref(MainActivity.this, "test", "default value");
In place of editor.commit() , use editor.apply()
BASICS:
getDefaultSharedPreferences() uses a default preference-file name. This default is set per application, so all activities in the same app context can access it easily as in the following example:
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
if (spref.contains("email")) {
String sEmailAddr = spref.getString("email", "");
}
The preferences are usually stored at /data/data/com.package.name/shared_prefs/com.package.name_preferences.xml
The alternative method - getSharedPreferences(name,mode) requires to indicate a specific preference (file) name and an operation mode (e.g. private, world_readable, etc.), which allow to have better access over your SharedPref file.

Not able to clear shred preferences

This is in my main activity class, I can pass and retrieve data in my other class through shared preferences but I cant clear the shared preferences in my other class. Also tell me how to check that my shared preferences are cleared.
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "userKey";
public static final String Pass = "passKey";
sharedPreferences=getApplicationContext().getSharedPreferences(MyPREFERENCES,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name,userName);
editor.putString(Pass,password);
editor.commit();
this is in my other class
SharedPreferences sharedPreferences;
sharedPreferences=getApplicationContext().getSharedPreferences(SignUPActivity.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
editor.commit();
Hi if you want just pass value from one Activity to Another or One Fragment to other than I suggest you to use INTENT to pass data
Look at this example how to pass -http://startandroid.ru/en/lessons/241-lesson-28-extras-passing-data-using-intent.html
Also -https://stackoverflow.com/a/30166602/4741746
sharedPreferences is used when data used for all activity which is permanatly stored in application you also can clear data
Remove given String from shearedPrefrance
public static void removeFromSharedPreferences(Context mContext, String key) {
if (mContext != null) {
SharedPreferences mSharedPreferences = mContext.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, 0);
if (mSharedPreferences != null)
mSharedPreferences.edit().remove(key).commit();
}
}
Remove All value from SharedPrefrance
public static void removeSharedPreferences(Context mContext) {
if (mContext != null) {
SharedPreferences preferences = mContext.getSharedPreferences("PREFERENCE", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
}
}
And why your code is not working is you have to passs Context.MODE_PRIVATE insted MODE_PRIVATE jsut confirm both should have same value
Put this code in both the classes
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Possible Reason is you are not using the same preferences.
In your first activity you are using:
sharedPreferences = getApplicationContext()
.getSharedPreferences(MyPREFERENCES,MODE_PRIVATE);
And in the other activity you should also use it.
Try to read these
http://developer.android.com/reference/android/app/Activity.html
also from the docs
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity. This simply calls the underlying
getSharedPreferences(String, int) method by passing in this activity's
class name as the preferences name.

sharedPreferences in Fragment

I know this has been asked before, but i can't seem to figure it out
i am trying to get my preferences by this:
SharedPreferences preferences = this.getActivity().getSharedPreferences("storedName", Context.MODE_PRIVATE);
String loginemail = preferences.getString("storedName", "");
but this doesn't seem to work, i have multiple sharedPreferences which i need to get in my fragment what is the correct way to do it?
As getDefaulSharedPreferences(this) doesn't work.
i store my prefs like so:
savePreferences("shareUniqePass", uniqePassIds.getText().toString());
savePreferences("storedName", inputEmail.getText().toString());
savePreferences("Storedpass", inputPassword.getText().toString());
private void savePreferences(String key, boolean value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor checkbox = sharedPreferences.edit();
checkbox.putBoolean(key, value);
checkbox.commit();
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor names = sharedPreferences.edit();
names.putString(key, value);
names.commit();
}
Instead of getting it from getSharedPreferences use the getDefaultSharedPreferences.
As getDefaulSharedPreferences(this) doesn't work.
You used getDefaultSharedPreferences for saving the data and therefore you must use getDefaultSharedPreferences to get the data that was saved.
this mean the instance of your fragment instead use the getActivity() to get the instance of context from your activity.
sample:
String loginemail = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(PREF_USER_NAME, "");;
You need to make sure that your saving and loading the data from the same shared preferences. If you're only accessing it from the one activity / fragment, you should use getDefaulSharedPreferences(this).
If, however, you're going to use it from several different activities / fragments, you should use:
private void savePreferences(String key, boolean value){
SharedPreferences prefs = getActivity().getSharedPreferences("storedName", Context.MODE_PRIVATE);
Editor checkbox = sharedPreferences.edit();
checkbox.putBoolean(key, value);
checkbox.commit();
}

error in saving the username at the launch of application in android

I am developing an android application in which i have to do the following thing
At the start of the app, first thing it should do is ask user to enter name and then through a welcome screen with that name.
Then When the app is used next time it should just give welcome screen (should not ask for name again)
I have created the code for the above.
I have used shared preference saved
My code is
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}
But how to check whetehr user is already registered?
Thanks
Tushar
But how to check whetehr user is already registered?
When user starts application first time that time you will check if any preference value exists for name key.
Following snippet will help you
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String namePrefrence = sharedPreferences.getString("uname", "");
if (namePrefrence.length() == 0) {
//User not registered!!
Show dialog where user will enter username
} else {
//User is registered!!
just show welcome screen
}
Well to use SharedPrefernces.. use this::
first declare it...
public static final String PREFS_NAME = "PrefernceNAme";
public static final String PREFS_ITEM = "PrefItemStored";
to get values from it, use:::
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
mode = preferences.getString(PREFS_ITEM, "PrefItemStored");
and to add values in SharedPrefernces, use::
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_ITEM, value)
.commit();

Android ==> Preference?

my app crashes with a null pointer exception on the code below.
i have an xml preference file under res/xml/defaults.xml
Any idea why it's crashing?
public class Preference extends Activity {
public Preference()
{
}
public String getPreference(String key)
{
//it still crashes here
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
String result = settings.getString(key, null);
return result;
}
}
Preference files are not storead in project's /res/xml/defaults.xml
They are stored on the device in your application folder something like
/data/data/com.your.pkg/default.prefs
Try do not specify the file name, as you will have some problems with the preference files, like this OP had here
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Then you will probably have to query
preferences.getString('weightPref', null);
Here's a sample code which shows how to save and retrieve Preferences. Here I am saving username and password in SharedPreferences.
SharedPreferences uPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor; = uPreferences.edit(); //Instantiating editor object
protected void storeSharedPrefs(String username, String password) {
/*
* Storing in Shared Preferences
*/
editor.putString("username", username);
editor.putString("password", password);
editor.commit(); //Commiting changes
}
Retrieving username and password in another activity from SharedPreferences.
private SharedPreferences mSP;
mSP = getSharedPreferences("CurrentUser", MODE_PRIVATE);
String username = mSP.getString("username", null);
String password = mSP.getString("password", null);
Hope it helps..
Setting a value in the shared preferences:
Editor prefs = getSharedPreferences("Application_name", MODE_PRIVATE).edit();
prefs.putString("key", accountKey);
prefs.commit();
Getting the value from another activity:
String accountKey =
this.getSharedPreferences("Application_name", MODE_PRIVATE).
getString("key", null);
It would be nice if you access the variable by using some predefined handler, such as getString(R.string._key), instead of the hardcoded string "key".
Your Preferences should extend PreferenceActivity. Then you need to create a resource xml file for preferences, and reference that in your PreferenceActivity like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
etc.
}
The preferences xml should have a PreferenceScreen as the top level element, and you can take advantage of all the different preference views Android makes available to you for setting preferences. This would be the most common, and elegant way to do it.

Categories

Resources