Android learning-data storage

Source: Internet
Author: User

From: http://blog.csdn.net/zjfstudio/article/details/4234414

 

In Android, three data storage methods and two storage methods are provided.

Three methods:

L system configuration (Shared preferences):

This type of application is mainly used to save the system configuration information. For example, if I set a color for the program interface, I want to retain the color set last time at the next startup. Because the interface of the Android system is in the form of an activity stack, some interfaces will be withdrawn when the system resources are insufficient. Therefore, I think some operations also need to be preserved when no activity occurs, it can be displayed when it is activated again.

L file (Files)

Android is an operating system, which naturally manages the storage system. Because it introduces the Linux core, all files in the andorid system are also in the form of Linux. Of course, our applications can record data in the form of files.

L database (SQLite Databases)

In the andriod system, a database management is indispensable, but considering the system resources (memory, hard disk), a lightweight database SQLite is selected. This is an open source relational database, like common relational databases, it also features acid.

 

Two storage methods:

Mainly based on the database sharing method.

L self-use within the program:

Generally, the data we need in the program is generally used for this program, so the programs we create in the above three ways are used for this program by default, and other programs cannot obtain the operation.

Enter the ADB shell in the command line to enter the file system of the mobile phone and the CD/data directory. Then, check the LS file. We found that each program we installed in the system has a folder here. After entering our program again, check the LS file. Several directories will appear: shared_prefs, files, databases, these directories are actually stored in our program's own data, the content is created by the above three ways, of course, if not created, this directory may not exist.

L data needs to be shared:

This type of data is usually some of our shared data, which is called by many programs. For example, the phone book data cannot be stored as private. Of course, in this way, the system configuration in the above three ways is not applicable, and "System Configuration" can only be accessed by this program. That is to say, only files and databases can be shared.

 

If it is not used, let's try it one by one:

 

(1) System Configuration

This type of data is stored in the form of NVP, that is, Map of name and value.

Storage:

// Get the preferences object of the activity.

Sharedpreferences uistate = getpreferences (0 );

// Get the editing object

Sharedpreferences. Editor editor = uistate. Edit ();

// Add Value

Editor. putstring (Key, Value );

Editor. putboolean (Key, Value );

Editor. Commit (); // submit and save.

Take:

// Get the preferences object of the activity.

Sharedpreferences settings = getpreferences (activity.Mode_private);

// Obtain the value.

String value = settings. getstring (Key, "Default Value ");

Boolean value = settings. getboolean (Key,False);

Access time:

With the access method, when do we want to access it:

Protected void onpause () // The system notification is paused. You can save the settings.

Public void ondestroy () // The system notification is disabled. You can save the settings.

Public void oncreate (bundle savedinstancestate) // start the system and enable the settings.

There are other statuses that we can handle based on the actual situation.

 

(2) File Operations

L open the file and operate it. If the file does not exist, it will be automatically created:

Fileoutputstream Fos = openfileoutput (file_name, context. mode_private );

// Write the value in Fos during the operation.

L read files:

Fileinputstream FCM = openfileinput (file_name );

L obtain the list of files created in the current activity:

String [] lst = filelist ()

L delete an object:

Super. deletefile (file_name );

 

(3) SQLite database operations

Database Operations are nothing more than common functions for database creation, table creation, addition, deletion, modification, and query. The Android system encapsulates a sqlitedatabase class for these operations.

LDatabase creation

The sqliteopenhelper class automatically creates a database. After the database is created, a sqlitedatabase class is returned:

Try {

Sqliteopenhelper dbhelper = new sqliteopenhelper (context,Dbname,Null, 1 );

DB = dbhelper. getwritabledatabase ();

} Catch (sqliteexception ex ){

DB = dbhelper. getreadabledatabase ();

}

ParametersDbnameIs the name of the database. Getwritabledatabase (), this method will get the database object. If the database does not exist, it will be created. But why should we pack a catch layer here? The main consideration is that the resources of mobile phones are limited, sometimes the data cannot be written due to insufficient space, but we can read it here, so getreadabledatabase is called in catch.

 

LCreate a table

_Db.exe csql ("Create Table tablename (ID integer primary key autoincrement, Name text not null );");

As you can see, this table creation is actually similar to the SQL statement we wrote, but some syntax details may be different. If this is not the case, Google will get n more.

 

