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";
Related
In my Java app, I have a number of saved values and settings that I would like to get as soon as the application starts. All these values are supposed to be stored in a singleton.
For example, I have a JDialog, where I save a path to my file using this:
AppSingleton appSingleton = AppSingleton.getInstance( );
private Preferences prefs;
private void btnSetPanelSetNavdataActionPerformed(java.awt.event.ActionEvent evt) {
appSingleton.setNavdataPath(txtNavdataPath.getText());
prefs = Preferences.userRoot().node(this.getClass().getName());
prefs.put("NAVDATA_PATH", txtNavdataPath.getText());
dispose();
}
I am checking and the value is saved.
This is my singleton:
public class AppSingleton
{
private static AppSingleton instance = null;
private String navdataPath = "";
private AppSingleton()
{
}
public static AppSingleton getInstance()
{
if(instance == null)
{
instance = new AppSingleton();
}
return instance;
}
public String getNavdataPath() {
return navdataPath;
}
public void setNavdataPath(String navdataPath) {
this.navdataPath = navdataPath;
}
public void initDefaultValues()
{
Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
this.navdataPath = prefs.get("NAVDATA_PATH","");
System.out.printf("CHECK DEFAULT: %s",this.navdataPath);
}
}
I am trying to get the saved values from the main() method in the class that initializes the JFrame:
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run() {
new IGAMainFrame().setVisible(true);
/* HERE!!! */
AppSingleton appSingleton = AppSingleton.getInstance();
appSingleton.initDefaultValues();
}
});
}
But the values are not initialized from the Preference class. "CHECK DEFAULT" shows empty string. I do not understand why and whether there is a better practice of restoring all saved values when a GUI application starts.
Thanks!
Change the line prefs = Preferences.userRoot().node(this.getClass().getName()); inside btnSetPanelSetNavdataActionPerformed to prefs = Preferences.userRoot().node(Appsingleton.class.getName()); Inside button click method, this.getClass() is not AppSingleton
here this is my static method
public static void messageHandler(final MessageMO messageMo) {
UIHandler = new Handler(Looper.getMainLooper());
UIHandler.post(new Runnable() {
public void run() {
// SharedPreferences sharedPreferences1;
Log.e("messageHandler", messageMo.getEventTitle());
ChatMO chatMO = new ChatMO();
chatMO.setMessage(messageMo.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMo.getfromUserName());
chatMO.setDate(messageMo.getDate());
chatMO.setEvent_id(messageMo.getEventId());
Log.e("handler", "eventid" + chatMO.getEvent_id());
Log.e("handler", "date" + chatMO.getDate());
listChatMessageObjectses.add(chatMO);
Log.e("handler", "listmessage" + listChatMessageObjectses);
}
});
}
here i have to store the value of listChatMessageObjects into shared preferences how to do it thanks in advance
You will need to change the method signature to receive a Context:
public static void messageHandler(final Context context, final MessageMO messageMo)
And then open the preferences using Context.getSharedPreferences.
PS: listChatMessageObjects sounds like a lot of data.. consider to use a ContentProvider for storing a lot of records.
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();
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
}
}
}
Activity 1st..
Here this is my first activity to add data
preferences=PreferenceManager.getDefaultSharedPreferences(context);
preferences = getPreferences(MODE_PRIVATE);
editor = preferences.edit();
editor.putString("userid",et_username.getText().toString());//adduserid
editor.putString("password",et_password.getText().toString());//add password
editor.commit();
Activity 2nd
This is my second activity to retrieve data.
String userName=preferences.getString("userid","");
String password=preferences.getString("password","");
Log.d("user : second", ""+preferences.getString("userid",""));
Log.d("password : second", ""+preferences.getString("password",""));
Here Log is not displayed because of null value.
Check your preferences object (probably is null). That might be the problem, as the other String variables are never null, the can be empty string ("").
Are you missing the initialization of preferences in the second Activity just in this example?
String userName=preferences.getString("userid");
String password=preferences.getString("password");
Log.d("user : second", ""+userName);
Log.d("password : second", ""+password);
Could you please try this way.
In both activities just use this to get the SharedPreferences object:
SharedPreferences prefs = getSharedPreferences("PREFS", Context.MODE_PRIVATE);
It may be that you attempt to access different preferences files from different Activities.
Or just use
PreferenceManager.getDefaultSharedPreferences(this);
i just store the one integer value you must more then one value in it..
PreferenceConnector.writeInteger(home.this, PreferenceConnector.com_id, homeComp_id);
below the preferenceConnector class to be use in it...
public class PreferenceConnector {
public static final String PREF_NAME = "Shared Preference";
public static final int MODE = Context.MODE_PRIVATE;
public static final String com_id = "com_id";
public static void writeBoolean(Context context, String key, boolean value) {
getEditor(context).putBoolean(key, value).commit();
}
public static boolean readBoolean(Context context, String key, boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, MODE);
}
public static Editor getEditor(Context context) {
return getPreferences(context).edit();
}
}
and then u also use the share preference value to other activity like below...
int Pref = PreferenceConnector.readInteger(mainpage.this, PreferenceConnector.com_id, 0);
hope above code to be useful...