How can I check whether a boolean is true or false from another java class?
menu.class
public class menu extends AppCompatActivity {
TextView textPoints;
Button button2;
public boolean easy;
public void Click(View v) {
if (button2.getText().equals("Svårighetsgrad: Svårt")) {
easy = true;
button2.setText("Svårighetsgrad: Lätt");
}
else {
easy = false;
button2.setText("Svårighetsgrad: Svårt");
GameActivity.class
menu m = new menu();
if (m.easy == true) {
myImageView.setVisibility(View.VISIBLE);
newAndroid();
points = getPoints() - 1;
text1.setText("Poäng: " + points);
}
else {
myImageView.setVisibility(View.VISIBLE);
newAndroid();
points = getPoints() - 5;
text1.setText("Poäng: " + points);
you are developing for Android right?
you should probably use SharedPreference in this case (it would be easier).
use this code to save value:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("EASY", easy);
editor.commit();
and this code to get the value:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean score = sharedPref.getBoolean("EASY", defaultValue);
If you're just trying to get whether or not a value is true or false, you could either make your boolean public or you could make a getter method.
public boolean getBooleanValue(){
return booleanYouWant;
}
You need a reference on that class in order to do that. The common way of communicating would be the observer pattern for java. Delegation is also a possibility - which will create a double reference, but in Java you usually want to take observer pattern, as it is implemented by default.
You can also have some kind of singleton pattern, to have a global reference of an instance.
Related
In my app I save some user information (i.e. name, weight, height) as key-value-pairs using SharedPreferences.
These information are used in several activities. So I thought, instead of implementing the whole procedure for reading/writing to the SharedPreferences in each activity, I also could implement a class "UserData" and define several static methods. So when I need some user information or want to save them I only use methods of the class "UserData" and this class handles all the stuff in background.
So I did the following things:
class UserData contains a private Map<String,?>
this map is filled by the getAll()-Method of SharedPreferences
initialization is triggerd in the onCreate()-Method in each activity
providing the values (for each possible type) to a defined key is done by the getValue(String key)-Method
writing (new) information should be done by setter methods
to write back to shared preferences, there is a save function
But now I have a lot of questions:
getAll() method
I expect, that getAll() will read all key-value-pairs from the SharedPreferences. So I would expect, that after initialization data will contain (String,String)-pairs (i.e. "name";"Max") as well as (String,Integer)-pairs (i.e. "weight",85). Am I right?
getting the values
Is the way, how I return the values in getValue(String key) correct? How can I get the value type from such a Map<String,?> or Map.Entry<String,?> definition?
adding Entries to the map
I have no idea how to overwrite or write new entries to data. One Idea was, to create a set-method for each type (i.e. String, Integer) I can save in SharedPreferences, create an Entry within this method and then calling an add-method. But how should this looks like?
saving
Will this saving fuction work properly? I'm not realy sure.
Or is this a total stupid approach?
Thanks for your support.
This is my UserData-class
public class UserData {
static private boolean isInit = false;
static private Map<String,?> data = new HashMap<>();
static void initialize(Context context){
if(UserData.isInit){
return;
}
if(context==null){
return;
}
// read data from memory
SharedPreferences pref = context.getSharedPreferences(context.getString(R.string.app_userdata),Context.MODE_PRIVATE);
UserData.data = pref.getAll();
Log.v(TAG,"loaded " + UserData.data.size() +" key-value-pairs into map");
UserData.isInit=true;
}
static void reinitialize(Context context){
UserData.isInit=false;
UserData.initialize(context);
}
static <T> T getValue(String key){
Object value = UserData.data.get(key);
if(value instanceof T){
return (T)value;
}else{
return null;
}
}
static <T> T getValue(String key,T retErr){
T value = getValue(key);
if(value!=null){
return value;
}else{
return retErr;
}
}
static void setString(String key, String str){
}
static void setInteger(String key, Integer i){
}
static private void addElement(Map.Entry<String,?> element){
}
static void save(Context context){
SharedPreferences pref = context.getSharedPreferences(context.getString(R.string.app_userdata),Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
for(Map.Entry<String,?> pair : UserData.data.entrySet()){
Object value = pair.getValue();
if(value instanceof String){
editor.putString(pair.getKey(),value.toString());
}else if(value instanceof Integer){
editor.putInt(pair.getKey(),(Integer)value);
}else if(value instanceof Float){
editor.putFloat(pair.getKey(),(Float) value);
}else if(value instanceof Boolean){
editor.putBoolean(pair.getKey(),(Boolean) value);
}
}
editor.apply();
}
}
Sample Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UserData.initialize(getApplicationContext());
}
}
i think you are trying to recreate the wheel. if you want to create a custom class for saving, adding, or even editing shared pref, that fine. Shared pref is a map, for you to use another map, just seems backwards to me.
SharedPreferences pref = getApplicationContext().getSharedPreferences("sharedPreferences", 0); // 0 - for private mode
Storing data into Shared pref.
Editor editor = pref.edit();
editor.putBoolean("name", "bill");
editor.commit();
To get the name
String name = pref.getString("name", null); //value is null if the key 'name' doesnt exist. you can also put in any string value here
remove data from shared pref
editor.remove("name");
editor.commit();
to remove everything..
editor.clear();
editor.commit();
If you want to create a class that does this, thats fine, but dont add the data into a map.
I want to disable the upload button for one day for after uploading firebase photo. i tried these codes, countdown works incorrectly when I change activity.
SharedPreferences prefs = getSharedPreferences("time", Context.MODE_PRIVATE);
long currentTime = new Date().getTime();
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("time", currentTime);
editor.apply();
dwn.setEnabled(false);
SharedPreferences prefs = getSharedPreferences("time", Context.MODE_PRIVATE);
long previousTime = prefs.getLong("time", 0);
long currentTime = new Date().getTime();
if (currentTime - previousTime > 60*1000){
dwn.setEnabled(true);
} else {
dwn.setEnabled(false);
new CountDownTimer(currentTime - previousTime, 1000) {
public void onTick(long millisUntilFinished) {
dwn.setText("fdfjhsn" + millisUntilFinished / 1000);
}
public void onFinish() {
dwn.setEnabled(true);
}
}.start();
This might be more than you were looking for, but I would extract the decision making to a separate class. Consider the following:
interface UserUploadHelper {
void userUploadedImage();
boolean canUserUploadImages();
}
We can have an implementation of this, backed by SharedPreferences. This object can then be injected into wherever we need it:
class SharedPreferencesUserUploadHelper implements UserUploadHelper {
private static final String LAST_IMAGE_UPLOAD_TIME = "last.user.upload.time";
private static final String PREFS_NAME = "user.upload";
private static final String PREFS_MODE = Context.MODE_PRIVATE;
private static final String MILLIS_IN_DAY = 24 * 60 * 60 * 1000;
private final SharedPreferences sharedPreferences;
SharedPreferencesUserUploadHelper(Context context) {
sharedPreferences = context.getSharedPreferences(PREFS_NAME, PREFS_MODE);
}
#Override
void userUploadedImage() {
sharedPreferences.edit().putLong(
LAST_IMAGE_UPLOAD_TIME,
new Date().getTime()
).apply();
}
#Override
boolean canUserUploadImages() {
long lastUploadTime = sharedPreferences.getLong(LAST_IMAGE_UPLOAD_TIME, 0L);
long now = new Date().getTime();
return lastUploatTime - now > MILLIS_IN_DAY;
}
}
Inside your upload code, when the code finishes uploading, you can call userUploadedImage()
Inside your activity code, you can check whether the button should be enabled with canUserUploadImages().
Doing this lets you change how you store that value and calculate the timeout without changing your firebase logic or your view logic.
You can inject this into a class using a tool like Dagger, or simply by creating an instance of it via its constructor. If you want to hide the concrete SharedPreferencesUserUploadHelper implementation, you can use a factory! This is good when you might decide to change how this class is implemented later.
public UserUploadHelperFactory {
public UserUploadHelper create(Context context) {
return new SharedPreferencesUploadHelper();
}
}
If we wanted to go a step further, we would actually break our original interface into two different interfaces, one for each method, since each method has different interested parties, and, for example, the view shouldn't be able to call userUploadedImage (Which makes that original interface a slight violation of the Interface Segregation Principle!)
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);
}
I would like to replace the SharedPreferences in my Android app by a class called SecurePreferences (which is a modified version of this). How can I flexibly call the methods of one of their instances?
Example:
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SecurePreferences securePref = new SecurePreferences(sharedPref, "", key, true);
...
public void loadSettings() {
Object pref;
if (Settings.usingEncryptedPreferences) {
pref = securePref;
} else {
pref = sharedPref;
}
boolean musicEnabled = pref.getBoolean("musicEnabled", true);
boolean soundEnabled = pref.getBoolean("soundEnabled", true);
boolean vibrationEnabled = pref.getBoolean("vibrationEnabled", true);
// and so on
}
Both SharedPreferences and SecurePreferences have a getBoolean method. But Android Studio tells me Cannot resolve method 'getBoolean(Java.lang.String, boolean)'.
The error is caused by the type of your pref variable. Object class does not have getBoolean method. There can be numerous solutions. For example: If the SecurePreferences extends SharedPreferences interface (or implements it), then the type of pref variable should be SharedPreferences.
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();