Persistent storage of Android data

Source: Internet
Author: User

One, the file storage

  Data is stored in a file:

  public void Save () {

String data = "Data to save";

FileOutputStream out = null;

BufferedWriter writer = null;

try{

out = Openfileoutput ("Data", context.mode_private);

      /*

Openfileoutput is used to store data in a specified file, and the returned out is a FileOutputStream object (a byte stream), where the first

The parameter refers to the file name, the second parameter refers to the mode of operation of the files, there are two:

Mode_private is the default mode of operation, indicating that when the same file name is specified, the content written will overwrite the contents of the original file;

Mode_append indicates that if the file exists, it appends content to the file and creates a new file if it does not exist.

      */

writer = new BufferedWriter (new OutputStreamWriter (out));

Writer.write (data);

}catch (Ioexption e) {

E.printstacktrace ();

}finally{

      

try{

if (writer! = null) {

Writer.close ();

}

}catch (ioexption e) {

E.printstacktrace ();

}

}

  The data is read from the file:

  Public String load () {

FileInputStream in = null;

BufferedReader reader = null;

StringBuilder content = new StringBuilder ();

try{

in = Openfileinput ("Data");

reader = new BufferedReader (new Fileinputreader (in));

String line = "";

while (line = Reader.readerline ()) = null) {

Content.append (line);

}

}catch (IOException e) {

E.printstacktrace ();

}finally{

if (reader! = null) {

try{

Reader.close ();

}catch (IOException e) {

E.printstacktrace ();

}

}

}

return content.tostring ();

}

Second, sharedpreferences storage (that is, the use of "key-value pair" way to store data)

  To store data steps:

1. Get the Sharedpreferences object first

      

      Three ways to get:

The first kind: the Getsharedpreferences () method in the context class;

The second kind: Get Preferences () method in activity class;

The third type: the Getdefaultsharedpreferences () method in the Preferences class.

2. Then store the data to the Sharedpreferences file

      In three steps:

(1) Call the Sharedpreferences object's edit () method to obtain a Sharedpreferences.editor object;

(2) Adding data to the Sharedpreferences.editor object;

(3) calling the Apply () method adds a data submission.

Such as:

Shared preferences.editor Editor = getsharedpreferences ("Data", Mode_private). Edit ();

Editor.putstring ("name", "Qbin");

Editor.putstring ("Age", "25");

Editor.apply ();

  To read the data step:

1, first obtain the Sharedpreferences object;

2. Use a series of Get methods in the Sharedpreferences object to read the stored data.

    Such as:

Sharedpreferences pref = getsharedpreferences ("Data", mode_private);

String name = pref.getstring ("name", "");

Int age = Pref.getint ("Age", 0);

Third, SQLite data storage (need to use Sqliteopenhelper abstract class)

  

 Sqliteopenhelper Abstract class:

There are 2 construction methods: Generally with the least parameter is the most common construction method (the first parameter of the context, the second parameter database name, the third parameter is the cursor generally passed NULL, the fourth parameter is a database

Version number);

There are 2 abstract methods: OnCreate () and Onupgrade () respectively;

            

There are 2 example methods: Getreadabledatabase () and getwritabledatabase () respectively;

          

   Such as:

      To create a database:

     public class Mydatabasehelper extends sqlitehelper{

public static final String Create_book = "CREATE table book ("

+ "ID integer primary key autoincrement,"

+ "Author text,"

+ "Price Real,"

+ "pages integer,"

+ "Neme text)";

//Build Table statement, where integer represents shaping, real represents floating point, text represents

Private Context Mcontext;

Public Mydatabasehelper (Context context, String name, Sqlitedatabase.cursorfactory factory, int version) {

Super (context, name, Factory, version);

Mcontext = context;

}

public void OnCreate (Sqlitedatabase db) {

Db.execsql (Create_book);

          The Execsql () method can perform SQL statements with change behavior such as INSERT, delete, update, and create table;

The Rawquery () method can execute a SELECT statement.

Toast.maketext (Mcontext, "Create succeeded", Toast.length_short). Show ();

}

public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {

}

}

Upgrade the database (for the above database upgrade, for example: Add a Category table in addition to the Book table):

public class Mydatabasehelper extends sqlitehelper{

public static final String Create_book = "CREATE table book ("

+ "ID integer primary key autoincrement,"

+ "Author text,"

+ "Price Real,"

+ "pages integer,"

+ "Neme text)";

      public static final String create_category = "CREATE table CATEGORY ("

+ "ID integer primary key autoincrement,"

+ "Category_name text,"

+ "Category_code integer");

Private Context Mcontext;

Public Mydatabasehelper (Context context, String name, Sqlitedatabase.cursorfactory factory, int version) {

Super (context, name, Factory, version);

Mcontext = context;

}

public void OnCreate (Sqlitedatabase db) {

Db.execsql (Create_book);

Db.execsql (create_category);

Toast.maketext (Mcontext, "Create succeeded", Toast.length_short). Show ();

}

public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {

Db.execsql (create_book);

Db.execsql (create_category);

OnCreate (DB);

}

}

    

      

Persistent storage of Android data

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.