Save and read int - android - android

I'm making a settings screen using an int to set the background of my app. It works just fine... inside the current activity. But as soon as I leave the activity, the int value is lost and the background isn't changed.
what I want to do: I want to save the int from my settings activity, and then import it to my other activites and check if the int "bak" equals null, "bg", "bg1" or "bg2".
I've heard of sharedPreferences but never got it working. That is why I open a new thread.

OK, add these global variables
SharedPreferences data;
public static String filename = "whateveryou want";
initialize it in onCreate
data = getSharedPreferences(filename, 0);
then to add something to it, use this, with "key" being a unique descriptor and name being the variable name you want to store
SharedPreferences.Editor editor = data.edit();
editor.putInt("key", name);
editor.commit();
access it by this, where default is what you want the variable to be assigned if no preference exists.
intVariable = data.getInt("key", default);
EDIT:
I noticed you want to use letters, eg bg1 etc. To do that you need to use a String, or use an int with a switch case or multiple if statements. Here's a switch case example you can modify. Just make sure to put the switch case statement after you access the SharedPreference in the previous code block.
switch (integerVariable){
case 1: // if the intagerVariable = 1, notice the : not a ;
// set background to BG1
break;
case 2: // if the intagerVariable = 2, notice the : not a ;
// set background to BG2
break;
}
Just add as many case statements as needed.

Related

Create SharedPreference from xml

