Android ==> Preference? - android

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.

Related

Can't access sharedpreferences from other activity?

I have a fragment where I let set some SharedPreference values set.
In the fragment, everything works fine - I can get any value I want, saving, editing, deleting works fine.
Then I have an Activity, from where I want to get the value "savedValue1" - but it does not work
public static final String MyPref = "MyPreference";
static SharedPreferences sharedpreferences;
//onCreateView...
sharedpreferences = this.getActivity().getSharedPreferences(MyPref,
Context.MODE_PRIVATE);
editor.putString("savedValue1", someString);
editor.commit();
I tried it with in Fragment:
public static String getValue(){
return sharedpreferences.getString("savedValue1","");
}
in Activity:
String newValue = Fragment.getValue();
But that doesn't work - any hint?
You should not have a Fragment.getValue() method.
SharedPreferences are here to avoid that.
Use the same getSharedPreferences("whatever", Context.MODE_PRIVATE) code and you shall get/set the same values inside the same preferences.
That is how it is supposed to be used. From the official documentation:
For any particular set of preferences, there is a single instance of
this class that all clients share.
Use this code to save and retrieve values from SharedPreferences
//To save string
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putString("savedValue1", someString);
e.commit();
//Retrieve team score
String saved_value = settings.getString("savedValue1", "");

SharedPreferences does not work for save

I'm using SharedPreferences to save username but it's not working.
In login Activity (read):
ocUserName = (EditText)findViewById(R.id.userNameText);
SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
String userNameKey = "userName";
String userNameTV = prefs.getString(userNameKey,null);
SharedPreferences.Editor editor = prefs.edit();
if(userNameTV != null) {
ocUserName.setText(userNameTV);
}
in second Activity (write):
SharedPreferences prefs =
getSharedPreferences("com.mesbahsoft.IRIB", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
String userNameKey = "userName";
editor.putString(userNameKey, ocUser);
editor.commit();
Activity.getPreferences(int mode) (as used in your login activity) has a comment:
Retrieve a {#link SharedPreferences} object for accessing preferences that are private to this activity.
In your second activity you use Activity.getSharedPreferences(String name, int mode) and provide what looks like your Application Id as the name.
In effect, you are using two different sets of shared preferences in each activity.
I recommend using PreferenceManager.getDefaultSharedPreferences(Context context) if you intend to use the shared preferences throughout your application.
I assume the problem is that you are unable to read the written value. You need to use the same file in login activity:
SharedPreferences prefs = this.getSharedPreferences("com.mesbahsoft.IRIB", Context.MODE_PRIVATE);
If this does not work, kindly specify clearly where you are seeing the problem and also specify exceptions seen.
You are accessing different shared preferences in your activities,
this.getPreferences( Context.MODE_PRIVATE); is shorthand for this.getSharedPreferences( <activity's class name>, Context.MODE_PRIVATE);
In you login activity, use this,
getSharedPreferences("com.mesbahsoft.IRIB", MODE_PRIVATE);
References:
http://developer.android.com/reference/android/app/Activity.html#getPreferences(int)
http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String,int)

Using shared preferences to store image URLs

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();

How setup default value Shared Preferences in an android apk?

I make a setup class with shared preferences and in the first open apk the user use the default value and after edit if he want it with update value. My problem is when re open the apk and no create preference apk display default value else if there is old preference display this. I want update preferences onCreate with old save preferences if preferences exist(no with default value). How I create this? I want something if pref exist go to share preference...and read value...else use the default
String strValue ="http://www.power7.net/LEDstate.txt";//default value
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
/* SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
String strValue = preferences.getString("Url","");
text = (TextView) findViewById(R.id.textUrl);
text.setText(strValue);
*/
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
}
public void Save(View view) {
SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
editor.putString("Url", strUrl); // value to store
// Commit to storage
editor.commit();
Change your code as for setting default value in TextView when user start your Application or any value not exist in SharedPreferences
SharedPreferences preferences;
String strValue="";
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
text = (TextView) findViewById(R.id.textUrl);
preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
strValue = preferences.getString("Url","");
if(!strValue.equals("")){
text.setText(strValue);
}
else{
text.setText("Set Default value here");
}
// your code here
In this way, you can get default value from preference if no value is their corresponding to your preference key
SharedPreferences preferences=getSharedPreferences(preferencename, MODE_PRIVATE);
String str=preferences.getString(key, defaultValue);

Trouble using sharedPreferences between two activities

I am trying to save a date in one activity and then have that date put in a textView in another activity. I am not sure about how to get the two activities to communicate with each other.
In file called report.java I have this method that gets the date and save it in sharedPrefernces.
private void updateLabel() {
date.setText(fmtDate.format(dateAndTime.getTime()));
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("date", date.getText().toString()); // value to store
editor.commit();
}
I am trying to figure out how to get my file called inspection use this to populate a textView
The problem I think I am having is with getting the correct name for the report file.
public static final String PREF_FILE_NAME = "report";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
then I have this code on a method called onResume()
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String strDate=preferences.getString("date", date.getText().toString());
date.setText(strDate);
}
You are saving the value to two seperate preference files.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
Use only one.
Why not use the default preference file that is accessible by all classes/activities of your app?
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(yourContext);
preferences.edit().putString(YOURKEY, yourStrValue);
This way you are not creating extra preference files in your app that you have to remember which values are stored in which files. Definately makes life easier.

Categories

Resources