Check if checkBoxPreference is "true" - java

I have Preferences with 10 checkBoxPreferences and I need to list how much it checked, eg 6/10 any idea?
I tried something, but absolutely failed.

I believe you're talking about the CheckBoxPreference class in Android, in which case you need to register a SharedPreferences.OnSharedPreferenceChangeListener and implement this method:
private static final String CHECKBOX_KEY = "your_checkboxpreference_key";
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(CHECKBOX_KEY)) {
if(sharedPreferences.getBoolean(key, true)) {
//Your code here
}
}
}

Related

How to image button to SharedPreferences and save it

Hello guys i have a question.
I have a button with 2 options like checked and unchecked for girl and i have same for boys. In my fragment i need to select one and save it in SharedPreferences.
i have this for configure buttons:
private void setSexButtons() {
sexButtonBoy.setOnClickListener(view -> {
sexButtonBoy.setSelected(true);
sexButtonBoy.setScaleX(1.4f);
sexButtonBoy.setScaleX(1.4f);
sexButtonGirl.setSelected(false);
sexButtonGirl.setScaleY(1.0f);
sexButtonGirl.setScaleX(1.0f);
Settings.setSelectedIem(true);
});
sexButtonGirl.setOnClickListener(view -> {
sexButtonBoy.setSelected(false);
sexButtonGirl.setSelected(true);
sexButtonGirl.setScaleX(1.4f);
sexButtonGirl.setScaleX(1.4f);
sexButtonBoy.setScaleY(1.0f);
sexButtonBoy.setScaleX(1.0f);
Settings.setSelectedIem(true);
});
}
and i also have a method to save - but i think i do something bad becouse this not work
public static void setSelectedIem(boolean selectedIem) {
getPreferences().edit()
.putBoolean(SELECTED_SEX, selectedIem)
.apply();
}
private static final String SELECTED_SEX = "selectedSex";
Please give me any advice how to do this good.
Sorry i miss it here is it:
privated SharedPreferences sharedPreferences;
and in onCreate
sharedPreferences = getSharedPreferences("me.fast.app", MODE_PRIVATE);
and here is main method:
private static SharedPreferences getPreferences() {
return ApplicationFast.sharedPreferences;
}
Updated with new method
public static boolean isSelectedItem(){
return getPreferences().getBoolean(SELECTED_SEX, false);
}
I think your problem is saving a boolean, because for both sexes you are saving "true".
You should do this:
private void setSexButtons() {
//If you want to recover the settings do this:
sexButtonBoy.setSelected(Settings.isSelected());
sexButtonGirl.setSelected(!Settings.isSelected());
sexButtonBoy.setOnClickListener(view -> {
sexButtonBoy.setSelected(true);
sexButtonBoy.setScaleX(1.4f);
sexButtonBoy.setScaleX(1.4f);
sexButtonGirl.setSelected(false);
sexButtonGirl.setScaleY(1.0f);
sexButtonGirl.setScaleX(1.0f);
Settings.setSelectedIem(true);
});
sexButtonGirl.setOnClickListener(view -> {
sexButtonBoy.setSelected(false);
sexButtonGirl.setSelected(true);
sexButtonGirl.setScaleX(1.4f);
sexButtonGirl.setScaleX(1.4f);
sexButtonBoy.setScaleY(1.0f);
sexButtonBoy.setScaleX(1.0f);
Settings.setSelectedIem(false);
});
}
And then:
public static void setSelectedIem(boolean selectedIem) {
getPreferences().edit()
.putBoolean(IS_BOY, selectedIem)
.apply();
}
private static final String IS_BOY = "isboy";

How to initialize preference value once in LibGDX?