LAdd

Of course, we can execute an SQL statement to insert data. We can also do this:

Contentvalues newtaskvalues =NewContentvalues ();

// Assign values for each row.

Newtaskvalues. Put (Key_task, Value );

Newtaskvalues. Put (Key_creation_date, Value );

// Insert the row.

DB. insert (Database_table,Null, Newtaskvalues );

We can put values in a hash table in sequence and store them directly.

 

LDelete

DB. Delete (Tablename, "Id =" + _ rowindex, null)

Enter the table name and conditions. Of course, you can directly splice a standard SQL statement.

 

LChange

Contentvalues newvalue =NewContentvalues ();

Newvalue. Put (Key_task, _ Task );

DB. Update (Database_table, Newvalue,Key_id+ "=" + _ Rowindex,Null

Store the value in the hash table, and then directly call

 

LQuery

Cursor result = dB. Query (database_table,

New String [] {key_id, key_task, key_creation_date },

Null, condition, null)

Here, a cursor is returned after the query. We can use this cursor to obtain data, which is used in the same way as a Java universal program.

There are more ways to use it. Only search for Google while using it.

 

(4) content providers sharing data

In the previous interface interaction, we also learned that when the Android system interface is called each other, the value is transmitted in Uri mode. On the surface, isn't URI a string? How many values can be passed? Otherwise, In Uri format: (1): // (2)/(3 ), we don't care about this first paragraph. In fact, our content providers can be defined in the system. We can write a class, for example, this is used to manage phone thin information, such:

Public ClassMyproviderExtendsContentprovider {

Private Static FinalStringMyuri=

"Content: // com. zjf. myprovider/items ";

Public Static FinalUriContent_uri= Uri.Parse(Myuri);

...

}

Here myprovider inherits the contentprovider class, and then we register it in the system (in manifext. XML ):

<Provider Android: Name = "myprovider" Android: Authorities = "com. zjf. myprovider"/>

Then we use: Content: // COM. zjf. myprovider/1 to get the information of the first person in the phone book through this URI. Let's analyze the last section "1", which is the first record, "com. zjf. myprovider "indicates which program I use to retrieve data. Therefore, the myprovider we write can perform data operations based on the input" 1 "parameter, you can save it to a file or database, but it is transparent to users and does not need to know the internal details. This is what we call the data sharing model.

Let's further look at the classes processed by myprovider inheritance:

@ Override

PublicCursor query (URI Uri, string [] projection, string selection,

String [] selectionargs, string sortorder ){

@ Override

Public IntDelete (URI Uri, string selection, string [] selectionargs)

@ Override

PublicUri insert (URI Uri, contentvalues values)

@ Override

Public IntUpdate (URI Uri, contentvalues values, string selection,

String [] selectionargs)

As you can see, myprovider is a data encapsulation. It provides shared data based on a unified interface. Each provider processes a type of shared data.

Of course, some providers in the system have been provided for us to use, such:BrowserRecords user browsing records;CalllogRecord System logs;ContactsPhone Book;SettingsSystem settings.

I don't know whether the URI "content: // contacts/1" is used to retrieve the phone book information.

 

After reading the specific implementation of the provider, we thought about what functions can this unified data interface standard provide for us? In fact, after reading the internal implementation of the provider, We also discovered that, that is, add, delete, modify, and query. Yes, we may use a unified interface to perform these operations on the public data. The specific method is as follows:

Query:

Cursor somerows = getcontentresolver (). Query (myprovider. content_uri,

Null, where, null, order );

Insert:

// Create a new row of values to insert.

Contentvalues newvalues = new contentvalues ();

Newvalues. Put (column_name, newvalue );

Uri myrowuri = getcontentresolver (). insert (myprovider. content_uri, newvalues );

Delete:

Getcontentresolver (). Delete (myprovider. content_uri, where, null );

Modify:

Getcontentresolver (). Update (myprovider. content_uri, newvalues, where,

Null );

These functions are a bit difficult to understand. Let's look at an application:

I want to query the information of the person surnamed Chen in the phone book, and then delete it:

Cursor somerows = getcontentresolver (). Query ("content: // contacts ",

Null, "name like 'chen % '", null, order );

// Obtain data from the cursor.

Getcontentresolver (). Delete ("content: // contacts", "name like 'chen % '", null); // Delete

Related Article

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.