Android Data storage

Source: Internet
Author: User
Tags sorted by name

There are typically three ways to store data stored in Android: Sharedpreferences, files, and SQLite databases that hold data for long periods of time. This article will be a few specific small examples to explain the specific implementation of these three ways.

sharedpreferences of data storage:

The sharedpreferences is located in the Android.content package for storing a small amount of simple data. The features are:

1. Lightweight data storage method

2. Store data as a key/value pair based on the storage method of the XML file

3. Storage of simple configuration information, supported storage types are: Boolean, Float, Integer, Long, String, and so on.

Sharedpreferences Storage Data Flow:

1. Get the Sharedpreferences object:

Private Sharedpreferences prefs;

①//does not specify a storage file name, using the default name, which is the active class name

Prefs = Getpreferences (mode_private);

②/*

* If the data in the file is a shared data between activities in an Android application,

* Every activity can be accessed, you need to use the following ways to get sharedpreferences:

* Prefs = getsharedpreferences ("Myprefs", mode_private);

*/

③//can also use Preferencemanager

Preferencemanager.setdefaultvalues (This,r.xml.preferences,false);

Prefs = Preferencemanager.getdefaultpreferencemanagers (this);

2. Store data (Use Editor object, save Key-value value), read data:

Editor editor = Prefs.edit ();

Store various types of data

Editor.putstring ("name", "Zhangsan");

Editor.putint ("Age", 18);

Editor.putlong ("Time", System.currenttimemillis);

Reading data

String name = prefs.getstring ("name");

int age = Prefs.getint ("Age");

3. Submit the settings data to save the data to a file:

After using the editor object in the 2nd step to set the Key-value value, the data is not saved to the file, and you need to save it for submission.

Editor.commit ();

4. Delete the saved data:

Sharedpreferences.clear ();

Said so much, may still be some friends say sharedpreferences what is a what east, the following everyone to see to understand:

  Figure 1. Sharedpreferences storing the contents of a file

Now you know, <string name= "user" >Zhangsan</string> is the content set with editor.putstring ("User", "Zhangsan"). Use DDMS to view the location of the file, which is stored in:

  Figure 2. Sharedpreferences File Location

Data storage (file) storage

It is easy to use sharedpreferences to store files, but you cannot specify the location of the files stored, the contents of the storage is very small, the use of file storage can be stored in the application of the default location of the file, or stored in an external storage device, such as an external SD card, can reduce the use of cell phone memory, You can store larger files.

Mode of operation of the file:

                                Table 1. File operation mode and description

Constant value

Description

Mode_private

Files can only be accessed by the application that is created

Mode_world_writeable

File allows other applications to write

Moed_world_readable

File allows other applications to read

Mode_append

If the file already exists, write the data at the end of the file without overwriting the original file contents

To use file storage:

1. Writing files

Write data to a file as a stream of characters

FileOutputStream out = Openfileoutput ("OUT.txt", mode_private);

String data = "123456abcdef";

Out.write (data); Writing data to a file

Out.close (); Close the file output stream

/*

* You can also use OutputStreamWriter to write to a file in the form of a byte stream

* OutputStreamWriter writer = new OutputStreamWriter (out);

* Writer.write (data);

* Writer.flush (); Output stream data

* Writer.close (); Close the stream

*/

2. Reading files

FileInputStream FIS = openfileinput ("Input.txt");

Bytearrayoutputstream out = new Bytearrayoutputstream ();

byte[] buffer = new byte[1024];

int len = 0;

while ((Len=fis.read (buffer))!=-1) {

Out.write (Buffer,o,len);

}

SQLite for data storage

Android uses the SQLite database engine, which is a contained, transactional database engine that does not require a separate service thread. SQLite database resource consumption, open source, powerful, has the following characteristics:

1. Lightweight, use a dynamic library, single file

2. Independence, no reliance, no installation

3. Isolation, all data in one folder

4. Cross-platform, support multiple operating systems

5. Multi-lingual interface, support many programming languages

6. Security, support transaction processing.

7. Exclusivity, the use of shared locks for independent transactions, multiple processes can read data from the consent database at the same time, but only one process can write data.

The data types supported by SQLite are: NULL, INTEGER, REAL, TEXT, blob type.

  

SQLite Storage Data Flow:

1. Get Sqlitedatabase Database objects

Sqlitedatabase db = Openorcreatedatabase ("user.db", mode_private,null);

2. Execute the data operation Statement of adding and deleting changes

Create a table

Db.execsql ("CREATE table if not exists CONTACTS_TB (_id integer primary key autoincrement,name text not null,age integer No T null) ");

Insert a piece of data into the database

Db.execsql ("INSERT into CONTACTS_TB (name,age) VALUES (' abc ', 20)");

Db.execsql ("INSERT into CONTACTS_TB (name,age) VALUES (' CDE ', 18)");

Queries all data, returns a Cursor object

cursor cursor = DB.RAW ("SELECT * from CONTACTS_TB", null);

/*

* You can also use contentvalues to perform SQL operations

* Contentvalues values = new Contentvalues ();

* Values.put ("name", "AAA");

* Values.put ("age", 20);

* Db.insert ("CONTACTS_TB", null,values); Inserting data

* Values.clear ();

* Values.put ("age", 18);

*//Update the property value of the _ID>2 data item

* Db.update ("CONTACTES_TB", Values, "_ID>?", New string[]{"2"});

*//Remove items containing ' a ' in name

