An example of five types of data storage in the Android system (i) _android

Source: Internet
Author: User
Tags gettext readline sqlite

The Android system has five types of data storage, namely file storage, SP storage, database storage, ContentProvider content provider, networked storage. Of these, the first four are local storage. The types of storage include simple text, window state storage, audio video data, and various data for XML registration files. The characteristics of various storage forms are not the same, so for different data types have a fixed form of storage, this article for the demonstration of convenience to give the case is basically the same, is to use account login to demo data storage, save account and password information, the next login remember account and password. Emphasis is on the principles of various storage forms.

File storage:

In the form of I/O streaming data into the cell phone memory or SD card, you can store large data, such as music, pictures or video. For mobile memory, the system creates a/data/data/package name/folder based on the package name of each application, and access to the directory under its own package does not require permission, and Android has provided a very simple API to access the folder directly. Access can be Getfilesdir () and Getcachedir (), and the two difference is that the system automatically cleans up the contents of the latter.

The files in the SD card are usually located in the Mnt/sdcard directory, and the mobile phones produced by different manufacturers may have different paths. The operation of the SD card is usually to determine whether the SD card is available and the remaining space is sufficient, because some of the phone's SD card can be unloaded, SD card in the non-mount state, can not be read and write operation. Another point, the SD card read and write operations require the appropriate permissions, or can not be completed. The way to get the SD card path is environment.getexternalstoragedirectory (), and the rest is basically similar to the file store.

File storage location:

SD Card Storage Path:

How data is stored in the phone's memory:

Package com.example.qqload;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;

Import Java.io.InputStreamReader; Import com.example.qqload_sp.

R
Import Android.os.Bundle;
Import android.app.Activity;
Import android.content.SharedPreferences;
Import Android.content.SharedPreferences.Editor;
Import Android.text.TextUtils;
Import Android.view.Menu;
Import Android.view.TextureView;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.CheckBox;
Import Android.widget.EditText;

Import Android.widget.Toast;
 public class Mainactivity extends activity {private EditText et_qq;
 Private EditText Et_password;

 Private CheckBox Cb_remenber;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  ET_QQ = (edittext) Findviewbyid (R.ID.ET_QQ); Et_password = (edittext) findviewbYid (R.id.et_password);
  Cb_remenber = (CheckBox) Findviewbyid (R.id.cb_remenber);
File File = new file (Getfilesdir (), "info.txt"); File File = new file (Getcachedir (), "info.txt"); Store data in Cache if (file.exists () && file.length () > 0) {try {FileInputStream FIS = new FileInputStream (file
    );
    BufferedReader br = new BufferedReader (new InputStreamReader (FIS));
    String line = Br.readline ();
    String QQ = Line.split ("# #") [0];
    String Password = line.split ("# #") [1];
    Et_qq.settext (QQ);
    Et_password.settext (password);
   Fis.close ();
   catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
  }} public void login (view view) {String QQ = Et_qq.gettext (). toString (). Trim ();
  String password = Et_password.gettext (). toString (). Trim (); if (Textutils.isempty (QQ) | |
   Textutils.isempty (password)) {Toast.maketext (this, "password or user name cannot be empty", 0). Show ();
  Return } if (cb_remenber.ischecked ()) {File File = NEW File (Getfilesdir (), "info.txt");
    try {fileoutputstream fos = new FileOutputStream (file);
    Fos.write (QQ + "# #" + password). GetBytes ());
    Fos.close ();
   Toast.maketext (Mainactivity.this, "save Success", 0). Show ();
    catch (Exception e) {toast.maketext (Mainactivity.this, save failed, 0). Show ();
   E.printstacktrace (); 

 }
  }
 }
}

How data is stored in an SD card:      

Package com.example.qqload;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import Java.io.InputStreamReader;

Import Java.text.Format; Import com.example.qqload_sp.

R
Import Android.os.Bundle;
Import android.os.Environment;
Import android.app.Activity;
Import android.content.SharedPreferences;
Import Android.content.SharedPreferences.Editor;
Import Android.text.TextUtils;
Import Android.text.format.Formatter;
Import Android.view.Menu;
Import Android.view.TextureView;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.CheckBox;
Import Android.widget.EditText;

