Android Data storage

Source: Internet
Author: User

Sharedpreferences and editor

Sharedpreferences saves data as long as it is similar to the configuration information format, so the data it holds is primarily a simple key-value pair form. The following diagram


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

Sharedpreference is an interface cannot create an instance, the context provides the following method to create an instance only one, that is, singleton mode.

Getsharedpreferences (String name,int mode);


Access Example

public class Mainactivity extends Activity {sharedpreferences sp; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);// Get Sharedpreferences Instance  Test is a file name, do not add a suffix, default to 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 without committing editor.commit ();} 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 values, the string corresponds to the string node in the XML file, and int is the INT node.

Storage Duration: The folder that contains the package name disappears when you uninstall the software, so the file cannot disappear as well.


Read and write sharedpreferences for other applications

The above is playing in its own app, this time to see how to read other applications, the key is to get other applications of the context (representing the Android application of the Global Information Interface) and because the package name is the Andoird application of the unique label, so call the app's context method

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

Get the context object for other apps and the other app sharedpreferences is readable (not 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);//Create SHAREDPREFERENCESSP = Context.getsharedpreferences ("Test") with the context of another application, 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, the programmer can use the IO stream to directly manipulate the sharedpreferences data of the application and other applications, but it is easy for Android to encapsulate it.

You cannot store custom types, primarily stored app configuration information, such as (user name, 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);

Here is an example of simple read and write

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 suffix, do not write no-prefix 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 ();}}}

The file suffix is not appended, the system default does not add suffixes, the storage path for the data/data/package name/file/folder

The file is still stored under the name of the package, so the data is lost when uninstalled.


SD card Storage

The disadvantage of using file storage and sharedpreferences storage is that the capacity is small because it is under the Data folder of the application. That's why the SD card is stored. The use of SD card storage is divided into three steps:

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

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

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 permission--><uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

Read and write SD card example

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 has obtained the Sqlitedatabase object representing the specified database, then it can be managed by this object to manipulate the database.

(1) Gets the Sqlitedatabase object, which represents the link to the database.

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

(3). Manipulate SQL statement execution results, such as using Simplecursoradapter to encapsulate cursor

(4). Close the Sqlidatabase and recycle the resources.

Common methods

Create (if 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) {//the cursor adapter is built at the same time as 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>


The uninstall software still exists because it is a custom path. This direct use of sqlitedatabase is rarely used in a way.

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


Sqliteopenhelper

This kind of inheritance sqliteopenhelper way to use is still more. It is an Android-provided tool class for managing databases that can be used to manage the creation of databases and updates.

Common methods:

Synchronized Sqlitedatabase getreadabledatabase (); open the corresponding Sqlitedatabase object as read-only

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 is updated.

It is recommended to use Getreadabledatabase () when obtaining a DB instance, and if Getwritabledatabase () once the disk is full, the database will be opened with an error, and the Getreadabledatabase method is opened read-only. Even if the disk space is full, it does not go wrong, but continues to use read-only mode. (Getreadabledatabase call will contain getwritabledatabase) when calling Getreadabledatabase () If the database does not exist call OnCreate (Sqlitedatabase db) ; Returns the instance after it exists

Mydb.java

public class MyDB extends Sqliteopenhelper {public MyDB (context context, String name,  int version) {Super (context, NAM E, NULL, version);//TODO auto-generated constructor stub}public sqlitedatabase db;final String create_table= "CREATE tabl e Student (_id integer PRIMARY key Autoincrement,word varchar (), detail varchar (20)) ";//called when the database is first created, when run the second time db== null@overridepublic void OnCreate (Sqlitedatabase db) {this.db=db;db.execsql (create_table);} Updates the table structure call when the software is upgraded, and the system automatically triggers the method when newversion>oldversion. @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.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.