somehow my mind is not working and mild fever didn't help.
I have the following code, batteryLevel here shows the correct value - 50.
public class AlarmEventService extends Service {
static String batteryLevel;
...
int level = intent.getIntExtra("level", 0);
batteryLevel = String.valueOf(level);
Log.i(APP_TAG, batteryLevel);
}
Why in my outside call when I get value of AlarmEventService.batteryLevel the value is null?
public class AlarmEventReceiverWake extends BroadcastReceiver {
...
Log.i(APP_TAG, "Battery Level " + AlarmEventService.batteryLevel);
}
From what you have presented of the code, there is no reason why it shouldnt work as expected. It may be possibile that:
Another variable named batteryLevel may be declared locally, thereby not assigning the value to the global version.
the value of batteryLevel may be reset after your initial call.
Make sure that the statement:
batteryLevel = String.valueOf(level);
is actually being called before
Log.i(APP_TAG, "Battery Level " + AlarmEventService.batteryLevel);
Related
This is a problem that is puzzling me and I wanted to get answers.
We have extended the Application and the class has variables that are to be accessed from different areas of the app. I think this was done to get a singleton implementation. The application has member objects of different classes.
public class DataApplication extends Application{
public InfoHelper mInfoHelper;
public void setHelper (InfoHelper infoHelper) {
mInfoHelper = infoHelper;
}
public InfoHelper getInfoHelper() {
if (mInfoHelper == null){
mInfoHelper = new InfoHelper();
}
return mInfoHelper;
}
// the InfoHelper class
public class InfoHelper{
public int trial = 10;
}
Now in an AsyncTask (which is started from an Activity A) updates the value of trial variable like this,
mDataApplication = (DataApplication) ((FragmentActivity)context).getApplication();
InfoHelper infoHelper = mDataApplication.getInfoHelper();
infoHelper.trial = 200;
when the AsyncTask is done, inside the Activity-A, I check the value of the trial variable using and InfoHelper variable that was created before calling the AsycTask,
// The below is created in onCreate() of Activiy-A, before the AsyncTask is started.
mInfoHelper = mScanApplication.getInfoHelper();
// After the Asyctask is done I would check the value of trial.
Log.d(TAG, "Test Value 1 --- "+ mInfoHelper.trial);
Log.d(TAG, "Test Value 2--- "+ mDataApplication.getInfoHelper().trial);
the result is,
Test Value 1 --- 10
Test Value 2--- 200
I was expecting the first result from the first Log statement but I did not expect the second log statement to get me the updated result. How did that happen? When updating in the AsyncTask, I created an object of InfoHelper and updated that object. How come it reflected everywhere. My friends said that it was because it was the same reference of the object and it does not matter if we create an object of the InfoHelper as it is the same memory location, if that is true then the question would be why the first Log statement showed me the old value?
My fundamentals are weak in this area and I appreciate may help in my quest to become better.
Note: If I create the mInfoHelper object again right before printing it I have the updated value which I was expecting to happen.
mInfoHelper = mScanApplication.getInfoHelper();
Log.d(TAG, "Test Value 1 --- "+ mInfoHelper.trial);
the result is,
Test Value 1 --- 200
calculate the amount of gas lost and set the car's current gas capacity to the new value. I forgot to add this part to the question. the amount of gas does not exceed the top gas capacity. I would like to know is this right?
private final int GAS_CAP = 30
public int getGasCapacity(int gasCapacity)
{
if(currentGas <= GAS_CAP)
{
gasCapacity = GAS_CAP - currentGas;
}
else gasCapacity = currentGas;
return gasCapacity;
}
Your method doesn't mutate the state of the object, it just returns a value. You only assign a value to the gasCapacity parameter of the method, which is local to the method.
If it's supposed to mutate something, then you got this wrong.
In addition, you are not doing anything with the value passed to your method in the gasCapacity variable, so your logic seems incorrect.
You will probably need two methods for this, one to get the current gas (accessor) and one to set it (mutator).
public int getGasLost(){
return GAS_CAP - currentGas;
}
public void setGasCapacity(int gasCapacity){
GAS_CAP = gasCapacity;
}
However, since GAS_CAP seems to be a final value, you won't be able to change it, can you confirm this?
I have 2 broadcastReceivers and 1 simple class
-simple class has 1 static variable
-when setting static variable simpleClas.time from broadcastReceiver1, the varibale is set to the correct value
-but when you try to access simpleClass.time from broadcastReceiver2, the static variable remains the same all the time, it remains in the init value. How is that thing possible?
At the end is a static
class simpleClass{
public static long time = 0;
}
class broadCastReceiver1 extends BroadcastReceiver{
#Override
public onReceive(){
//do some stuff and do an update of time variable
simpleClass.time = System.currentTimeMillis()/1000;
}
}
class broadCastReceiver2 extends BroadcastReceiver{
#Override
public onReceive(){
//do some stuff and only Read the variable time that was previously modified by broadCastReceiver1 and print the reading
System.out.println("new Value of time = " + simpleClass.time);
}
}
assuming that order of events is:
broadCastReceiver1
broadCastReceiver2
The value of time is read all the time to initial value 0;
for the broadCastReceiver2 the variable is all the time at value 0, but in the simpleClass class, time variable is updated!!!
you can do other operations in simpleClass with the new value of variable time.
Somehow broadCastReceiver2 sees only the init value of simpleClass.time.
How come? can anyone explain?
By default, broadCastReceivers run on a new process, therefore they can't share the same data.
You will need to change your manifest definitions to make them run on the same process by adding android:process="string" to the broadcast reciever definition
I was wondering if it is possible to reset the value of a variable from another class. For example I have this variable in a HillClimber (hc) class:
public int ballWeight = 200;
What I want to do is run a simulation of a game with the ball weighting at this value. When it is finished I want to set the value to 201 from another class and begin the simulation again, and after that increase to 202 and start another and so on. My problem is that every time I restart the simulation the ballWeight variable is reset to 200. I have tried using a setter method in the HillClimber class:
public int setBallWeight(int ballWeight) {
return this.ballWeight = ballWeight;
}
and called it from another class at the end of a simulation:
hc.setBallWeight(hc.ballWeight+1);
but this does not seem to work as the variables stored value is not changed. Does anyone know how I can do this so the stored value of ballWeight will be increased by 1 each time a simulation ends? Or is this even possible? Thanks.
Usually in a POJO you have what are called a getter and a setter method for every variable of the object. In your case:
public class HillClimber{
private int ballWeight;
public HillClimber(){
this.ballWeight = 200;
}
public void setBallWeight(int ballWeight){
this.ballWeight = ballWeight;
}
public int getBallWeight(){
return this.ballWeight;
}
}
In this way you can access the variable ballWeight via get and set method. You don't access it directly like in hc.ballWeight, which is possible but is a bad practice, and prevent this access type declaring your variable as private (meaning that only the class in which it is declared can directly access it).
To fullfill your request of adding one at every run of the game you can therefore call
hc.setBallWeight(++hc.getBallWeight()); //Equivalent to hc.setBallWeight(hc.getBallWeight() + 1);
I usually don't use this approach if the class isn't automatically generated (as in an Hibernate context), but instead declare another method in the HillClimber class
public void incrementBallWeight(int ballWeightToAdd){
this.ballWeight += ballweiGhtToAdd; //Equivalent to this.ballWeight = this.ballWeight + ballweiGhtToAdd;
}
or if I always need to add only one to my variable
public void incrementBallWeight(){
this.ballWeight++;
}
and then simply call incrementBallWeight after every game run.
NB: to have this working you will have to use always the same instance of HillClimber. In your main
public class Game{
private HillClimber hc = new HillClimber(); //Create the instance and sets ballWeight to 200
public static void main(String[] args){
playGame();
hc.incrementBallWeight(); //ballWeight == 201
playAnotherGame()
hc.incrementBallWeight(); //ballWeight == 202 -> Always the same instance of HillClimber (hc)
.
.
.
}
}
EDIT
I think your problem is greater than that. You are asking to save the state of a variable ( meaning that this value should be available also if you turn off and on your pc) without using a permanent storage. This is simply unachievable.
You should rethink your program (and I mean java program, not a "game run") to not stop after every game run. You can do this in different ways: via Swing GUI, via user input from stdin and so on. If you want some help on this topic, we need to know more of your code (maybe putting the whole of it is best).
OR you can use a file to store your value, which is not as difficult as you think. (Also).
I am trying to write a code to get the set of points (x,y) that are accessible to a monkey starting from (0,0) such that each point satisfies |x| + |y| < _limitSum. I have written the below code and have used static HashSet of members of Coordinate type (not shown here) and have written a recursive method AccessPositiveQuadrantCoordinates. But the problem is the members of the HashSet passed across the recursive calls is not reflecting the Coordinate members added in previous calls. Can anybody help me on how to pass Object references to make this possible? Is there some other way that this problem can be solved?
public class MonkeyCoordinates {
public static HashSet<Coordinate> _accessibleCoordinates = null;
private int _limitSum;
public MonkeyCoordinates(int limitSum) {
_limitSum = limitSum;
if (_accessibleCoordinates == null)
_accessibleCoordinates = new HashSet<Coordinate>();
}
public int GetAccessibleCoordinateCount() {
_accessibleCoordinates.clear();
Coordinate start = new Coordinate(0,0);
AccessPositiveQuadrantCoordinates(start);
return (_accessibleCoordinates.size() * 4);
}
private void AccessPositiveQuadrantCoordinates(Coordinate current) {
if (current.getCoordinateSum() > _limitSum) { return; }
System.out.println("debug: The set _accessibleCoordinates is ");
for (Coordinate c : _accessibleCoordinates) {
System.out.println("debug:" + c.getXValue() + " " + c.getYValue());
}
if (!_accessibleCoordinates.contains(current)) { _accessibleCoordinates.add(current); }
AccessPositiveQuadrantCoordinates(current.Move(Coordinate.Direction.East));
AccessPositiveQuadrantCoordinates(current.Move(Coordinate.Direction.North));
}
I will give points to all acceptable answers.
Thanks ahead,
Somnath
But the problem is the members of the HashSet passed across the recursive calls is not reflecting the Coordinate members added in previous calls.
I think that's very unlikely. I think it's more likely that your Coordinate class doesn't override equals and hashCode appropriately, which is why the set can't "find" the values.
As an aside, using static variables like this seems like a very bad idea to me - why don't you create the set in GetAccessibleCoordinateCount() and pass the reference to AccessPositiveQuadrantCoordinates, which can in turn keep passing it down in the recursive calls?
(As another aside, I would strongly suggest that you start following Java naming conventions...)
i don't see any problem with making the field _accessibleCoordinates non-static
and you should know that HashSet does not guarantee the same iteration order everytime, you could better use a LinkedList for that purpose...
and about pass by reference, i found this post very useful
java - pass by value - SO link
From what you are doing you would be updating _accessibleCoordinates in every recursive call correctly.