Android Five big storage ways specific explanation

Source: Internet
Author: User
Tags define null

Sharedpreferences and editor

Sharedpreferences saves data only if it is similar to the configuration information format. The data it saves is therefore mostly simple key-value to form. The following diagram


It can be seen that, when stored with the sharedpreferences of the internal class editor, take the time with Sharedpreferences.

Sharedpreference is an interface cannot create an instance, the context provides the following methods to create an instance the instance can have only one, that is, a singleton pattern.

Getsharedpreferences (String name,int mode);


Sample Storage Samples

public class Mainactivity extends Activity {sharedpreferences sp; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);// Gets the Sharedpreferences instance  test is the file name. Do not add suffixes, the default is that the XML format SP = getsharedpreferences ("Test", context.mode_world_writeable);//Get internal class write data Sharedpreferences.editor Editor = Sp.edit (), editor.putstring ("name", "value"),//Cannot get data editor.commit () without committing;} public void btn (view view) {string string = sp.getstring ("name", "null"); Toast.maketext (This, string, 1). Show ();}}
The storage path is: data/data/package name/shared_prefs/test.xml

Open the file to see

<?xml version= "1.0" encoding= "utf-8" standalone = "yes"? ><map><string name= "Name" >value</string ></map>

When storing the put value, the string node is in the corresponding XML file. int at the time of the corresponding int node.

Storage Duration: The directory where the package name resides when uninstalling the software disappears, so the file cannot be the same.


Read and write sharedpreferences for other applications

The above is played in its own app, this time to see how to read other applications. The key is to obtain the context of the program for the other application (the interface that represents the global information for the Android app) and because the package name is the only indication of the Andoird application, so calling the context method of the app

Createpackagecontext ("Android.example.homework", context_ignore_security);

Get the context object for other applications and the other application sharedpreferences is readable (writable, must be readable) and can "do whatever you like".

public class Mainactivity extends Activity {sharedpreferences sp; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);// Get Sharedpreferences instance try {//Get the app's context object through the package name context Context=createpackagecontext ("Com.example.homework", context_ignore_security);//Use the context of other applications to create SHAREDPREFERENCESSP = Context.getsharedpreferences ("Test", Context.mode _world_readable+context.mode_world_writeable);} catch (Namenotfoundexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public void btn (view view) {string string = sp.getstring ("name", "null"); Toast.maketext (This, string, 1). Show ();}}

The read-write is not unique, and the program ape is fully capable of using IO streams to directly manipulate sharedpreferences data for this application and other applications. It's just that Android has encapsulated him, and it's easy.

Cannot store its own definition type. The main stored app configuration information, such as (Username,password, etc.).

Chche Storage

Insufficient storage space system will delete Cache storage, but do not rely on system removal

Save:

