Android shared preference selecting image - android

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

Related

Logic behind storing a max number of user favorites to SharedPreferences

I'm wanting to store a number of different user favorites (in this example a max of 5) in sharedpreferences.
The user will be able to add and delete these favorites from within the app.
I'm having trouble getting my head around how to achieve this (I assume some sort of looping is needed).
The gist of what I'm trying to do when a user adds a new favorite:
//init prefs
public static final String PREFS_NAME = "PREFS";
SharedPreferences sharedPreferences = null;
SharedPreferences.Editor sharedPreferencesEditor;
//onCreate
sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
//method called when user adds new favorite
public void addFavorite(String fav) {
//int i = 0;
//int maxFavs = 5;
//check how many favorites are already stored in shared prefs, if any (is it under maxFavs?)
//if over maxFavs, display error
Toast.makeText(getApplicationContext(),"Favorite added",Toast.LENGTH_SHORT).show();
//else continue
//upon finding available favorite 'space' (less than permitted maxFavs), add to favorites in shared prefs
sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString("fav_" + i, fav);
sharedPreferencesEditor.apply();
}
Am I getting the right idea here, or is there a better way to do what I'm intending to do? Hopefully it's clear from the above.
Store favorite count in preferences as an int and read & update it as needed. Also it would be better if you store favorites in preferences as (key : favoritedItemId, value boolean)
Even better: Use a proper local database for situations like this. Preferences is a primitive key value type storage intended for simplier cases like storing a users light mode preference.
Gave up and created a simple database following the example here:
https://inducesmile.com/android/android-sqlite-database-example-tutorial/
Still, if anyone has a solution I'd be interested to see!

How do I access a value from my Preference?

My app contains shared preferences, so in my "Settings-Menu" I can select an item from a list.
In another java file I want to access the value of the selected item.
I failed passing the integer-value through an intent, because the integer is declared in private static, private boolean, and Android Studio tells me, it cannot be refferenced from a static content.
So how can I receive my value from this integer? Thanks in advance :).
Edit: firstival, thanks a lot for that many answers! But as I'm not that much into java I wasn't able to follow your instructions, so I'm going to depict my problem closer.
I'm using androids template "Settings-Activity". In my strings.xml I've got
<string name="Values">Values</string>
<string-array name="pref_example_list_titles">
<item>A</item>
<item>B</item>
<item>C</item>
</string-array>
<string-array name="pref_example_list_values">
<item>01</item>
<item>02</item>
<item>03</item>
</string-array>
In my SettingsActivity.java
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
{...}
In another java file, a fragment "FirstFragment.java I finally want to assign the value from pref_example_list_values to a new integer, called "Vallue2".
So could you please explain me, how I do this, bc I couldn't follow your explainations. Thanks a lot!
As per documentation:
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them.
This means that a single file holds the value, and the preffered way to read and write to it are as following:
SharedPreferences preference = yourContext.getSharedPreferences(yourFileName), Context.MODE_PRIVATE
);
preference.edit().putString(AN_IDENTIFIER, "aValue").apply();
Then to retrieve the value:
SharedPreferences preference = yourContext.getSharedPreferences(yourFileName), Context.MODE_PRIVATE
);
preference.getString(AN_IDENTIFIER,"a default value to use");

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.

How to hold the selected value in the radio button?

I'M doing quiz app. I have set 50 questions and each question contains 4 options(radio group) with pervious and next button. What i need is when select the answer and goes for next question and again he comes to previous question that time what he select perviously that answer should be in selected state.
But user selected value i getText()
How to implement this ? Any one help me..
Thanks in advance..
ImageView previousbtn1 = (ImageView) findViewById(R.id.prv_btn);
previousbtn1.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
if ( j < 1 )
{
Toast.makeText(Question.this, "First Question", Toast.LENGTH_SHORT).show();
}
else
{
--j;
--num;
--m;
TextView txtque = (TextView) findViewById(R.id.que_txt);
txtque.setText("Q" + num + ")" + ques1.get(j));
--k;
btn_practice1.setText(answ1.get((k * 4) + 0));
btn_practice2.setText(answ1.get((k * 4) + 1));
btn_practice3.setText(answ1.get((k * 4) + 2));
btn_practice4.setText(answ1.get((k * 4) + 3));
}
}
});
use SharedPreferences, that will save your values permanently, untill user reinstall (clear data) application. Shared Preferences works like this
// save string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("some_key", string); // here string is the value you want to save
editor.commit();
// restore string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
string = settings.getString("some_key", "");
Basically it looks like your problem is not how to set a radio button active, but the whole concept - so I describe how I'd do it:
The easy way
Use any kind of list or map (preferably hashmap, where the key is the question number and the value is the answer value (1,2 or 3 - simple integers)). Then when you're at question 2 for example, you check if there is alrerady an entry for the key 2, if so you you read out the value and actviate the corresponding radio button (this is by the way done with radio1.setChecked(true)) - if not as soon as the user clicks a radio button the anser is stored in the hash map.
The maybe better way :)
Almost same as before, but instead of simple "ints" as answers you use objects for your answers (maybe also for the questions, then you could store your answers directly in the question) - this is good if the answers / questions are gonna be more complicated then simple "1,2 or 3".
Side note
If the answers of the users should be available AFTER the app is closed, you'd have to store them in either a sqlite db or in shared preferences. I think sqlite is better for this, since these ansers are not really SharedPreferences/Settings, but you surely need a little more effort.
Since you ask for it:
switch(answer){
case 1:
radio1.setChecked(true)
break;
case 2:
radio2.setChecked(true)
break;
case 3:
radio3.setChecked(true)
break;
default:
break;
}

Save and read int - 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.

Categories

Resources