I'm using preferences to save the sound settings in my game as a boolean value. However, when I first start the game, the boolean initializes to false (sound off), because I'm not initializing it elsewhere. I could initialize it to true in the create method, but then the game would just start with sounds on every time you start the game, and that would just defeat the purpose of preferences.
Otherwise it works fine, it's just that I want the boolean to initialize to true the first time you start the game and not every time you restart it.
Is there a way to do this with preferences or do I have to use some other kind of saving method?
Note: this is a desktop application
public Preferences getPreferences() {
if (preferences == null) {
preferences = Gdx.app.getPreferences("myPrefs");
}
return preferences;
}
private void generatePreferences() {
getPreferences().clear();
getPreferences().putBoolean("soundEnabled", true).flush();
getPreferences().putBoolean("notFirstLaunch", true).flush();
}
public void loadPreferences() {
if (!getPreferences().getBoolean("notFirstLaunch")) {
generatePreferences();
} else {
//read the prefs and do your stuff
}
}
I would suggest you a slightly different approach:
Firstly, I think that the perfect place to initialize prefs is create method of the main game class (the one that extends Game):
public void create () {
Prefs.initPrefs();
....other initialization....
}
Then, initPrefs method looks like:
private static final String MUSIC_ON = "music_on";
private static final String LANG = "lang";
public static void initPrefs() {
boolean needChange = false;
if (!pref.contains(MUSIC_ON)) {
pref.putBoolean(MUSIC_ON, true);
needChange = true;
}
//if no lang - select system default
if (!pref.contains(LANG)) {
String language = Locale.getDefault().getLanguage();
pref.putString(LANG, language);
needChange = true;
}
if (needChange) {
pref.flush();
}
}
And finally to toggle the music:
public static boolean isMusicOn() {
return pref.getBoolean(MUSIC_ON);
}
public static void toggleMusic() {
pref.putBoolean(MUSIC_ON, !isMusicOn());
pref.flush();
}
I know this is a few years old now but just in case anyone else was wondering.
I think what you need to do is add a default value to your getBoolean() method without calling flush().
In my game i have a method called isSoundOn() which i call when my sound button is created. The very first time you start your game after installing it, you probably wont have saved a preference which means that the method below has to default to something. if you add true to the getBoolean method then your game should initialize to true.
public boolean isSoundOn() {
return preferences.getBoolean("soundOn", true);
}

Android - Set variable once and use everywhere in app