I am using SharedPreference to store data between activities (it's not anything settings-related, just user data).
I created these static methods in a utils class to handle writing to/reading from shared preference from anywhere in my app:
public static <T> void saveData(Context context, String key, T value, String typeOfValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences("FILE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
switch (typeOfValue) {
case ("String"):
editor.putString(key, (String) value);
break;
case ("int"):
editor.putInt(key, (Integer) value);
break;
case ("Boolean"):
editor.putBoolean(key, (Boolean) value);
break;
default:
break;
}
editor.commit();
}
public static <T> T loadData(Context context, String key) {
SharedPreferences sharedPreferences = context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
return (T) sharedPreferences.getAll().get(key);
}
I have these questions:
If I do this way, when is the preference file "FILE" created? Is it created when the application is installed or only when the first save or load method is called? Is it an xml?
What if I want to make sure
A shared preference file called "FILE" is created when the application is installed.
Inside that file, declare a list of permanent keys (no more keys will be added later) and have them all set to default values.
How do I do that? I heard that creating the shared preference from XML might help, but after reading the android api, it seems like this kind of shared preference is for the "settings" in android only.
I know that you can "kinda" set the default value like this
String username = prefs.getString("username_key", "DefaultUsername");
But I don't want this since all my read methods are generic. Also, I don't like this cause I don't really know what happens under the hood. It doesn't seem like the default value is actually set into the preference file, it might simply return the default value if a value has not yet been set.
You can view the sharedPreference.xml.
Use Android Studio -> tools -> Android -> Android Device Monitor.
The file path is /data/data/<package_name>/shared_prefs
So you can test when the file created.

Can't Get Shared Preference Value Even Though Values Exist

Any time I try to getInt() from a SharedPreference my app crashes, yet I can iterate through the preferences as a map. For instance, see the starred lines below:
private void loadPref(){
myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
int sf = DEFAULT_VALUE;
Map<String,?> keys = myPrefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
if (entry.getKey().contentEquals("score_format"))
// this works: //*****
sf = Integer.parseInt(entry.getValue().toString()); //*****
}
// but this does not: //*****
// sf = myPrefs.getInt("score_format", DEFAULT_VALUE); //*****
setScoreFormat(sf);
}
Clearly, my prefs are being saved (as evidenced by this sample and working preference screens across multiple activities). I am calling super.onCreate() before trying to access getDefaultSharedPreferences.
What should I be considering to understand why this code is not working? Why would the map work but not the "getInt" method? I did notice that the app would also crash if I tried to cast the key value explicitly... I had to cast it toString first.
What am I missing?
if you don't want to parse, make sure the score you're putting into the intent with putExtra is an int type, not a string.
Looks like object assosiated with score_format key is a String but you are trying to obtain it as int which is a mistake.

Why cannot save INT to SharedPreferences?

I have a strange problem. I have never had it before. When I try to save int value to my SharedPreference and then restore in other Activity. Value is always 0 even if I save there other value (for example: 1);
private String Number;
private String Profile;
and then saving values (in this case "1") to SharedPreferences in first Activity:
SharedPreferences a = FirstActivity.this.getSharedPreferences("a", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorProfiles = a.edit();
prefsEditorProfiles.putInt(Profile, 1);
prefsEditorProfiles.putInt(Number, 1);
prefsEditorProfiles.commit();
then restore SharedPreferences in other Activity:
SharedPreferences a = SecondActivity.this.getSharedPreferences("a", MODE_PRIVATE);
int ab = a.getInt(Number, 0);
And application shows me 0 instead of 1. My other SharedPreferences works great. I don't know where is the problem.
I'd check what's the value of the Number and Profile variables you declared... you are using their values as keys, so if they have conflicting names, you might be overwriting one setting with the other even though the code looks right.
I'd recommend replacing this:
private String Number;
private String Profile;
With this:
private final String NUMBER = "Number";
private final String PROFILE = "Profile";
And then using those constants when setting/getting your preference value.
Do you ever set a value for
"Number" and "Profile"?
If not then that is your problem -those strings are null.
Please try to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
rather than using
SharedPreferences prefs = getActivity().getSharedPreferences ("PREFS_KEY", 0);
when Storing int in shared preference
I've been trying for a while to use putInt like you but it always give an error.
prefsEditorProfiles.putInt(Number, 1);
by just changing a.putInt to a.putString and retrieving it with a.getString I was able to have the correct value.
so, I guess there should be something wrong with putInt and getInt.
Anyway, try that also to have the correct value you need to continue for application.

Android shared preference selecting image

I have been making a live wallpaper and have finally succeeded so far, but now I would like to let the users choose the background they would like to have that I have in the drawable folder.
I have been trying a few things but so far no luck passing this through.
I have an xml file to read one of two images they can choose from (I figure if I can get one working they all should be the same)
Here's how it reads so far
"DarkBack"
"MediumBackb"
"LightBack"
<string-array name="frontleft_value">
<item>"1"</item>
<item>"2"</item>
<item>"3"</item>
</string-array>bubble
So they choose from either one of three backgrounds
In the activity I have this:
mPrefs = UnderwaterActivity.this.getSharedPreferences(SHARED_PREFS_NAME, 0);
mPrefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(mPrefs, null);
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
myOtherClass.myfrontleftimage = (Integer.parseInt(prefs.getString("front_sub_left_choice", "1")));
}
So this should get me a integer of 1 or 2 depending on which one is click in the settings of the livewallpaper.
The background image is held in a different class but first I have to compare what they clicked, so I tried an if/else statement to no luck at all.
I tried strings but that didn't work so I changed it to int and had some luck but not all.
The if else went like this.
private int chooseImage(){
int theImage = 0;
if(myfrontleftimage == 1){
theImage = R.drawable.image1;
}else if (myfrontleftimage == 2){
theImage = R.drawable.image2;
}else{
theImage = R.drawable.image3;
}
return theImage;
}
Then I put this method into the background image so it can read it, I have a setting java file and implement the engine for shared preferences also but I have a feeling it's in my if else statement, what I want is to get the value of the preference and compare them if they equal to 1, 2, 3 if either one equals one of them then it loads that background image, makes sense in theory but not in practice obviously, any help would be greatly appreciated, if I can figure this one out then I can use it for sprites also that I have in the livewallpaper.
Thanks in advance
EDIT:
I found the issue so far, I put in the pref file this:
<string-array name="livewallpaper_back_names">
<item>Brown</item>
<item>Grey</item>
</string-array>
<string-array name="livewallpaper_back_value">
<item>0x7f020000</item>
<item>0x7f020001</item>
</string-array>
Then in the sharedpreferences file I try to parse the 0x7f020000 (which I want to use to pick the image with) into an int like so
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key)
{
sackNum = Integer.parseInt(prefs.getString("livewallpaper_back", "0x7f020000"));
}
But then I get this error that it can't be done
E/AndroidRuntime(340): java.lang.NumberFormatException: unable to parse '0x7f020000' as integer
So this is where I am stuck at the moment.
I checked the log and the array does get passed through and changes no problem so this is where the issue lies and if anyone can help me parse this thing into an int I would greatly appreciate it.
Thanks again for any help in advance.
You are listening for Shared preference changes, but you do not appear to be setting them.
Set the charedPreferences using and Editor when the user makes a selection.
Then in your activity, read the shared preference in the onCreate() method. That way it will check the savedPreference every time the activity starts.
The code for editing preferences is something like this:
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferences settings = getSharedPreferences("YOURPREFERENCENAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", "MyNameIsBob");
editor.putString("password", "MyPasswordIsEasy");
editor.commit();
}
In your onCreate you would do something like this:
// Get any existing username and password saved
// Restore preferences
SharedPreferences settings = getSharedPreferences("YOURPREFERENCENAME", 0);
user_name = settings.getString("name", "defaultNameValue");
password = settings.getString("password", "defaultPasswordValue");
Ok I figured this out with the help of the test pattern example found here: http://www.codeproject.com/KB/android/AndroidLiveWallpaper.aspx
First I add a third depth to the array.xml like
<string-array name="livewallpaper_back_names">
<item>Brown</item>
<item>Grey</item>
</string-array>
<string-array name="livewallpaper_back_value">
<item>brown</item>
<item>grey</item>
</string-array>
<integer-array name="brownback">
<item>0x7f020000</item>
</integer-array>
<integer-array name="greyback">
<item>0x7f020001</item>
</integer-array>
So now it will read the brown or grey then I add the getResources().getIdentifier to get which array the user picks in the settings menu of the livewallpaper like so:
public void onSharedPreferenceChanged(SharedPreferences prefs, String key)
{
String blah;
sackNum = prefs.getString("livewallpaper_back", "brown");
int pid = getResources().getIdentifier(sackNum + "back", "array", getPackageName());
int backImageArray[] = getResources().getIntArray(pid);
int back = backImageArray[0];
int theBackImage = back;
blah = getString(back);
Log.d(TAG, blah);
}
the int pid gathers the array of either brown or grey by adding back (in the xml) and gets the array which I then put into the backImageArray choosing only the first one because thats the only one, next I change the array into an integer (int back = backImageArray[0];) so it can be read to get the image the user chooses which would be theBackImage or you caould just drop it right into the Bitmap as such
private Bitmap _backgroundImage = BitmapFactory.decodeResource(getResources(),theBackImage);
and presto it gets the image. If anyone has a better way of doing this please add to this but so far this works, Mind you you have to update in the code so it reads it and changes it right away but this is the answer I figured out to get the user to at least choose the image.
Hope it helps someone else out.
Sam

