How to store your data in Android 4

Source: Internet
Author: User

4 data storage methods in Android:
1.SharedPreference
2.SQLite
3.ContentProvider
4.File

1.SharedPreference
1) Lightweight data storage mode a
2) is essentially an XML file that stores Key-value key-value pairs of data
3) to hold configuration information for an application's parameters/properties
The Sharedpreference object itself can only fetch data without support for storage and modification, and the modification is implemented by editor to implement the
steps to implement Sharedpreference storage:
(1) Get Sharedpreference object
Sharedpreferences pref = getsharedpreferences ("Mypref", mode_private);
The first parameter is the name of the XML file to be stored, and the second is the file access mode
(2) to obtain the Sharedpreference.editor object
Editor editor = Pref.edit ();
(3) through the Putxxx method of the editor interface, save the key-value, where xxx is a different data type
editor.putstring ("name", "Zhang3");
Editor.putint ("Age", 18);
Editor.putlong ("Time", System.currenttimemillis ());
Editor.putboolean ("Default", true);
The first parameter specifies the key name that is requested for reading information
The second parameter specifies a default value for the key. The XML specifies the key at noon, and this default value as the method return value
(4) Saves the Key-value value through the commit method of the editor interface
Editor.commit ();//After each commit the
get data
String name = pref.getstring ("name", "AAA");
Similar to other data types
Sharedpreference small items (for learning reference)

An open source embedded database engine written in the

2.SQLite
C language. Support for most SQL92 standards.
Main Features: 1. Lightweight a dynamic library, single file
2. Independence is not dependent, no installation
3. Isolation is all in one folder
4. Multiple operating systems supported across platforms
5. Multi-lingual interface supports many programming languages
6. Security Transactions
About security issues with transactions:
--independent transaction processing through exclusive and shared locks on the database
--Multiple processes can read data at the same time in the same database, but only one can write data.


SQLite data type:
----sqlite supports null (NULL) integer (integer value)
REAL (floating-point value) TEXT (string value)
BLOB (binary)
SQLite Dynamic Data type (weak reference)
----When a value is inserted into the database, SQLite checks its type, and if the type does not match the associated column, SQLite
Converts the value to the type of the column, and if it cannot, the value is stored as its own type.
Note:
1. There are no network servers available for SQLite, only file locking or performance issues that may exist through network sharing.
2. Provide database-level locking only
3. There is no user account concept, but the permissions of all databases are determined based on the file system.
Use SQLite in Android: (Sqlitedatabase and Sqliteopenhelper)
1). Sqlitedatabase:
--provides some classes to manage SQLite databases
-provides methods for creating, deleting, executing SQL commands, and performing other common database administration tasks
-the database name of each program is unique
Common methods provided:
Db.execsql (SQL)//execute any SQL statement
Db.insert (table,nullcolumnhack,values)
Db.delete (table, Whereclause,whereargs)
Db.update (Table,values,whereclause,whereargs)
Db.query (Table,columns,selection, Selectionargs,groupby,having,orderby)
Db.rawquery (Sql,selectionargs)
to store data in the database, here's the first method: less common, more cumbersome
Add the following code to the OnCreate function:

//each program has its own database, by default each does not interfere with each other//create a database, and open/* first parameter: Database name * Second parameter: Database access rights * Third parameter: cursor instance chemical Plant class, can not need */sqlitedatabase db = Openorcreatedatabase ("User.db", mode_private, NULL);d b.execsql ("Create Table if not exists USERTB (_id integer primary key autoincrement,name text not null,age integer not null,sex text not nul L);d B.execsql ("INSERT into USERTB (name,sex,age) VALUES (' Zhang San ', ' female ')");d B.execsql ("INSERT INTO USERTB (name,sex,age VALUES (' John Doe ', ' female ', ') ');d b.execsql ("INSERT into USERTB (name,sex,age) VALUES (' Harry ', ' Male ', 33)"); Cursor C = Db.rawquery ("SELECT * from USERTB", null), if (C!=null) {while (C.movetonext ()) {log.i ("info", "_id" +c.getint ( C.getcolumnindex ("_id")); LOG.I ("info", "name" +c.getstring (C.getcolumnindex ("name")); LOG.I ("Info", "Age" +c.getint (C.getcolumnindex ("Age")); LOG.I ("info", "Sex" +c.getstring (C.getcolumnindex ("Sex")); LOG.I ("info", "!!!!!!!!!!!!!!!!!!!!!!!!!!! 1 ");} C.close ();} Db.close (); 

The above is adding data and querying the data and printing output information in log
Note:
The cursor is a class of managed data collection after the Android query data, if the query gets less data, there will be no memory
Problem, and the virtual opportunity guarantees that the cursor will eventually be released. If the cursor data volume is particularly large, especially if there is blob information inside, it should
Ensure that the memory that the cursor occupies is released in a timely manner close

The second method:
Contentvalues:
-This class is used to store a set of values that can be contentresolver processed.
Contentvalues values = new Contentvalues ();
Similar HashMap key value
Values.put ("name", "Zhang San");
Add the following code to the OnCreate function:

Sqlitedatabase db = Openorcreatedatabase ("Stu.db", mode_private, NULL);d b.execsql ("CREATE table if not exists USERTB (_id Integer primary key autoincrement,name text not null,age integer not null,sex text not null) "); Contentvalues values = new Contentvalues (), Values.put ("name", "Zhang San"), Values.put ("Age", and "Values.put") ("Sex", "male"); Db.insert ("Str.db", null,values); Values.clear (); Values.put ("Name", "John Doe"); Values.put ("Age", "a"); Values.put ("Sex", " Male ");d B.insert (" str.db ", null,values); Values.clear (); Values.put (" name "," Harry "); Values.put (" Age "," n "); Values.put (" Sex "," male ");d B.insert (" str.db ", null,values); Values.clear ();//Update values.put (" Sex "," female ") db.update (" Stutb ", Values," _ Id>? ", New string[]{" 2 "});//Change the gender of id>2 to female db.delete (" Stutb "," Name like ", New string[]{"% five "});// Delete all records with five in the name cursor c = db.query ("Stutb", NULL, "_ID>?", New string[]{"0"},null,null, "name");//query all sorts by name if (c!=null {String[]columns =c.getcolumnnames (), while (C.movetonext ()) {for (String columnname:columns) {log.i ("info", C.getstring (C.getcolumnindEX (ColumnName)));}} C.close ();} Db.close ();

2). Sqliteopenhelper
--sqlitedatabases help class for managing database creation and version updates
--Generally, create a class inheritance and override the OnCreate () and Onupgrade () methods
--Method Description:
OnCreate (Sqlitedatabase db) called when creating a database
Onupgrade (sqlitedatabase db,int oldversion,int newversion) version updated when called
... getreadabledatabase () Create or open a read-only database
... getwritabledatabase () Create or open a read-write database

Create a new class to inherit Sqliteopenhelper, and override Oncreate,onupgrade, and the constructor

Public Dbopenhelper (Context context, String name) {Super (context, name, NULL, 1);} @Override//When creating a database for the first time call, general write to build the table operation public void OnCreate (Sqlitedatabase db) {db.execsql ("CREATE table if not exists STUTB (_id Integer primary key autoincrement,name text not null,age integer not null,sex text not null);d b.execsql ("Insert int o Stutb (name,sex,age) VALUES (' Zhang San ', ' female ', 17) '); Self-invoking public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) when @Override//database version is updated {//TODO auto-generated m Ethod stub}//then mainactivity Modify the OnCreate function Dbopenhelper helper= new Dbopenhelper (Mainactivity.this, "stu.db");// Helper.getreadabledatabase ();//Gets a read-only database that can only be queried, cannot be written, cannot be updated sqlitedatabase db = Helper.getwritabledatabase ();// Db.query (table, columns, selection, Selectionargs, GroupBy, having, by-and-by); Cursor C = Db.rawquery ("SELECT * from STUTB", null), if (c!=null) {string[]columns =c.getcolumnnames (); while (C.movetonext ()) {for (String columnname:columns) {log.i ("info", C.getstring (C.getcolumnindex (ColumnName)));}} C.cloSe ();} Db.close ();

3.ContentProvider
View ContentProvider
4.File
The Android system can access files through streams, supporting file stream wrappers, but only allows read and write access to files
--android "/DATA/DATA/COM.XXX.XX (owning application package)" in Linux system
"/sdcard" in--SD card
The activity provides a way to get the file stream:
--openfileoutput---The method returns the output stream for the specified file
--openfileinput---Returns the input stream for the specified file
There are several other file manipulation methods:
--filelist ()---Get an array list of all file names under a private directory
--getfilesdir ()---Gets the file object to which the activity belongs
--deletefile (String name)---Delete the specified file

FileOutputStream openfileoutput (string name,int mode)
--The first argument is an open file name
--The second parameter is the access mode for the specified file

mode_append--Open the file and add it at the end of the file
mode_private--open files in a private way that is only available to the application to read and write
mode_world_readable--opening a file in a way that provides other applications to read
mode_world_writable--opening files in a way that provides other application writes

File output stream Write Data sample code:

private void WriteTextFile (String filename,string text) whrows ioexception{fileoutputstream fos = null; Bufferedoutputstream BOS = Null;try{fos = Openfileoutput (filename,mode_private); bos = new Bufferedoutputstream (FOS); Bos.write (Text.getbytes ("UTF-8"))}finally{try{if (Bos!=null) bos.close (); catch (IOException e) {}try{if (fos!=null) Fos.close ();} catch (IOException e) {}}}//file input stream read Data sample code: private String ReadTextFile (String filename) throws ioexception{ FileInputStream FIS = null; Bufferedinputstream bis = Null;try{fis = openfileinput (filename); bis = new Bufferredinputstream (FIS); String Realpath=this.getfilesdir (). GetPath (). toString () + "/"; File File = new file (realpath+ filename), byte[] buf = new byte[(int) file.length ()];bis.read (BUF);} finally{}}

  

  

  

  

How to store your data in Android 4

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.