Basically my question is I want to set lets say a string to A or B that is chosen by the user on the first screen. And then have this string variable be saved to be used on other actives else where in the app. I have see the posts and many like in Android global variable.
But the variable needs to be set and the gotten on each activity the variable isn't saved, once and then can be used everywhere?
How could this be done?
I hope i have explained this well enough, as my question differs from the one above.
The variable is not final it can be changed on the first activity but then I want to use it on the following activities, with out having to pass it with intent to each one.
Thanks for the help in advance.
You can use a public class with static String variable or passing the variable to another Activity with putExtra method.
Example :
public class Global {
public static final String DEVELOPER_KEY;
public static final String PLAYLIST_ID;
}
I have made one class for same purpose :
public class Constant {
public static int NUMBER_OF_TILES;
public static String setTilesId[] = {};
public static String TilesDesc[] = {};
public static String Image[] = {};
public static String TilesName;
public static int numberofbox = 0;
public static boolean isLogedIn = false;
public static String TilesSize = null;
public static boolean from_activity = true;
public static String URL_FOR_PRODUCT_ACTIVITY;
}
Now i can use this variables from anywhere in my APP.
You can put your variable in SharedPreferences. As it exactly matches you requirement.
You can put your variable in first screen and use it anywhere in your application. Also it is not final, you can change whenever you want it will just overwrite existing value of variable.
And MOST important thing is it will be preserved even after application is closed.
So whenever user starts your application next time you can use that variable.
A.java code:
package p2;
public class A{
public static String abc;
}
After declaring the static string in class A use it anywhere in the package using the class name as it is static so value will remain whatever you update it to.
B.java code :
package p1;
public class B{
public void methodTest(){
String s = A.abc;
}
}
Make your string public static
Ex:public static String myvar="hey"//This will be available across all classes
Instead of using static variable You can simply use Shared Preferences because after some time when your application is in background your static value become free automatically by garbage collector and become null
public void setString(Context context, String value) {
SharedPreferences prefs = context.getSharedPreferences("setString",
0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("getString", value);
editor.commit();
}
public String getString(Context context) {
SharedPreferences prefs = context.getSharedPreferences("setString",
0);
String value = prefs.getString("getString", null);
return value;
}
You can also usw SharedPreferences:
SharedPreferences sets =getSharedPreferences(Choose_a_name, 0);
SharedPreferences.Editor editor=sets.edit();
editor.put string("from user", your string);
editor.commit();
And in your other activities you can retrieve, change and save them again. In that way, you can provide the customized data from the user over the activity lifecycle. Even If your task is completely killed, your data is available on the next launch.
To retrieve the data from another activity:
SharedPreferences sets = getSharedPreferences(yourPrefName,0);
String your string = sets.get string("from user", default value);
I want to give you alternative ideas comparing to intents or static classes. Hope it helps :)
class SharedPref
{
public void setString(Context context, String value) {
SharedPreferences prefs = context.getSharedPreferences("setString",
0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("getString", value);
editor.commit();
}
public String getString(Context context) {
SharedPreferences prefs = context.getSharedPreferences("setString",
0);
String value = prefs.getString("getString", null);
return value;
}
}
and use this class like
SharePref pref=new SharedPref();
pref.setString("Hellooo");
String value=pref.getString();

Intellij IDEA plugin - PersistentStateComponent loadState not called

I am trying to develop a plugin for Intellij IDEA, I am working with SDK 129.451.
The issue I have is that I can't persist the user data like some list items he can input in the plugin and have the data back after the IDE restarts..
I am using PersistentStateComponent to persist the data, the getState() method seems to be called but the loadState() method doesn't.
Here is a sample class that extends PersistentStateComponent:
#State(name = "Test", storages = {#Storage(file = StoragePathMacros.APP_CONFIG+"/other.xml"
)})
public class Test implements PersistentStateComponent<Element> {
String ceva;
public Test() {
ceva = "sad";
System.out.println("constr");
}
public String getCeva() {
return ceva;
}
public void setCeva(String ceva) {
this.ceva = ceva;
}
public void loadState(Element state) {
System.out.println("cstate load");
ceva = (String) state.getContent().get(0);
}
public Element getState() {
System.out.println("cstate retu");
Element configurationsElement = new Element("testtt");
configurationsElement.addContent(ceva);
return configurationsElement;
}
}
Also I added this class in plugin.xml here:
<extensions defaultExtensionNs="com.intellij">
<applicationService serviceImplementation="ro.catalin.prata.testflightuploader.controller.Test"/>
<!-- Add your extensions here -->
<toolWindow id="TF Uploader" secondary="true" icon="/general/add.png" anchor="right"
factoryClass="ro.catalin.prata.testflightuploader.view.TFUploader">
</toolWindow>
</extensions>
And I also have a tool window class:
public class TFUploader implements ToolWindowFactory {
private JButton buttonAction;
private ToolWindow myToolWindow;
final Test test = ServiceManager.getService(Test.class);
public TFUploader() {
// I assume it should print the saved string but it doesn't
System.out.println(test.getCeva());
buttonAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// if I click a button I am setting some new value to the string I want to save
test.setCeva(test.getCeva() + "-dddddd+");
}
});
}
Ok so, if I close the app or minimize it, the getState method gets called as I expected.. but when I open the app, the loadState method doesn't get called.. can somebody help me how I can solve this?
I already read this but it doesn't seem to help me to much. Also I want to use PersistentStateComponent as I want to save objects more complex than a simple String.
Thank you in advance!
Ok, I made it! :)
I don't know exactly what the issue was but I changed the Test class to this:
#State(
name = "Test", storages = {
#Storage(
id = "other",
file = "$APP_CONFIG$/testpersist.xml")
})
public class Test implements PersistentStateComponent<Test> {
String ceva;
public Test() {
ceva = "sad";
System.out.println("constr");
}
public String getCeva() {
return ceva;
}
public void setCeva(String ceva) {
this.ceva = ceva;
}
public void loadState(Test state) {
System.out.println("cstate load");
XmlSerializerUtil.copyBean(state, this);
}
public Test getState() {
System.out.println("cstate retu");
return this;
}
}
And in the TFUploader I changed the way I loaded the Test class to this:
final Test test = ServiceManager.getService(Test.class);
I hope it helps others..
I have already commented here but will say again that in my case loadState(MyService state) wasn't called because of lack of getter and setter for stateValue from this example:
class MyService implements PersistentStateComponent<MyService> {
public String stateValue;
public MyService getState() {
return this;
}
public void loadState(MyService state) {
XmlSerializerUtil.copyBean(state, this);
}
}
In my case I was getting a NullPointerException even before loadState was getting called. Similar to your code above I used an Element class as the state class. I had a constructor with some parameters in Element class. This was the problem as the framework could not create an instance of my state class. I tried to add a blank constructor without any parameters. This worked.

