Static modified static variables are easy to use and can be used in different classes and packages. They occupy memory independently in virtual machines. Yes, these are their advantages, however, after the project was launched, it was found that static has some disadvantages.
When viewing the project crash information, it is found that the NULL pointer exception occurs in many places. After troubleshooting, it may be a static problem. In the project, we save the User information, that is, the User object, as a static variable. in the case of an error, this variable is also used. Therefore, it can be inferred that there is a certain relationship with this storage method. At the same time, many users report that, when an application is opened, after a call or waiting for a long time, returning to the application will also crash, these crashes are related to null pointers of static variables.
In this case, is static modification very dangerous in Android development? Maybe we can say that if it is defined as static User u = new User (); then there should be no big problem, but if it is static User u, therefore, NULL may occur. Of course, the attributes in the preceding method may also be empty, but this can be encapsulated to avoid null pointers. In addition, static constants are useful.
So how should we save the logon or global information? According to Google's official recommendations and recommendations from Baidu's experts, we should try our best to use custom classes inherited from the Application, and define global variables in the classes we inherit, you can use getApplicationContext () to obtain and save related variables.
For example:
[Java]
Public class TestApplication extends Application {
Private int curIndex;
Public int getCurIndex (){
Return curIndex;
}
Public void setCurIndex (int curIndex ){
This. curIndex = curIndex;
}
@ Override
Public void onCreate (){
Super. onCreate ();
}
@ Override
Public void onTerminate (){
Super. onTerminate ();
}
}
Flexible Use in Activity
[Java]
TestApplication application = (TestApplication) this. getApplicationContext ();
// Save the variable
Application. setCurIndex (5 );
// Get the variable
Application. getCurIndex ();
The Application exists at the same time as the Application, that is, the Application is there and will not be recycled by the GC. Therefore, this method is safer and more secure, in addition, you can do a lot of work in the Application. Let's talk about it later.
From zhangyue0503