Could someone maybe tell me what i'm doing wrong? I'm betting im missing one small thing. I've looked on the developer site and i've read some tutorials and i'm just not seeing what i did wrong.
I'm trying to use a ListPreference to decide which sound to play on a button click.
I have this at the top:
public String greensound;
Here's my OnClick code:
case R.id.green:
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);
greensound = prefs.getString("greensound", "gsone");
if (greensound == "gsone") {
mSoundManager.playSound(1);
} else if (greensound == "gstwo") {
mSoundManager.playSound(2);
} else if (greensound == "gsthree") {
mSoundManager.playSound(3);
}
break;
Here's my xml:
<ListPreference
android:title="Geen Button"
android:key="greensound"
android:summary="Select sound for the Green Button"
android:entries="#array/green_list"
android:entryValues="#array/green_list_values"
android:defaultValue="gsone">
</ListPreference>
here's my Settings.java:
package com.my.app;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Settings extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
and here's my array's if that will help at all:
//This is the one I want to display to the user
<string-array name="green_list">
<item>Sound One</item>
<item>Sound Two</item>
<item>Sound Three</item>
<item>Sound Four</item>
<item>Sound Five</item>
</string-array>
<string-array name="green_list_values">
<item>gsone</item>
<item>gstwo</item>
<item>gsthree</item>
<item>gsfour</item>
<item>gsfive</item>
</string-array>
edit: added a logcat that kinda looked possibly related.
08-27 01:52:07.738: WARN/Resources(6846): Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f090000}
08-27 01:52:07.748: WARN/Resources(6846): Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f090000}
08-27 01:52:07.758: WARN/Resources(6846): Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f090000}
DDMS > File Explorer > Data > Data > packageName > SharedPreferences
This is what was in there:
com.my.app_preferences.xml:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="redsound">rsone</string>
<string name="greensound">gsone</string>
</map>
_has_set_default_values.xml:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="_has_set_default_values" value="true" />
</map>
This all really confuses me more because...It looks like greedsound does infact = gsone
so.... I don't understand whats wrong its not even playing the default sound. and yes i've tested
mSoundManager.playSound(1);
mSoundManager.playSound(2);
mSoundManager.playSound(3);
all without the other code and they work great. I'm not sure what's work
greensound.equals("gsone")
I had a similar problem. I changed my '==' comparisons to string.contentsEquals() and things started working. I eventually ended up putting the keys and values into HashMaps.
The only issue I can think of is that your preferences are not getting set before you are running your playSound code. To ensure the settings are loaded include the following code in your onCreate():
/* Loading default preferences the first time application is run */
PreferenceManager.setDefaultValues(getApplicationContext(),
R.xml.filename, false);
Also, check through the DDMS > File Explorer > Data > Data > packageName > SharedPreferences that your preferences are getting set.
When you are using Preference Activity and creating it from xml resource. It automatically creates a SharedPreference file: packageName_preferences (eg. com.my_company.my_app_preferences). Thus to access this you need to use the following code:
SharedPreferences prefs = getSharedPreferences("com.my.app_preferences", MODE_PRIVATE);
And finally remove the following line in the xml:
android:defaultValue="gsone"
Hope this helps.
Related
I am making a simple Android game that displaying a sequence of visual stimuli. I have two activities (Main & Settings). In the setting you will be able to edit the number of stimuli. When I edit the number it does not update at the main activity.
This is into Main activity onCreate
settings = new SettingsActivity();
setNrOfStimuli = settings.getSetNrOfStimuli();
stimuli = new int[setNrOfStimuli];
This is on Main activity
public void onSettingBtnClicked(View view) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
}
This is on Settings activity
public void onBackBtnClicked(View view) {
setNrOfStimuli = Integer.parseInt(inputNrOfStimuliView.getText().toString());
finish();
}
I can transfer the value of number by Intent or getter & setter but the problem is with initialization when it comes back to Main activity from Settings.
I think you should use SharedPreferences to store user's settings. You can go through this tutorial to learn about it.
https://www.javatpoint.com/android-preferences-example
You have to change this in the tutorial's code:
In prefs.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- you do not worry about how this information will be stored, it will be handled
by the android. You have to use those data by getting that data by their key -->
<EditTextPreference
android:key="stimuli_numbers"
android:summary="Please enter Number of stimuli"
android:inputType="numberDecimal"
android:digits="0123456789"
android:title="Number of stimuli" />
</PreferenceScreen>
and in your Main Activity
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
//get the number of stimuli
//stimuli_numbers is the key and 0 is the default value (you can change this according to yours.
setNrOfStimuli = Integer.valueOf(prefs.getString("stimuli_numbers","0");
I would like to check programmatically whether an sd card is installed, and if yes, give the user the choice to switch between external and internal storage.
I have my other static settings organized inside a preferences.xml.
It seems that I have to rewrite all the settings of the xml file in code if I start to work with preferences more dynamically.
Or is there an option to enhance the preferences from the xml with preferences from code which get used just once needed?
Thanks
Add this to manifest for install app on sd card if is possible:
android:installLocation="preferExternal">
To verify is sd card writable and readable use this method:
private boolean isExternalStorageWritable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);}
To get folder of appfiles on sdCard (externalStorageVolumes[0] is primary folder):
File[] externalStorageVolumes =
ContextCompat.getExternalFilesDirs(getApplicationContext(), null);
Oficial documentation
I found out myself, it looks a bit clumsy, but it works.
Once again: My problem is that I have certain setting options pre configured in an xml file as described here:
Preferences with XML
Here is my preferences.xml:
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="#string/download_header">
<SwitchPreferenceCompat
app:key="dl_background"
app:title="#string/background_behaviour"
app:defaultValue="false"/>
<ListPreference
app:title="#string/dl_qual"
app:defaultValue="#string/low_qual"
app:key="dl_qual"
app:entries="#array/dl_qual_arry"
app:entryValues="#array/dl_qual_arry"/>
</PreferenceCategory>
<PreferenceCategory app:title="#string/tc_header">
<SwitchPreferenceCompat
app:key="tc_installed"
app:title="#string/tc_behaviour"
app:defaultValue="false"/>
<ListPreference
app:title="#string/dl_dir_root"
app:key="dl_dir_root"/>
</PreferenceCategory>
</PreferenceScreen>
Here you can define arrays which map to ListPrefrence objects.
Each option list is then populated from a resource xml file holding the actual list entries.
I used this approach for the first ListPreference "dl_qual" above.
This is the resource.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="dl_qual_arry">
<item>Higher quality (128kbps)</item>
<item>Lower quality (64kbps)</item>
</string-array>
</resources>
But then I had the idea to insert a ListPreference where the values of the options list are only known at runtime.
This is my second ListPreference above "dl_dir_root".
I was too lazy to rewrite (and read how to do it in advance) the complete settings activity from code.
So I ended up with this SettingsFragment inside my SettingsActivity:
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
//First, lets check whether we have initialized preferences already
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String selectedDir = prefs.getString("dl_dir_root", "INIT");
setPreferencesFromResource(R.xml.root_preferences, rootKey);
PreferenceScreen root = getPreferenceScreen();
ListPreference dlDirRoot = root.findPreference("dl_dir_root");
CharSequence[] arryValues = BBCWorldServiceDownloaderUtils.getStoragePaths(getContext());
CharSequence[] arryEntrys = BBCWorldServiceDownloaderUtils.getStoragePaths(getContext());
dlDirRoot.setEntries(arryEntrys);
dlDirRoot.setEntryValues(arryValues);
if(selectedDir.equals("INIT")) {
//Initialize value/index
dlDirRoot.setDefaultValue(arryValues[0]);
dlDirRoot.setValueIndex(0);
}
else{
//Position at already selected value/index
dlDirRoot.setDefaultValue(selectedDir);
dlDirRoot.setValue(selectedDir);
dlDirRoot.setValueIndex(dlDirRoot.findIndexOfValue(selectedDir));
}
}
}
The pre defined xml is applied first, then the ListPreference object for "dl_dir_root" is acessed and the options are added:
ListPreference dlDirRoot = root.findPreference("dl_dir_root");
CharSequence[] arryValues = BBCWorldServiceDownloaderUtils.getStoragePaths(getContext());
CharSequence[] arryEntrys = BBCWorldServiceDownloaderUtils.getStoragePaths(getContext());
dlDirRoot.setEntries(arryEntrys);
dlDirRoot.setEntryValues(arryValues);
The rest is checking/keeping state between the calls to the activity.
If anyone knows of a more elegant way, I would be curious.
Best
Matthias
I'm working on a project where I've defined several strings to use on my project.
I want to use a string to be displayed as my subtitle of the page on the toolbar. The reason I'm using strings is because I want my app to be translation supported.
Here is how I use subtitles on the toolbar of my activity:
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setTitle("Title");
ab.setSubtitle("Subtitle");
I want to use a string on java (like #string/helloworld in xml) but I don't know how can I do that.
Can anyone help me?
In your "res" directory, there might be "strings.xml" file. (If you didn't remove it). Add string tags like bellow code snippets.
<string name="title">Title Message</string>
<string name="sub_title">Sub Title Message</string>
And in your java file.
String mStringTitle = getString(R.string.title);
String mStringSubTitle = getString(R.string.sub_title);
You can also use these string resources in your layout XML like follows.
<TextView
android:text="#string/title" />
For more information, please refer to the bellow URLs.
What is the string resource in Android? android_string_resources
How to support multiple locales?
support_different_language //
different-locales
In this case, use R.string.helloworld, because these methods require a resource ID.
This is the code -
R.string.message_failure
Implementation of the above code -
snackbar = Snackbar.make(constraintLayout,R.string.message_failure, Snackbar.LENGTH_SHORT)
//String_file.xml code -
<string name="message_failure">Failure</string>
I'm trying to extend the DialogPreference so I can have a NumberPicker for one of my
preferences. I've been reading:
http://developer.android.com/guide/topics/ui/settings.html#Custom
But I'm hitting an 'Error inflating NumberPickerReference' message. I think I know
why, but I'm not sure how to fix it.
My preferences.xml looks like:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:key="pref_alertsEnabled"
android:title="#string/alert_enable"
android:summary="#string/alert_enable_desc"
android:defaultValue="true" />
<NumberPickerPreference
android:key="perf_Timer"
android:title="#string/timer"
android:negativeButtonText="#android:string/cancel"
android:dialogTitle="#string/timer"
android:summary="#string/timer_desc"
android:dialogMessage="#string/timer_desc"
android:positiveButtonText="#android:string/ok"/>
</PreferenceScreen>
And in my projects src folder I have NumberPickerReference.java. I think the thing I'm missing is how to tell Android where to find NumberPickerReference class.
When preferences.xml is read in, I'm guessing it goes looking for the NumberPickerReference class, but doesn't find it.
Do I need to specify where to find the NumberPickerReference.class ? If yes, how do I do this ?
BTW, the app runs fine if I remove the <NumberPickerReferecnes> item from preferences.xml
Just add the path to that preference:
com.your.package_name.and_path.NumberPickerPreference
E.g.
<com.example.myapp.preferences.NumberPickerPreference
android:key="perf_Timer"
android:title="#string/timer"
android:negativeButtonText="#android:string/cancel"
android:dialogTitle="#string/timer"
android:summary="#string/timer_desc"
android:dialogMessage="#string/timer_desc"
android:positiveButtonText="#android:string/ok"/>
I have never really had to ask a question here. Almost any question I can think of has already been asked and answered. Thus the reason I have never registered.
However, I have finally run across something that I cannot find an answer for. I assume it would be fairly simple.
I am trying to implement in app billing for an android project I am working on. I typically code in C# and use Unity to build the .APK.
However, this time I have to make modifications in Eclipse to some PreferenceScreens.
I have an xml file with some string-arrays set up for a ListPreference under my PreferenceScreen. These ListPreference values are then passed to UnityPlayer for a method. That's all set up.
I am trying to figure out a way to set up in app billing to trigger on selection of one of my list preference, or preference items.
I can probably figure a lot of it out on my own, but I need help with a function to do something pulling from a string value in the list preferences. Does this make sense?
I don't expect to be spoon fed, so if I can just get help on a few lines for this I would appreciate it. Of course I won't complain if anyone wants to write up a little 20 liner function to do it for me.
Thanks in advance,
John
** edit **
Here is the xml from the preferenceScreen I need to address with android In App Billing from Java
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="wallpaper_settings"
android:title="#string/wallpaper_settings" >
<!-- Ad Placeholder -->
<CheckBoxPreference
android:defaultValue="true"
android:key="rotate"
android:summary="#string/rotateSummary"
android:title="#string/rotateTitle" />
<CheckBoxPreference
android:defaultValue="true"
android:key="doubleTap"
android:summary="#string/doubleTapSummary"
android:title="#string/doubleTapTitle" />
<CheckBoxPreference
android:defaultValue="false"
android:key="swipeEmul"
android:summary="#string/simulateSwipeSummary"
android:title="#string/simulateSwipeTitle" />
<ListPreference
android:entryValues="#array/cameraValues"
android:defaultValue="MainCamera"
android:entries="#array/whichCam"
android:summary="#string/cameraSummary"
android:dialogTitle="#string/cameraTitles"
android:title="#string/cameraTitles"
android:key="whichCam"/>
</PreferenceScreen>'
This question is very generic, on an Android application you might do this by creating an Activity, then starting that activity from your preference "onClick" method and then, once the activity starts, you load all your in app billing stuff (showing a progress dialog) and finally present the "buy" dialog. Is this what you need?