GWT Editors - how to add N sub-editors of the same type based on a Collection

I have an object, Supply, that can either be an ElecSupply or GasSupply (see related question).
Regardless of which subclass is being edited, they all have a list of BillingPeriods.
I now need to instantiate N number of BillingPeriodEditors based on the contents of that list, and am pretty baffled as to how I should do it.
I am using GWTP. Here is the code of the SupplyEditor I have just got working:
public class SupplyEditor extends Composite implements ValueAwareEditor<Supply>
{
private static SupplyEditorUiBinder uiBinder = GWT.create(SupplyEditorUiBinder.class);
interface SupplyEditorUiBinder extends UiBinder<Widget, SupplyEditor>
{
}
#Ignore
final ElecSupplyEditor elecSupplyEditor = new ElecSupplyEditor();
#Path("")
final AbstractSubTypeEditor<Supply, ElecSupply, ElecSupplyEditor> elecSupplyEditorWrapper = new AbstractSubTypeEditor<Supply, ElecSupply, ElecSupplyEditor>(
elecSupplyEditor)
{
#Override
public void setValue(final Supply value)
{
setValue(value, value instanceof ElecSupply);
if(!(value instanceof ElecSupply))
{
showGasFields();
}
else
{
showElecFields();
}
}
};
#Ignore
final GasSupplyEditor gasSupplyEditor = new GasSupplyEditor();
#Path("")
final AbstractSubTypeEditor<Supply, GasSupply, GasSupplyEditor> gasSupplyEditorWrapper = new AbstractSubTypeEditor<Supply, GasSupply, GasSupplyEditor>(
gasSupplyEditor)
{
#Override
public void setValue(final Supply value)
{
setValue(value, value instanceof GasSupply);
if(!(value instanceof GasSupply))
{
showElecFields();
}
else
{
showGasFields();
}
}
};
#UiField
Panel elecPanel, gasPanel, unitSection;
public SupplyEditor()
{
initWidget(uiBinder.createAndBindUi(this));
gasPanel.add(gasSupplyEditor);
elecPanel.add(elecSupplyEditor);
}
// functions to show and hide depending on which type...
#Override
public void setValue(Supply value)
{
if(value instanceof ElecSupply)
{
showElecFields();
}
else if(value instanceof GasSupply)
{
showGasFields();
}
else
{
showNeither();
}
}
}
Now, as the list of BillingPeriods is a part of any Supply, I presume the logic for this should be in the SupplyEditor.
I got some really good help on the thread How to access PresenterWidget fields when added dynamically, but that was before I had implemented the Editor Framework at all, so I think the logic is in the wrong places.
Any help greatly appreciated. I can post more code (Presenter and View) but I didn't want to make it too hard to read and all they do is get the Supply from the datastore and call edit() on the View.
I have had a look at some examples of ListEditor but I don't really get it!
You need a ListEditor
It depends of how you want to present them in your actual view, but the same idea apply:
public class BillingPeriodListEditor implements isEditor<ListEditor<BillingPeriod,BillingPeriodEditor>>, HasRequestContext{
private class BillingPeriodEditorSource extends EditorSource<BillingPeriodEditor>{
#Override
public EmailsItemEditor create(final int index) {
// called each time u add or retrive new object on the list
// of the #ManyToOne or #ManyToMany
}
#Override
public void dispose(EmailsItemEditor subEditor) {
// called each time you remove the object from the list
}
#Override
public void setIndex(EmailsItemEditor editor, int index) {
// i would suggest track the index of the subeditor.
}
}
private ListEditor<BillingPeriod, BillingPeriodEditor> listEditor = ListEditor.of(new BillingPeriodEditorSource ());
// on add new one ...
// apply or request factory
// you must implement the HasRequestContext to
// call the create.(Proxy.class)
public void createNewBillingPeriod(){
// create a new one then add to the list
listEditor.getList().add(...)
}
}
public class BillingPeriodEditor implements Editor<BillingPeriod>{
// edit you BillingPeriod object
}
Then in you actual editor edit as is in the path Example getBillingPeriods();
BillingPeriodListEditor billingPeriods = new BillingPeriodListEditor ();
// latter on the clickhandler
billingPeriods.createNewBillingPeriod()
You are done now.

Categories