Android data storage and android Data Storage

Source: Internet
Author: User

Android data storage and android Data Storage
SharedPreferences and Editor

As long as SharedPreferences stores data in a format similar to configuration information, SharedPreferences stores data in a simple key-value pair. Diagram below


We can see that the internal class Editor of SharedPreferences is used for storage and SharedPreferences is used for retrieval.

SharedPreference is an interface that cannot be used to create an instance. Context provides the following method to create an instance. Only one instance can be created, that is, the 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 the SharedPreferences instance "Test" is the file name without a suffix. The default format is XML format sp = getSharedPreferences ("Test", Context. MODE_WORLD_WRITEABLE); // obtain the internal class write data SharedPreferences. editor editor = sp. edit (); editor. putString ("name", "value"); // The data editor cannot be obtained without submission. commit ();} public void btn (View view) {String string = sp. getString ("name", "null"); Toast. makeText (this, string, 1 ). show ();}}
Storage path: data/package name/shared_prefs/Test. xml

Open the file and you will see

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

When the stored value is put, the String corresponds to the string node in the XML file, and the Int node corresponds to the int node.

Storage Duration: when the software is uninstalled, the folder where the package name is located disappears, so the file cannot disappear.


Read and Write SharedPreferences of other applications

The above is playing in its own APP. The key to reading other apps this time is to obtain the Context of other apps (the interface representing the global information of Android Apps) because the package name is the unique identifier of the Andoird application, the Context method of the APP is called.

createPackageContext("android.example.homework", CONTEXT_IGNORE_SECURITY);

Get the Context object of other applications, and the SharedPreferences of other applications are readable (not writable, must be readable). Then, you can "Do whatever you want.

