Android global variable dynamic value - android

Hello all i want to make use of a global integer variable that i shall be incrementing in 7 different activities according to the users right or wrong choise. The problem is that i every time i implement the variable in each different activity , the value is not kept. Instead i get the default value of the variable. What i want is that every increment i make to the variable is saved , when i use it again in the next variable. Any help appreciated.
I have tried and failed :
public class MyApplication extends Application {
private int grade=0;
public int setGrade(int grade) {
this.grade = grade;
}
public int getGrade() {
return grade;
}
}
public class lessonOnePhoto extends Activity {
private int grade = ((MyApplication) this.getApplication()).getGrade();
if (rbtn[0].getText().toString().equals("Boy")) {
grade++;
}
else {
Toast.makeText(getApplicationContext(),"Wrong Choise",Toast.LENGHT_SHORT).show();
}
}

The grade you are incrementing is local and private to your activity. It is also a primitive, rather than an object, so grade = .getGrade() will set the local variable to the same value as the global value, it is not some kind of reference.
Instead, do something like this:
MyApplication myApplication = ((MyApplication) this.getApplication());
myApplication.setGrade(myApplication.getGrade()++);
Or implement increment decrement methods.
public class MyApplication extends Application {
private int grade=0;
public int setGrade(int grade) {
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void incrementGrade() {
grade++;
}
public void decrementGrade() {
grade--;
}

you have to increment the original application value .. not the copy to maintain the variable in between the activities
if (rbtn[0].getText().toString().equals("Boy")) {
grade++;
}
change to
if (rbtn[0].getText().toString().equals("Boy")) {
((MyApplication) this.getApplication()).setGrade(grade++)
}

You can add one method in application class to increment value
public class MyApplication extends Application {
private int grade=0;
public int incrementGrade() {
this.grade = grade + 1;
}
public int setGrade(int grade) {
this.grade = grade;
}
public int getGrade() {
return grade;
}
}
and increment when needed
MyApplication myApplication = ((MyApplication) this.getApplication());
myApplication.incrementGrade();
OR ================
Make that grade static and increment by accessing it in static way
public static int grade = 0;
access it lie this
MyApplication.grade ++;

You can get the result from the activities where the user enters the response and handle it from a MainActivity that manages all the responses.
Another option to avoid storing information in the Application class could be to have a Singleton with a Shared Instance that stores the global variables. However, the use of singletons is considered a bad practice in some cases.

Related

Android - My Global Variable values return null after switching Application

I am Using GlobalVariable file to hold data during my entire application, but what happens is it returns null value if i switch to another application and returns back.
below is my code :
In Manifest :
<application
..
android:name=".MyApplication" >
For Class of global variables :
public class MyApplication extends Application {
public int rowId = 0;
}
inside the activities
int mRowId = ((MyApplication) getApplicationContext()).rowId;
you need to make it static and final but use it with getters and setters only.
Something like the following
public class MyApplication extends Application {
public final static int rowId = 0;
dont forget your initializing and setters and getters please :
int rowId;
public int getRowId() {
return rowId;
}
public void setRowId(int rowId) {
this.rowId = rowId;
}
to set the values from outside the class, something like:
MyApplication.rowId = //whatever returns int
to get the values from outside/inside the class, something like:
int TempInt = MyApplication.rowId; // TempInt will have the value of rowId
check What are setters and getters :
https://dzone.com/articles/why-should-i-write-getters-and-setters

A listener for changing variable in android

I have a variable in my class , I want when that variable changed , I do an action in another class .
in fact I want a listener for changing variable in android (my variable may change every minute)
public class Connect {
public static boolean myBoolean;
//some actions do and myBoolean change
}
public class Selection extends Activity implements OnMenuItemClickListener{
//I want a thing like listener here ,when myboolean changed I do an action (myboolean may change every minute)
}
It's not possible directly. However, you can make your field private, add getters and setters, and create a method of adding listeners (this is called the Observer pattern):
interface ConnectionBooleanChangedListener {
public void OnMyBooleanChanged();
}
public class Connect {
private static boolean myBoolean;
private static List<ConnectionBooleanChangedListener> listeners = new ArrayList<ConnectionBooleanChangedListener>();
public static boolean getMyBoolean() { return myBoolean; }
public static void setMyBoolean(boolean value) {
myBoolean = value;
for (ConnectionBooleanChangedListener l : listeners) {
l.OnMyBooleanChanged();
}
}
public static void addMyBooleanListener(ConnectionBooleanChangedListener l) {
listeners.add(l);
}
}
Then, wherever you want to listen to changes of the boolean, you can register a listener:
Connect.addMyBooleanListener(new ConnectionBooleanChangedListener() {
#Override
public void OnMyBooleanChanged() {
// do something
}
});
Adding a method to remove listeners is left as an exercise. Obviously, for this to work, you need to make sure that myBoolean is only changed via setMyBoolean, even inside of Connect.

how to pass, from a class to another, the name of a variable (NOT the value)

I need to pass name of a variable created in Class A to the Class B, so I can put a value in that variable (in Class B).
But, in Class B I do not know the name of that variable.
The code is something like this:
Class A
public class A {
int valore; // this is the variable, in Class b, I don't know this name!
public void callClassB(){
ClassB.Method(what shoudld i put here?)
}
}
This is the Class B
public class B {
public void Method(the_Name_Of_TheVariable_I_get){
the_Name_Of_TheVariable_I_get = 5; // i need to do this
}
}
Why do you need the variable name? Simply pass the variable itself. In class B create a method
public int getValore(){
return valore;
}
Then in Class A use modify the code as
public void callClassB(){
ClassB.Method(getValore())
}
I do not really understand what you are trying to achieve here?
You can also use the following appraoch:
interface ValueSetter {
void setValue(int value);
}
Class A
public class A implements ValueSetter{
int valore;
public void callClassB(){
ClassB.Method(this)
}
void setValue(int value){
valore = value;
}
}
This is the class B
public class B{
public void Method(ValueSetter valueSetter){
ValueSetter.setValue(5);
}
}
This is more inline with OOPS..
You will need to use reflection for this.
Here is a tutorial from Oracle: http://docs.oracle.com/javase/tutorial/reflect/index.html
You cant get the name of variable at runtime though. But assuming you have the name of the field the code would look something like this:
this.getClass().getDeclaredField(the_Name_Of_TheVariable_I_get).set(this, 5);
you can pass the name of the variable "valore", then you need reflection to assign it in your method :
a = new A();
Field f = a.getClass().getDeclaredField(varName);
f.set(a, 5);
a can be a parameter too. (it is necessary to give the instance that possesses the member).
However, this is not a recommended way of treating your issue, as it is unreliable in the sense that the compiler will not be able to check you are accessing items that actually exist.
It would be better to use an interface, for instance :
public interface Settable {
public void set(int value);
}
and then:
public class A implements Settable {
private int valore;
public void set(int value) {
valore = value;
}
public void callClassB(){
ClassB.Method(this);
}
}
and in B:
public class B{
public void Method(Settable settable){
settable.set(5);
}
}

How do I create an int that other classes can see and edit? Android

I have a class called Scouting, and it runs a function in a different class ScoutingFormData(different java file in the same package). I want it so that an integer defined in Scouting can be edited from ScoutingFormData. I defined the int:public int SFID=-1; in the main class of Scouting, but I can't figure out how to edit that int from ScoutingFormData.
Don't make your instance fields public, use getter and setters.
public int getField() {
return field;
}
public void setField(int field) {
this.field = field;
}
This is if your field needs to be an instance field.
If you need a field that belongs to the class ScoutingObject you need to make it static
public static int SFID=-1;
Then you can access it like this:
ScoutingObject.SFID
add static modifer to it so it belongs to the class.
If you mean objectwise. Use getters and setters.
Or you can change it directly by doing ScoutingObject.SFID=?; //in your ScoutingFormData class.
Use getters and setters and avoid using public attributes.
Make these methods in your Scouting class:
public int getMyInteger()
{
return myInteger;
}
public void setMyInteger(int newIntegerValue)
{
this.myInteger = newIntegerValue;
}
Where you have your private int myInteger.
In your ScoutingFormData class your can get and set the values:
setMyInteger(23); // The integer myInteger in the Scouting class is now set to 23
int newInteger = getMyInteger(); // The integer newInteger has been initialized to myIntegers value

Android how to pass a variable to another java file

In Reminder1.java I have the int hourOfDay2 and int minute2 variables. These equals with the hourOfDay and minute variable of the TimePickerDialog.
In myfile.java i want to examine the value of these variables. How to do that?
One thing I've seen posted here on SO a few times, and that I've used for global variables, is an extended Application class, like so:
public class GlobalVars extends Application {
private static int hourOfDay2;
private static int minute2;
public static int getHourOfDay() {
return hourOfDay2;
}
public static int getMinute() {
return minute2;
}
public static void setHourOfDay(int hour) {
hourOfDay2 = hour;
}
public static void setMinute(int minute) {
minute2 = minute;
}
}
Add it to your Application tag in the manifest, like so:
<application android:name=".GlobalVars" />
Then, in your main class's onCreate, or wherever necessary, just call GlobalVars.setMinute(int) to initialize them, then you can access them the same way in any other class, with int x = GlobalVars.getMinute().
In android, you can use Bundle to pass values.

Categories

Resources