Android app-do not store data in the Application class, androidapplication

Source: Internet
Author: User

Android app-do not store data in the Application class, androidapplication
Recently, a serious problem was found during development. When we press the home Key of the application to run it in the background, after a while, when we open the application again, in, an NullPointException NULL pointer exception occurs. According to the logcat log, a global variable is located. Why? It turns out that we put a lot of data into the application as a global variable, leading to problems. Next we will explain why we cannot put the data in the application.
I. Introduction to the application class Application and Activity. Service is a system component of the android framework. When the android program starts, the system creates an application object to store some information about the system. Generally, the system will create an application class for us by default. We do not need to perform any operations in the class, and the program will be automatically created. If you need to create your own Application, it is easy to perform some operations in it, create a class that inherits the Application and registers it in the application tag of manifest (you only need to add a name attribute to the Application tag to set the name of your Application ).

 <application        android:name="com.example.applicationdemo.MyApplication"        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >
The MyApplication class is a custom class that inherits from the Application class.
public class MyApplication extends Application {public String name;public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();}}

Ii. Why can't data be stored in the application?
Let's take a simple example: we write a set get variable method in the application inheritance class, and then use the set method of the application to set the value of the variable through the first activity, obtain this value in another activity and convert it to uppercase for display. The Code is as follows: MainActivity:
public class MainActivity extends Activity {private MyApplication application;private Button btnName;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);application = (MyApplication) getApplication();application.setName("YangLiang");btnName = (Button) findViewById(R.id.btn_name);btnName.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MainActivity.this, ShowNameActivity.class);startActivity(intent);}});}}
MyApplication class
public class MyApplication extends Application {public String name;public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();}}
Another activity that displays the content
public class ShowNameActivity extends Activity {private MyApplication app;private TextView tv;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.showname);app = (MyApplication) getApplication();String name = app.getName();tv = (TextView) findViewById(R.id.tv_showname);tv.setText(name.toLowerCase());}}
Open the application, go to the ShowNameActivity interface, and press the home Key to enter the background. After a while, open the demo again, and a null pointer exception occurs.
Error logs in logcat
Locate the Code:
tv.setText(name.toLowerCase());
Name is empty at this time
Why? Because when an application runs in the background, the system may kill the application process of the current application when the application is switched to the background or when the memory is insufficient, when we switch the application from the background to the foreground again, the system will generate a new application class. At this time, we call
app = (MyApplication) getApplication();String name = app.getName();tv.setText(name.toLowerCase());
The above name is empty, so there will be a null pointer exception, that is, the data we store in the application, it is possible that application destruction and reconstruction may cause data loss when the program is running in the background, which is fatal for the program and causes a null pointer exception and program crash.

3. What is a better solution? 1. Data is transmitted through intent, rather than in the global variable application. Of course, this method has limitations. Not all places are suitable for using intent to transmit data, not all types of data can be transmitted using intent. For more information about intent data transmission, see other materials.
2. Data Persistence, writing to a file, shareprefrence, and databases. Then, read the file where data is needed.
3. perform non-null judgment on all locations where such data needs to be used, and then perform corresponding operations.
Iv. Conclusion: Do not store data easily in the application class. What the application class should do is to initialize global configurations, data storage should use the methods recommended earlier.
Demo: http://download.csdn.net/detail/yanglfree/7709955
Android Application Data Storage Methods (2)

SQLite is a standard database for Android. It supports SQL statements and is a lightweight embedded database. an instance of SQLiteDatabase represents an SQLite database. Through some methods of the SQLiteDatabase instance, we can execute SQL statements to add, delete, query, and modify databases. note that the database is private to an application, and the database name is unique in an application. according to this name, we can see that this class is a helper class. this class mainly generates a database and manages the database version. when the getWritableDatabase () method of this class is called in the program or the getReadableDatabase () method, if there is no data at the time, the Android system will automatically generate a database. SQLiteOpenHelper is an abstract class. We usually need to inherit it and implement the three functions. The specific functions are as follows: onCreate (SQLiteDatabase): This method is called when the database is generated for the first time. Generally, the database table is generated in this method. onUpgrade (SQLiteDatabase, int, int): When the database needs to be upgraded, the Android system will actively call this method. in general, we delete a data table in this method and create a new data table. Of course, whether other operations are required depends on the needs of the application. in addition, we call this code after the query: Cursor cur = db. query (TABLE_NAME, col, null, null); The following describes the parameters: the first parameter is the name of the table in the database, for example, in our example, the table name is TABLE_NAME, that is, "diary ". the second field is the information of the columns to be returned. in this example, we want to obtain the title and body columns. we put the names of these two columns in the string array. The third parameter is selection, which is equivalent to the where part of the SQL statement. to return all data, set it to null. The fourth parameter is selectionArgs. In the selection section, can you use it ?, So the string defined in selectionArgs will replace ?.

How do I store some fixed data in android applications?

First, let's take a look at the android Data Storage Methods: file stream reading, SQLite, Content Provider, and Preference .. Note: The file users in resource and assets can only read files that cannot be written.
As the only way to share data between programs, Content Provider is not suitable here. So,
The first method is to use the FileInputStream and FileOutputStreamdui classes to perform file I/O operations and store data directly to the mobile phone.
The second method is to use SQLite to operate data through methods in the SQLiteDatabase class.
Third, Preference is used to store simple data types and save some settings. I personally think it is best to use it here. It uses key-value pairs for storage. Example:
Storage: SharedPreferences. Editor editor = sp. edit ();
Editor. putString (KEY_TEXT, "yonghu ");
Editor. commit ();
Get: sp = getPreferences (MODE_PRIVATE );
String result = sp. getString (KEY_TEXT, null );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.