static variable doesn't modify java android - java

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

Related

How to generate auto increment ID and do not set to default when a program is closed and opened again in java?

I am generating the auto increment number as the code below.
public class CoachRegForm extends javax.swing.JFrame {
/**
* Creates new form CoachRegForm
*/
private static int counter = 10000;
final private int coachId;
public CoachRegForm() {
initComponents();
coachId = counter++;
String staffIDInString=new Integer(coachId).toString();
CoachRegFormIDShowLab.setText(staffIDInString);
}
It works within the system, but when I close the program and run again, it goes back to the default which is 10000.
Is there any method to carry the last number saved by the program to the next time I open the program?
Your static counter field exists in the memory until your JVM shuts down (i.e., program end for standalone main() applications), so if you wanted to save and retrieve the counter value again, you need a persistent store like a database (preferable) or file system.
You can use Java API to connect to database (java.sql.* i.e., JDBC) to connect to database or file system API (i.e., java.io.*) &
A good way to store some field value is Preferences: http://www.vogella.com/tutorials/JavaPreferences/article.html
You might also consider using an AtomicInteger to prevent problems with concurrency (within ONE multithreaded instance of your program) in future.
package preferences;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.prefs.Preferences;
public class PrefsAutoinc {
private Preferences prefs;
private static final String AI_SETTING_ID = "autoincrement";
public void testPrefs() {
prefs = Preferences.userRoot().node(this.getClass().getName());
AtomicInteger autoinc = new AtomicInteger(prefs.getInt(AI_SETTING_ID, 0));
System.out.println("last saved value: " + autoinc);
System.out.println("next: " + autoinc.incrementAndGet());
System.out.println("next: " + autoinc.incrementAndGet());
prefs.putInt(AI_SETTING_ID, autoinc.get());
}
public static void main(String[] args) {
PrefsAutoinc test = new PrefsAutoinc();
test.testPrefs();
}
}
Of course if your program uses a database in any other way, then storing autoincrement value in database would be a better choice, as #javaguy suggests.
However, if you plan to run multiple instances of your application at the same time and the uniqueness of id is a must, then using centralized db storage is the only choice. Because each instance would increment it's own copy of variable and then save it in preferences, some values would be lost.
You can store the value in an ini file. You will need to update the value each time it changes.
If you do not want the users to easily detect the value, then you can store it in a database.
Anyway, you will need to not initialize it to 10000, just in the case the value was not already saved somewhere.

Android - "extending Application" and singleton and member variables

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

Setting the value of a variable from another class in Java

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).

Null value when trying to retrieve from other class

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);

Method to add a class to an array keeps adding the classes to the first position only

Here is the method
public void addModuleToStudent(Module aModule)
{
int position = 0;
if(position > 3)
{
System.out.println("Error: Student already has four modules\n");
}
else
{
moduleArray[position] = aModule;
position++;
}
}
The problem is that the position doesn't seem to be increment the position variable because when ever I add a module class it occupies the 1st position in the the array and when I add another instead of being added into the second position it overwrites the first.
Yes, position is a local variable. Every time you call addModuleToStudent, you get a new variable, initialized as 0.
It sounds like you want to make this an instance variable instead, so that it persists between method calls.
Better yet, don't use an array instead - use an ArrayList<Module> instead, and then you can just use:
public void addModuleToStudent(Module module)
{
if (modules.size() > 3)
{
throw new SomeAppropriateException("Cannot have more than 4 modules");
}
modules.add(module);
}
position is a local variable, each time you call your addModuleToStudent method it is re-initialized to zero. So, do something like
int position=0
public void addModuleToStudent(Module aModule)
{
//your logic here
}
You're resetting position to zero every time the method is called
Either make position an instance variable in the class, or use a Vector<Module> or an ArrayList<Module> instead of an array and call:
modules.add(aModules);
to add each new module onto the end of the list.
I am assuming that you are calling the addModuleToStudent method each time and that you want to add a module and that moduleArray is some global variable...
The problem here is that whenever you call the method, position is always initialized to 0. To solve your problem, what you might want to do is to remove the int position = 0; line and use the position variable as a global variable.

Categories