Import Android.widget.Toast;
 public class Mainactivity extends activity {private EditText et_qq;
 Private EditText Et_password;

 Private CheckBox Cb_remenber;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activIty_main);
  ET_QQ = (edittext) Findviewbyid (R.ID.ET_QQ);
  Et_password = (edittext) Findviewbyid (R.id.et_password);
  Cb_remenber = (CheckBox) Findviewbyid (R.id.cb_remenber);
  File File = new file (Environment.getexternalstoragedirectory (), "info.txt");
    if (file.exists () && file.length () > 0) {try {FileInputStream FIS = new FileInputStream (file);
    BufferedReader br = new BufferedReader (new InputStreamReader (FIS));
    String line = Br.readline ();
    String QQ = Line.split ("# #") [0];
    String Password = line.split ("# #") [1];
    Et_qq.settext (QQ);
    Et_password.settext (password);
   Fis.close ();
   catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
  }} public void login (view view) {String QQ = Et_qq.gettext (). toString (). Trim ();
  String password = Et_password.gettext (). toString (). Trim (); if (Textutils.isempty (QQ) | |
   Textutils.isempty (password)) {Toast.maketext (this, "password or user name cannot be empty", 0). Show ();Return
   } if (cb_remenber.ischecked ()) {File File = new file (Environment.getexternalstoragedirectory (), "info.txt"); Determine if the SD card is mounted if (! Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {Toast.maketext (Mainactivity.this, "
    SD card not available ", 0). Show ();
   Return
   //Determine if SD card size is sufficient long size = Environment.getexternalstoragedirectory (). Getfreespace ();
   String info = formatter.formatfilesize (this, size);
   
   The data stored here is small and is not judged toast.maketext (this, "free space" + info, 0). Show ();
    try {fileoutputstream fos = new FileOutputStream (file);
    Fos.write (QQ + "# #" + password). GetBytes ());
    Fos.close ();
   Toast.maketext (Mainactivity.this, "save Success", 0). Show ();
    catch (Exception e) {toast.maketext (Mainactivity.this, save failed, 0). Show ();
   E.printstacktrace ();

 }
  }
 }
}

SP Storage:

SP storage is essentially an XML file that is stored in the phone's memory as a key-value pair. Often used to store simple parameter settings, such as the login account password storage, window function State of storage, the storage file is located in: data/data/Package name/shared_prefs folder. When used, you first need to get the instance object of the Sharedprefrences by context.getsharedprefrences (String name,int mode), and when storing the data, Use the Sharedprefrences instance object to get the editor of the Sharedprefrences file, add the data with putxxx () in the editor, and then be sure to submit the data with commit, otherwise you cannot get the data. When fetching data, use the GetXXX () method directly.

The SP store automatically generates an XML file with the following path:

How SP storage is implemented:

Package com.example.qqload; Import com.example.qqload_sp.

R
Import Android.os.Bundle;
Import android.app.Activity;
Import android.content.SharedPreferences;
Import Android.content.SharedPreferences.Editor;
Import Android.text.TextUtils;
Import Android.view.Menu;
Import Android.view.TextureView;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.CheckBox;
Import Android.widget.EditText;
Import Android.widget.Toast;
 public class Mainactivity extends activity {private EditText et_qq;
 Private EditText Et_password;
  Private CheckBox Cb_remenber;
 Private Sharedpreferences sp;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  ET_QQ = (edittext) Findviewbyid (R.ID.ET_QQ);
  Et_password = (edittext) Findviewbyid (R.id.et_password);
  Cb_remenber = (CheckBox) Findviewbyid (R.id.cb_remenber);
  SP = this.getsharedpreferences ("config", 0); String QQ = sp.getstring ("QQ","");
  String Password = sp.getstring ("Password", "");
  Et_qq.settext (QQ);
 Et_password.settext (password);
  public void Login (view view) {String QQ = Et_qq.gettext (). toString (). Trim ();
  String password = Et_password.gettext (). toString (). Trim (); if (Textutils.isempty (QQ) | |
   Textutils.isempty (password)) {Toast.maketext (this, "password or user name cannot be empty", 0). Show ();
  Return
   } if (cb_remenber.ischecked ()) {Editor edit = Sp.edit ();
   Edit.putstring ("QQ", QQ);
   Edit.putstring ("password", password);
  Edit.commit ();

 }
 }
}

Database storage:

All information in a database is stored in a single file, takes up small memory, and supports basic SQL syntax, which is often used in a project to store user information, such as a student information management system on a mobile phone. SQLite is a lightweight database built into mobile devices, Sqliteopenhelper is an abstract tool class provided by Android that manages the creation and upgrading of databases. The path to the database is:/data/data/application package name/databases/database. If you want to create a database, you need to customize a class to inherit Sqliteopenhelper, and then overwrite the abstract method, specifying the database name and version number. The creation of the table is implemented in the OnCreate () method by executing the SQL statement. If you just create it, the class does not actually create the database, but it needs to be done by executing helper.getwritabledatabase () or hepler.getreadabledatabase (). In addition, you can define a class implementation individually by doing an incremental check on the database you created. There are two ways to check and delete the operation, one is to execute the SQL statement directly, the other is the implementation of the API of Android itself. Using a database to achieve account login appears to be a bit overqualified for the demonstration of the principle of the database in this paper, the case is to use a database to record multiple users of the account and password information, and the last account information back to the interface. But this is rarely done in practical applications.

Exporting a database file from a mobile file cannot be opened directly, so you can view it using the visualizer and the Sqlite3 action tool. Here is an introduction to the use of sqlite3 tools. The following steps are required:

1. Execute adb shell command into linuxne kernel;

2. Use CD to enter the path where the database is located CD:/data/data/application package name/databases;

3. Enter database mode: SQLITE3 database name. db;

4. Execute SQL statement

Sqlite3 Operation Demo:

Database storage Path:

Database implementation method, first create a class inheritance Sqliteopenhelper, create the database and table in the class:

Package com.example.qqload.db;

Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import android.database.sqlite.SQLiteDatabase.CursorFactory;
Import Android.database.sqlite.SQLiteOpenHelper;

The public class Userdbopenhelper the extends Sqliteopenhelper {public
 userdbopenhelper (context) {
  super ( Context, "user.db", NULL, 1);
  TODO auto-generated constructor stub
 }
 @Override public
 void OnCreate (Sqlitedatabase arg0) {
  Arg0.execsql ("CREATE table User (_id integer primary key autoincrement,name Vachar (), password varchar)");
 @Override public
 void Onupgrade (sqlitedatabase arg0, int arg1, int arg2) {
  //TODO auto-generated method s Tub
 }
}

Create a tool class that implements operations on the database:

Package Com.example.qqload.db.dao;
Import java.util.ArrayList;

Import java.util.List;
Import android.content.ContentValues;
Import Android.content.Context;
Import Android.database.Cursor;

Import Android.database.sqlite.SQLiteDatabase;

Import Com.example.qqload.db.UserDBOpenhelper; 
 public class Userdao {private Userdbopenhelper helper;
 Public Userdao {helper = new Userdbopenhelper (context);
  Public long Add (String name,string password) {sqlitedatabase db = Helper.getwritabledatabase ();
  The ability to add data using SQL statements//db.execsql (INSERT into user (Name,passeord) values (?,?), New Object[]{name,password});
  Android itself API implementation modification function can have return value contentvalues values =new contentvalues ();
  Values.put ("name", name);
  Values.put ("password", password); Long result = Db.insert ("user", null, values);
  With a return value indicating which row db.close () is added;
 return result;
  Public list<user> FindAll () {list<user> List =new arraylist<user> (); Sqlitedatabase db = Helper.getreadAbledatabase ();
  Cursor Cursor = db.rawquery ("Select name, password from user", null);
  Cursor Cursor = db.query ("User", new string[]{"name", "password"}, NULL, NULL, NULL, NULL, NULL);
   while (Cursor.movetonext ()) {String name = cursor.getstring (0);
   String Password = cursor.getstring (1);
   User US = new user ();
   Us.setname (name);
   Us.setpassword (password);
  List.add (US);
  } cursor.close ();
  Db.close ();
 return list;

 }
}

Implementing account logins and records in the Main method

Package com.example.qqload;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import Java.io.InputStreamReader;

Import java.util.List;
Import Com.example.qqload.db.dao.UserDao;
Import Com.example.qqload.db.dao.user;

Import COM.EXAMPLE.QQLOAD.R;
Import Android.os.Bundle;
Import android.app.Activity;
Import android.content.SharedPreferences;
Import Android.content.SharedPreferences.Editor;
Import Android.text.TextUtils;
Import Android.view.Menu;
Import Android.view.TextureView;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.CheckBox;
Import Android.widget.EditText;

Import Android.widget.Toast;
 public class Mainactivity extends activity {private EditText et_qq;
 Private EditText Et_password;
 Private CheckBox Cb_remenber;
 Private Userdao DAO;

 Private list<user> List; @Override protected void OnCreate (Bundle savedinstancestate) {super.OnCreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  ET_QQ = (edittext) Findviewbyid (R.ID.ET_QQ);
  Et_password = (edittext) Findviewbyid (R.id.et_password);
  Cb_remenber = (CheckBox) Findviewbyid (R.id.cb_remenber);
  User U = new user ();
  DAO = new Userdao (mainactivity.this);
  List = Dao.findall ();
   if (list.size () = = 0) {et_qq.settext ("");
  Et_password.settext ("");
   else {System.out.println ("size:" + list.size ()); for (int i = 0; i < list.size (); i++) {System.out.println (List.get (i). GetName () + "::::" + list.get (i). GetPassword
   ());
   U = List.get (List.size ()-1);
   String QQ = U.getname ();
   String password = U.getpassword ();
   Et_qq.settext (QQ);
  Et_password.settext (password);
  } public void Login (view view) {String QQ = Et_qq.gettext (). toString (). Trim ();
  String password = Et_password.gettext (). toString (). Trim (); if (Textutils.isempty (QQ) | | Textutils.isempty (password)) {Toast.maketext (this, "password or user name cannot be empty", 0). show ();
  Return   } if (cb_remenber.ischecked ()) {Dao.add (QQ, password);
  Add functionality to the tool class Toast.maketext (Mainactivity.this, "save Success", 0). Show ();

 }
 }
}

The directory structure of the account login case using the database is as follows:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.