Android Development (i) Implementing data storage technology

Source: Internet
Author: User
Tags sqlite sqlite database xml parser

This article describes 5 ways to store data in Android.

Data storage is the most frequently used in development, and here are 5 ways to implement data storage in the Android platform, respectively:

1 Storing data using sharedpreferences

2 File storage Data

3 SQLite Database Storage data

4 Storing data using ContentProvider

5 Networked Storage data

Here will be a detailed introduction.

First: Using Sharedpreferences to store data

Sharedpreferences is a lightweight storage class on the Android platform, primarily to save some of the most commonly used configurations, such as window state, typically Overloaded window state onsaveinstancestate save is typically done with sharedpreferences, which provides the Android platform with regular long shaping, int shaping, and string-string saving.

What kind of treatment is it? Sharedpreferences similar to the previous INI configuration file on a Windows system, but it is divided into multiple permissions, you can share access globally, android123 hints are ultimately stored in XML, the overall efficiency is not particularly high, It's a lot better for conventional lightweight than SQLite, and if it's really storage, it's not a good concept to define the file format. XML processing is Dalvik through the native XML parser, such as the Xmlpull method, which is good for memory resource occupancy.

Its essence is based on XML file storage Key-value key value pairs of data, usually used to store some simple configuration information.

Its storage location is under the/data/data/< package name >/shared_prefs directory.

The Sharedpreferences object itself can only fetch data and does not support storage and modification, and storage modifications are implemented through editor objects.

The steps for implementing sharedpreferences storage are as follows:

First, get the Sharedpreferences object according to the context

Second, use the edit () method to obtain the editor object.

Store Key-value key value pairs through the editor object.

Submission of data through the commit () method.

Here is the sample code: public class Mainactivity extends activity {

@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);

Get Sharedpreferences Object
Context ctx = Mainactivity.this;
Sharedpreferences sp = ctx.getsharedpreferences ("sp", mode_private);
Depositing data
Editor Editor = Sp.edit ();
Editor.putstring ("String_key", "STRING");
Editor.putint ("Int_key", 0);
Editor.putboolean ("Boolean_key", true);
Editor.commit ();

Returns the value of the String_key
LOG.D ("SP", Sp.getstring ("String_key", "none"));
If Not_exist does not exist, the return value is "none"
LOG.D ("SP", Sp.getstring ("Not_exist", "none"));
}

}


After this code is executed, a sp.xml file is generated in the/data/data/com.test/shared_prefs directory, and an application can create multiple such XML files.

Compared with the SQLite database, the Sharedpreferences object eliminates the creation of databases, tables, SQL statements and many other operations, relatively more convenient and concise. But Sharedpreferences also has its own flaws, such as its functional storage boolean,int,float,long and string Five simple data types, such as its inability to perform conditional queries. So no matter how simple the sharedpreferences data store operation is, it can only be a supplement to the way it is stored, and it cannot completely replace other data storage methods such as the SQLite database.

The second type: file storage data

With regard to file storage, activity provides a openfileoutput () method that can be used to output data to a file in a way that is the same as saving data to a file in a J2SE environment.

Files can be used to store large amounts of data, such as text, pictures, audio, and so on.

Default location:/data/data/< package >/files/***.***.

code example: public void Save ()

{

try {
FileOutputStream outstream=this.openfileoutput ("A.txt", context.mode_world_readable);
Outstream.write (Text.gettext (). toString (). GetBytes ());
Outstream.close ();
Toast.maketext (Myactivity.this, "Saved", Toast.length_long). Show ();
catch (FileNotFoundException e) {
Return
}
catch (IOException e) {
return;
}

}

The first parameter of the Openfileoutput () method specifies the file name, cannot contain the path delimiter "/", and if the file does not exist, Android automatically creates it.

The files created are saved in the/data/data/<package Name>/files directory, such as:/data/data/cn.itcast.action/files/itcast.txt, by clicking on the Eclipse menu " Window '-Show View-' other ', expand the Android folder in the Conversation window, select the File Explorer view below, and then expand/data/data/<package in the File Explorer view The file is visible to the Name>/files directory.

The second parameter of the Openfileoutput () method is used to specify the mode of operation, with four modes, respectively:

Context.mode_private = 0

Context.mode_append = 32768

context.mode_world_readable = 1

Context.mode_world_writeable = 2

Context.mode_private: For the default mode of operation, the file is private data and can only be accessed by the application itself, in which the written content overwrites the contents of the original file, if you want to append the newly written content to the original file. You can use the Context.mode_append

Context.mode_append: Mode checks whether the file exists, appends to the file, or creates a new file.

Context.mode_world_readable and context.mode_world_writeable are used to control whether other applications have permission to read and write to the file.

Mode_world_readable: Indicates that the current file can be read by other applications;

Mode_world_writeable: Indicates that the current file can be written by another application.

If you want the file to be read and written by other applications, you can pass in: Openfileoutput ("Itcast.txt", context.mode_world_readable + context.mode_world_writeable); Android has its own security model, and when the application (. apk) is installed, the system assigns him a userid, and when the application accesses other resources such as files, it needs userid matching. By default, any file created by the application, sharedpreferences, should be private (located in/data/data/<package name>/files) and not accessible by other programs.

Unless context.mode_world_readable or context.mode_world_writeable are specified at the time of creation, only such other programs can access them correctly.

Read file example: public void Load ()
{
try {
FileInputStream instream= this.openfileinput ("A.txt");
Bytearrayoutputstream stream= new Bytearrayoutputstream ();
Byte[] buffer= new byte[1024];
int length=-1;

while ((Length=instream.read (buffer))!=-1) {
Stream.Write (buffer,0,length);
}

        stream.close ();
        instream.close ();
        text.settext (stream.tostring ());
        toast.maketext (myactivity.this, "Loaded", Toast.LENGTH_LONG) . Show ();
    } catch  (filenotfoundexception e)  {
         e.printstacktrace ()

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.