* Db.delete ("CONTACTS_TB", "Name like", New string[]{"%a%"});

*//query _id>0 items, sorted by name

* Cursor cursor = db.query ("CONTACTS_TB", NULL, "_ID>?", New string[]{"0"},null,null,name);

*/

  

/*

* Create and manage databases using Sqliteopenhelper objects

* Create a new class Dbohelper extends Sqliteopenhelper

* @override Oncreate,onupdate method

* Using Dbohelper objects

* Dbohelper helper = new Dbohelper (This, "user.db");

*//Create or open a read-only database

* Sqlitedatabase db = Helper.getwriteabledatabase ();

*//sqlitedatabase db = Helper.getreadabledatabase ();

* Data operation is the same as above

*/

3. Processing the obtained results

String NAME[10];

int age[10];

int i=0;

while (Cursor.movetonext ()) {

Name[i] = cursor.getstring (Cursor.getcolumnindex ("name"));

Age[i] = Cursor.getint (Cursor.getcolumnindex ("Age"));

i++;

}

Cursor.close (); Manual shutdown is required, otherwise an unknown exception will occur

Db.close (); Database objects must also be closed manually

The following is a concrete example of a simple implementation of SQLite data storage, using the ListView data binding:

Dbhelper.java file public class DBHelper extends Sqliteopenhelper{public dbhelper (context context, String name) {Super ( context, name, NULL, 1);} @Overridepublic void OnCreate (Sqlitedatabase db) {} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {}}contact.java file, public class, contact extends activity{private ListView lists; Simpleadapter adapter; List<map<string, object>> dataList, @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.layout_contacts); lists = (ListView) Findviewbyid ( R.id.contacts_list); All_contacts ();} public void All_contacts () {dataList = new arraylist<map<string,object>> (); adapter = new Simpleadapter ( Contact.this, DataList, r.layout.layout_contacts, new string[]{"_id", "name", "Sex", "Phone"}, new int[]{r.id._id,r.id. _name,r.id._sex,r.id._phone});D Bhelper dbhelper = new DBHelper (contact.this, "contacts.db"); Sqlitedatabase db = Dbhelper.getreadabledatabase (); CUrsor cursor = db.rawquery ("SELECT * from Tb_persons", null), Cursor.movetofirst ();d o {map<string, object> Map = new Hashmap<string, Object> (), Map.put ("_id", Cursor.getint (Cursor.getcolumnindex ("_id")), Map.put ("name", Cursor.getstring (Cursor.getcolumnindex ("name"))) map.put ("Sex", Cursor.getstring (Cursor.getcolumnindex ("Sex"))) Map.put ("Phone", Cursor.getstring (Cursor.getcolumnindex ("Phone")));d Atalist.add (map); while (Cursor.movetonext ()); Cursor.close ();d b.close (); Lists.setadapter (adapter);}} Mainactivity.java file public class Mainactivity extends Activity {private button Btn_add;private button btn_ok;private Button btn_cancel;private EditText nametext;private EditText sextext;private EditText phonetext;private linearlayout Info_layout;private sqlitedatabase db; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); btn_add = (Button) Findviewbyid (r.id.btn_add); Btn_OK = ( Button) Findviewbyid (r.id.btn_OK) Btn_cancel = (Button) Findviewbyid (r.id.btn_cancel); nametext = (EditText) Findviewbyid (r.id.name); Sextext = ( EditText) Findviewbyid (r.id.sex);p Honetext = (EditText) Findviewbyid (r.id.phone); info_layout = (linearlayout) Findviewbyid (R.id.info_form);D Bhandler ();} Auxiliary method, open Add contact information area public void Add_contact (View v) {info_layout.setvisibility (view.visible); Btn_add.setenabled ( FALSE);} Jump to query all contact page public void Search_all (View v) {Intent Intent = new Intent (mainactivity.this, Contact.class); StartActivity (intent);} Add contact information Area public void Insert_info (View v) {Long id = 0; String name = Nametext.gettext (). toString (). Trim (); String sex = Sextext.gettext (). toString (). Trim (); String phone = Phonetext.gettext (). toString (). Trim (); Contentvalues values = new Contentvalues () values.put ("name", name), Values.put ("Sex", sex); Values.put ("Phone", phone) ;d B = openorcreatedatabase ("Contacts.db", mode_private, null); id = db.insert ("tb_persons", null, values); Values.clear ( );d b.close (); Nametext.settext (""); Sextext.setText ("");p Honetext.settext (""); info_layout.setvisibility (view.invisible); btn_add.setenabled (true); if (id==-1) { Toast.maketext (This, "Contact add failed!") ", Toast.length_short). Show (); return;} Toast.maketext (This, "contact added successfully!") ", Toast.length_short). Show ();} Empty Add information box public void Cancel_info (View v) {nametext.settext (""); Sextext.settext ("");p Honetext.settext (""); info_ Layout.setvisibility (view.invisible); btn_add.setenabled (true); Toast.maketext (This, "added canceled! ", Toast.length_short). Show ();} Create contact database PRIVATE void Dbhandler () {//Create application Database db = Openorcreatedatabase ("Contacts.db", mode_private, NULL); Db.execsql ("CREATE table if not exists tb_persons (_id integer primary key autoincrement,name text not null,sex text not Nu Ll,phone text NOT NULL) ");}}

Application map and how the program works:

The above is the principle of three ways, the code is more messy, have time to comb the next! Believe in the power of sharing, perseverance is victory!

Android Data storage

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.