File dir = Getcachedir (); File File = new file (dir, "test.txt"), try {fileoutputstream fos = new FileOutputStream (file); Fos.write ("Buffered Storage". GetBytes () );} catch (Exception e) {//Todo:handle Exception}

Take:

FileInputStream fis = new FileInputStream (file)

both of these methods are internal storage, and data is lost when you uninstall an app.


File storage

File storage is one way that Android continues to read and write files using IO streams in Java

Two core methods:

Openfileinput (String name);

Openfileoutput (String name);

The following is a simple read and write sample

public class Mainactivity extends Activity {sharedpreferences sp; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} public void readed (view view) {FileInputStream FIS = null; StringBuffer sb=null;try {//Open file input stream files file name. Here the system does not add suffixes, does not write the no-suffix FIS = openfileinput ("files"); byte[] buff = new Byte[1024];int len = 0;SB = new StringBuffer (); while (len = Fis.read (buff))! =-1) {Sb.append (new String (buff, 0, Len));} Off-stream fis.close ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Toast.maketext (this, SB, 0). Show ();} public void writer (view view) {FileOutputStream Fos = null;try {//Open file output stream in Append mode fos = Openfileoutput ("Files", mode_append); Wrap the stream into printstreamprintstream printstream = new PrintStream (FOS);p rintstream.print ("Content la La la"); Toast.maketext (This, "write succeeded", 0). Show (); catch (FileNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {if (FOS! = null) try {Fos.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

This file does not have a suffix, and the system does not add suffixes by default. The storage path is data/data/package name/file/Directory

The file is still stored in the package name, so the data will be lost when uninstalling.


SD card Storage

The disadvantage of using file storage and sharedpreferences storage is that the capacity is small due to the application's data directory. That's why the SD card is stored. The use of SD card storage is divided into three steps:

(1) Infer if the application has read/write SD card permissions

Environment.getexternalstoragestate (). Equals (environment.media_mounted);
(2) Get the SD card folder

File dir = environment.getexternalstoragedirectory ();
(3) Use stream to read and write data


Permissions for SD card

<!--add SD card to create and delete file permissions--><uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/ ><!--Add SD card Write access--><uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

Read and write SD card sample

public class Mainactivity extends Activity {private final String file_name= "test.txt"; @Overrideprotected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} /** read Data */public void readed (view view) {BufferedReader bis=null;//when the SD state is equipped with the IF (Environment.getexternalstoragestate ( ). Equals (environment.media_mounted)) {File Dir = environment.getexternalstoragedirectory (); try {File file = new file ( Dir, file_name); FileInputStream fis = new FileInputStream (file),//The FIS stream is packaged as bufferedreaderbis= new BufferedReader (New InputStreamReader (FIS)); String len = null; StringBuffer sb = new StringBuffer (""); while ((Len=bis.readline ())!=null) {sb.append (len);} Toast.maketext (This, "The data read is:" +SB, 0). Show (); catch (Exception e) {e.printstacktrace ();} finally{if (Bis!=null) {try {bis.close ()} catch (IOException e) { E.printstacktrace ();}}} else Toast.maketext (this, "SD card not available", 0). Show (); /** Write Data */public void writer (view view) {Randomaccessfile RAF = null;if (EnviRonment.getexternalstoragestate (). Equals (environment.media_mounted)) {File dir = Environment.getexternalstoragedirectory ();  File File = new file (dir, file_name);//Create randomaccessfiletry with the specified file {RAF = new Randomaccessfile (file, "RW");//Move the document record pointer to the last Prevent Raf.seek (File.length ()) before overwriting again; Raf.write ("Come a string to play". GetBytes ()); Toast.maketext (This, "write succeeded", 0). Show (); catch (Exception e) {e.printstacktrace ();} Finally{if (raf!=null) {try {raf.close ();} catch (IOException e) {e.printstacktrace ();}}}}}

SQLite storage

SQLite is a lightweight database (the underlying is a database file) once the application obtains the Sqlitedatabase object representing the specified database. The next step is to manage the database with this object.

(1) Gets the Sqlitedatabase object. It represents a link to the database.

(2). Call the Sqlitedatabase method to run the SQL statement.

(3). Operation result of SQL statement, for example, using Simplecursoradapter to encapsulate cursor

(4). Turn off sqlidatabase. Recycle resources.

Frequent usage

Create (assuming not present) or open database static sqlitedatabase openorcreatedatabase (String path, Cursorfactory Factory)
Punch in an existing database static sqlitedatabase OpenDatabase (String path, cursorfactory factory, int flags)

Mainactivity.java

public class Mainactivity extends Activity {private ListView listview;private sqlitedatabase db;private EditText EditText ;p rivate string table_name= "student";//CREATE TABLE statement private String create_table = "CREATE TABLE" +table_name+ "(_id integer Prima Ry key Autoincrement,name varchar (), age integer) "; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);//Initialize EditText = (EditText) Findviewbyid (r.id.et); listview= (listview) Findviewbyid (R.ID.LISTIVEW);//Open or CREATE DATABASE (absolute path required here) db= Sqlitedatabase.openorcreatedatabase ("/MNT/SDCARD/MY.DB3", null), if (!exits (table_name)) {Db.execsql (CREATE_TABLE) ;}} @Overrideprotected void OnDestroy () {Super.ondestroy ();//Close Database if (Db!=null&&db.isopen ()) Db.close ();} public void btn (view view) {switch (View.getid ()) {case r.id.btn1://insert string str = Edittext.gettext (). toString (); String sql = "INSERT INTO" +table_name+ "(NAME) VALUES ('" +str+ "')"; SYSTEM.OUT.PRINTLN (SQL);d b.execsql (SQL); Break;case r.id.btn2://Read String sql2 = "SELECT * from" +table_name+ ""; cursor cursor = db.rawquery (SQL2, null); Inflatelistview (cursor); break;}} public boolean exits (string table) {string Sql= "select * from Sqlite_master where name=" + "'" +table+ "'"; SYSTEM.OUT.PRINTLN (SQL); cursor cursor = db.rawquery (sql, NULL); if (Cursor.getcount ()!=0) {return true;} return false;} private void Inflatelistview (cursor cursor) {///build cursor adapter at the same time that the cursor encapsulation becomes adaptersimplecursoradapter adapter = new Simplecursoradapter (this, Android. R.layout.simple_expandable_list_item_1, cursor, new string[]{"name"}, new int[]{android. R.id.text1},cursoradapter.flag_register_content_observer); Listview.setadapter (adapter);}}


Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:id=" @+id/container "android:layout_width=" Match_parent "android:layout_height= "Match_parent" android:orientation= "vertical" > <edittext android:id= "@+id/et" Android:layout_wi Dth= "Match_parent" android:layout_height= "wrap_content"/> <button android:id= "@+id/btn1" an Droid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:onclick= "Btn" Android: text= "inserting string data"/> <button android:id= "@+id/btn2" android:layout_width= "Match_parent" Androi d:layout_height= "Wrap_content" android:onclick= "btn" android:text= "Take out data"/> <listview Androi D:id= "@+id/listivew" android:layout_width= "match_parent" android:layout_height= "wrap_content" > </L Istview></linearlayout>


Because it is the path of your own definition, the uninstall software still exists. Such a direct use of sqlitedatabase in a way that uses very little.

Note: The column name of the primary key here must be _id, because Simplecursoradapter only recognizes the primary key with the column named _id.

Android also provides us with some handy ways to manipulate the database

Insert method

Regardless of whether the third parameter has data, running the method adds a single piece of data.

        Table name inserted//nullcolumnhack the        column name forcibly inserted as a null column when the values are null or do not include random key-value pairs when the parameter is valid        //values represents a row of data        Insert (string table, String nullcolumnhack, contentvalues values)
The actual Insert method is still inserted at the bottom of the SQL statement. Because the SQL statement it generates is always the same as the following statement

The number of Key-value in Contentvalue determines the following key-value pairs. INSERT into < table name > (Key1,key2 ...) VALUES (Value1,value2 ...)
Assuming that the third parameter is empty at this time

INSERT into < table name > () VALUES ()


Updata Method

The number of rows affected by the database returned by the method

To change the database table name//updated value//The record that satisfies the whereclaues sentence will be updated/used to pass in the parameter update for the whereclause sentence (String table, contentvalues values, String Whereclause, string[] whereargs)
For example, we want to update the names of people with all primary keys greater than 20 in the person table. The following methods can be called, for example:

Contentvalues values = new Contentvalues ()///Store the updated name Values.put ("name", "new name"); Db.update ("person", values, "_ID>?")

", New integer[]{20});

The corresponding SQL statement

Updata person Set Key1=value1,key2=value2...where _id>20


Delete Method

Return value changed number of rows

Table name. Whereclause the deleted condition. Whereargs to Whereclause incoming Delete (string table, String Whereclause, string[] whereargs)
For example, to delete all the names of people in the person table beginning with the Wang Word

Db.delete ("Person", "name-like", New string[]{"King%"});
The corresponding SQL statement

Delete person in where name like ' King% '


Query Method

DISTINCT specifies whether to remove the name of the table that is repeatedly logged//table run query data//columns the column name to query//selection the query condition is equivalent to the following section of the SELECT statement Wherekeyword. The Selectionargs query statement matches the number of parameters//groupby used to control the grouping,//having filtering//orderby sorting, PersonID desc Descending, age ASC ascending;//limit Paging for example: 5, 10db.query (DISTINCT, table, columns, selection, Selectionargs, GroupBy, having, by-and-by, limit, cancellationsignal);


Db.query ("Person", new string[]{"_id,name,age"}, "name like?", new string[]{"Sheet%"}, NULL, NULL, "DESC", null);
Sqliteopenhelper

This way of inheriting sqliteopenhelper is still much more.

It is a tool class for managing databases provided by Android and can be used to manage the version number and update of database creation.

Regular usage:

Synchronized Sqlitedatabase getreadabledatabase (); open the corresponding Sqlitedatabase object in a read-only manner

Synchronized Sqlitedatabase getwritabledatabase (); open the corresponding Sqlitedatabase object in write mode

abstract void Create (Sqlitedatabase db), which is invoked the first time a database is created.


abstract void Upgrade (Sqlitedatabase db,int oldversion,int newversion), which is invoked when the database version number is updated.

It is recommended to use Getreadabledatabase () when obtaining a DB instance, assuming that with getwritabledatabase () once the disk is full, the database will be opened with an error, and the Getreadabledatabase method is opened in a read-only manner. Even if the disk space is full, it will not go wrong, but continue to use the read-only method.

(Getreadabledatabase call will include Getwritabledatabase) when calling Getreadabledatabase () Assuming the database does not exist call OnCreate (Sqlitedatabase db) ; Returns the instance after it exists

Mydb.java

public class MyDB extends Sqliteopenhelper {//number of Parameters 1: Context//Number 2: Database name//Parameter 3: Cursor factory (only used when you define it, no need to define NULL yourself)//Database version public MyDB ( Context context, String name,  int version) {Super (context, name, null, version);//TODO Auto-generated constructor Stu B}public sqlitedatabase db;final String create_table= "CREATE TABLE student (_id integer primary key autoincrement,word var Char (a), detail varchar (20)) ";//called when the database is created for the first time. When executing the second time db==null@overridepublic void OnCreate (Sqlitedatabase db) {this.db=db;db.execsql (create_table);} Update the table structure call when the software upgrade, when Newversion>oldversion, the system itself to trigger the method. This method is called when the database is opened in a different version from the current version @overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {}}





Mainactivity.java

public class Mainactivity extends Activity {String A; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); MyDB db = new MyDB (This, "mydb.db3", 1); Sqlitedatabase database = Db.getreadabledatabase ();}}

Storage path data/data/Package name/databases/mydb.db3

The file is still missing while uninstalling.


Enquiry when you use it. Cursor:

Regular usage:

Isafterlast () whether the pointer to the cursor points to the back of the last piece of data

MoveToNext () to have the cursor pointer pointing to the next piece of data

Movetofirst () to have the pointer of the cursor point to the first piece of data

getString (int columnindex) Gets the string value of the specified column in the current row. Index of participation

Getcolumnindex (stringcolumnname) Gets the column index based on the column name

Insert will be used: Contentvalus

Contentvalus method is very easy, key-value pair

Change data:

Change parameter 1: Name of the changed table 2: Changed to the value of the number of parameters 3: Update condition Parameters 4: Update the value of the placeholder in the condition

Db.update (dbhelper.table_name, values,dbhelper.enscore_name+ "=?", New string[]{"Hanhan"});

Delete data:

Data deletion parameter 1: Name of the table to delete data 2: Delete condition 3: Delete the value of a placeholder in a condition

Return value---The number of rows to delete data

Db.delete (dbhelper.table_name,dbhelper.enscore_name+ "=?", New string[]{"Zhangsan"}).






Android Five big storage ways specific explanation

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.