Public class MainActivity extends Activity {SharedPreferences sp; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the SharedPreferences instance try {// obtain the Context object Context = createPackageContext ("com. example. homework ", CONTEXT_IGNORE_SECURITY); // use the Context of another application 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 above read and write operations are not unique. programmers can use IO streams to directly operate SharedPreferences data that should have been used and other applications, but Android encapsulates the SharedPreferences data, which is simple.

The user-defined type cannot be stored. The APP configuration information is mainly stored, such as the user name and password ).

Chche Storage

If the storage space is insufficient, the system will delete the Cache storage, but do not rely on the system to delete it.

Storage:

File dir = getCacheDir (); File file = new File (dir, "test.txt"); try {FileOutputStream fos = new FileOutputStream (file); fos. write ("buffer storage ". getBytes ();} catch (Exception e) {// TODO: handle exception}

Take:

FileInputStream fis = new FileInputStream(file)

Both methods are internal storage, and data will be lost when the application is detached.


File Storage

FIle storage is a way for Android to continue reading and writing files using the IO stream in Java.

Two core methods:

OpenFileInput (String name );

OpenFIleOutput (String name );

The following is an example of simple read/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 FCM = null; StringBuffer sb = null; try {// open the file input stream file name. The system does not add a suffix here, do not write a file without a suffix. The file is not written. byte [] buff = new byte [1024]; int len = 0; sb = new St RingBuffer (); while (len = Fi. read (buff ))! =-1) {sb. append (new String (buff, 0, len);} // sets the function of streaming. 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 the file output stream fos = openFileOutput ("files", MODE_APPEND) in append mode ); // wrap the stream into PrintStreamPrintStream printStream = new PrintStream (fos); printStream. print ("content La la"); Toast. makeT Ext (this, "written successfully", 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 has no suffix. By default, no suffix is added. The storage path is under data/package name/file/folder.

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


SD card Storage

The disadvantage of using File storage and SharedPreferences storage is that the capacity is small because it is in the data folder of the application. Therefore, SD card storage is available. There are three steps to use the SD card for storage:

(1) Determine whether the application has the permission to read and write the SD card

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
(2) obtain the directory of the SD card

File dir = Environment.getExternalStorageDirectory();
(3) Use stream to read and write data


SD card Permissions

<! -- Add permissions for creating and deleting SD cards --> <uses-permission android: name = "android. permission. MOUNT_UNMOUNT_FILESYSTEMS"/> <! -- Add SD card write permission --> <uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>

Read/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; // if (Environment) when the SD status is ready. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {File dir = Environment. getE XternalStorageDirectory (); try {File file = new File (dir, FILE_NAME); FileInputStream FD = new FileInputStream (file ); // package the FCM stream into BufferedReaderbis = new BufferedReader (new InputStreamReader (FCM); String len = null; StringBuffer sb = new StringBuffer (""); while (len = bis. readLine ())! = Null) {sb. append (len);} Toast. makeText (this, "read data:" + 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 unavailable", 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); // use the specified File to create RandomAccessFIletry {raf = new RandomA CcessFile (file, "rw"); // move the file record pointer to the end to prevent overwrite the previous raf. seek (file. length (); raf. write ("playing with a string ". getBytes (); Toast. makeText (this, "written successfully", 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 layer is a database file). Once the application obtains the SQLiteDatabase object representing the specified database, it can be used to manage and operate the database.

(1) obtain the SQLiteDatabase object, which represents a link to the database.

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

(3). Operate the execution results of SQL statements. For example, use SimpleCursorAdapter to encapsulate Cursor.

(4). Close SQLiDatabase and Recycle resources.

Common Methods

// Create (if not exist) or open the 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; private String TABLE_NAME = "student "; // create table statement private String CREATE_TABLE = "create table" + TABLE_NAME + "(_ id integer primary key autoincrement, name varchar (20), age integer )"; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentV Iew (R. layout. activity_main); // initialize editText = (EditText) findViewById (R. id. et); listview = (ListView) findViewById (R. id. listivew); // open or create a database (the absolute path is required here) db = SQLiteDatabase. openOrCreateDatabase ("/mnt/sdcard/my. db3 ", null); if (! Exits(table_name1_mongodb.exe cSQL (CREATE_TABLE) ;}@overrideprotected void onDestroy () {super. onDestroy (); // close the 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(sql1_mongodb.exe cSQL (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 encapsulated into 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_width = "match_parent" android: layout_height = "wrap_content"/> <Button android: id = "@ + id/btn1" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: onClick = "btn" android: text = "insert string data"/> <Button android: id = "@ + id/btn2" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: onClick = "btn" android: text = "retrieve data"/> <ListView android: id = "@ + id/listivew" android: layout_width = "match_parent" android: layout_height = "wrap_content"> </ListView> </LinearLayout>

:


Because it is a custom path, the uninstall software still exists. This method of using SQLiteDatabase is rarely used.

Note: The column name of the primary key must be _ id, because SimpleCursorAdapter can only recognize the primary key of the column name as _ id.


SQLiteOpenHelper

This method of inheriting SQLiteOpenHelper is usually used. It is a tool class provided by Android to manage databases. It can be used to manage versions and updates created by databases.

Common Methods:

Synchronized SQLiteDatabase getReadableDatabase (); open the corresponding SQLiteDatabase object in read-only mode

Synchronized SQLiteDatabase getWritableDatabase (); open the corresponding SQLiteDatabase object in write mode

Abstract void Create (SQLiteDatabase db); this method is called back when a database is created for the first time.

Abstract void Upgrade (SQLiteDatabase db, int oldVersion, int newVersion); this method is called back when the database version is updated.

GetReadableDatabase () is recommended when obtaining database instances. If getWritableDatabase () is used, once the disk is full, an error occurs when opening the database. The getReadableDatabase method is read-only, even if the disk space is full, no error occurs. Instead, the read-only mode is used. (GetReadableDatabase calls include getWritableDatabase) When getReadableDatabase () is called, if the database does not exist, onCreate (SQLiteDatabase db) is called; If yes, this instance is returned.

MyDB. java

Public class MyDB extends SQLiteOpenHelper {// parameter 1: context // parameter 2: Database Name // parameter 3: cursor Factory (used only when custom, no need to customize null) // database version public MyDB (Context context, String name, int version) {super (context, name, null, version ); // TODO Auto-generated constructor stub} public SQLiteDatabase db; final String CREATE_TABLE = "create table student (_ id integer primary key autoincrement, word varchar (20 ), detail varchar (20) "; // called when the database is created for the first time. When the second running, db ==null @ Overridepublic void onCreate (SQLiteDatabase db) implements this.dbmongodbmongodb.exe cSQL (CREATE_TABLE);} // update the table structure call during software upgrade. When newVersion> oldVersion, the system automatically triggers this method. @ 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/package name/databases/mydb. db3

Files are still lost during uninstallation.


Cursor is used for query:

Common Methods:

Whether the isAfterLast () cursor Pointer Points to the end of the last data

MoveToNext () directs the cursor to the next data

MoveToFirst () points the cursor pointer to the first data

GetString (int columnIndex) obtains the String value of the specified column in the current row, and the index of the parameter column.

GetColumnIndex (StringcolumnName) obtains the column index based on the column name.

Insert: ContentValus

The ContentValus method is simple, just a key-value pair.

Modify data:

// Modify parameter 1: name of the table to be modified parameter 2: modified value parameter 3: Update condition parameter 4: update the placeholder VALUE 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 be deleted parameter 2: Deletion condition parameter 3: The placeholder value in the deletion Condition

// Return value --- number of rows deleted

Db. delete (DBHelper. TABLE_NAME, DBHelper. ENSCORE_NAME + "=? ", New String [] {" zhangsan "});






Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.