How to use a single intent with multiple buttons

I have an android context menu with various selections and depending on the user selection I want to start an intent. The intent starts the same activity for all the buttons but will contain different String variables depending on the selection. I am currently using a switch, case methodology for my click listener but keep running into 'duplicate local variable' problems as I try to eliminate code repetition! If anyone could provide a-bit of pseudo-code that would be even better!
It's hard to tell without seeing some code, but "duplicate local variables" together with "switch case" makes me think you're declaring a variable in one of the cases with the same name as a variable from another case.
Code within different cases of the same switch is all in the same scope, unless you surround the code within a case with brackets, like this:
switch(VALUE) {
case A: {
String string = "";
}
case B: {
//Same variable name, possible since it's in a different scope now.
String string = "";
}
}
So either use brackets, or simply make sure you're using different variable names across the cases.
you can use intent.putExtra(String name, String value) and push it to the other activity.
Pseudo code:
Button1.value = "X" ;
Button2.value = "Y" ;
onClickListner(View v) {
Intent intent = new Intent() ;
intent.putExtra("ButtonValue",
v.value() ) ;
// extra code goes here...
}
Hope this is what you were looking for..
VInay
I like to use set/getTag(Object), as you can put any type you like into it (as long as you're careful about getting it out again):
button1.setTag(MyClass.STATIC_INT_1);
button2.setTag(MyClass.STATIC_INT_2);
button1.setOnClickListener(Click);
button2.setOnClickListener(Click);
private OnClickListener Click(View v) {
Intent intent = new Intent() ;
intent.putExtra("Value", Integer.parseInt(v.getTag().toString()) ) ;
ยทยทยท
}

Categories

Resources