0

I have loader class that loads the data from server in background when the user logs in.

The class has a static field,

public static String previousTime = "";

This field is then assigned a value with the following code (in background):

long localTime = dateTimeZone.convertLocalToUTC(lastSynchDate.getMillis(), false);
SyncDateTime = formatter.print(localTime);

if(!response.equals(""))
{
JSONObject resetJson = new JSONObject(response);

previousTime = resetJson.getString("previousTime");

success = resetJson.getString("success");
}
}

if(previousTime.equals(""))
{
previousTime = SyncDateTime;
}

The value of static field previousTime is preserved. So far so good.

But for the same code, while the user is in a logged-in state, if application is rebuilt, the previousTime value gets lost and becomes blank.

Then I need to log-in again, to get the value.

I thought that keeping the value static should preserve the value even after application rebuilt. But I have no clear idea that what's causing it to be blank.

sjain
  • 23,126
  • 28
  • 107
  • 185

2 Answers2

1

A static variable is just a variable that has a single value for a class, rather than one value per instance.

When you restart the program the value is lost when the old copy of the program stops. When the new version starts, that value has not been initialized, hence you need to login again.

andy256
  • 2,821
  • 2
  • 13
  • 19
0

Well Basicaly its better not using any static vars in application unless for Constants and general function which you can re-use in application.

Try passing the vars in intent, or saving them in main activity which have ref to all.

SacreDeveloper
  • 1,253
  • 1
  • 9
  • 16