Four ways to store Android data _android

Source: Internet
Author: User
Tags sqlite stub

Android offers the following four ways to store :

    • Sharepreference
    • Sqlite
    • File
    • ContentProvider

The data in the Android system are basically private, and are generally stored in the "data/data/package name" directory. If you want to implement data sharing, the correct way is to use ContentProvider.

Sharedpreference
Sharedpreference is a lightweight method of data storage, which is actually based on the "Key-value" key value pairs of data stored in XML files. Typically used to store some configuration information for a program. It is stored in the data/data/package name/shared_prefs directory.
The sharedpreference itself can only fetch data, and does not support storage and modification. Storage and modification are implemented by editor objects.

1), modify and store data

    1. The Sharedpreference object is obtained according to the Getsharedprerences (key, [mode]) method of the context;
    2. Using Sharedpreference Editor () method to obtain editor object;
    3. by editor The Putxxx () method, the key value pair is stored in the data;
    4. The data is submitted to the sharedpreference through the editor commit () method.

Comprehensive Example:

Set the value in a single case and then write the value to sharedpreference

 private string Setcityname (String _cityname) {
  city.getcity (). Setcityname (_cityname);
  
  Context CTX =mainactivity.this;
  Sharedpreferences sp =ctx.getsharedpreferences ("City", mode_private);
  Editor Editor=sp.edit ();
  Editor.putstring ("CityName", City.getcity (). Getcityname ());
  Editor.commit ();
  
  Return city.getcity (). Getcityname ();
 

2), access to data

    1. The Sharedpreference object is also obtained according to the context object;
    2. Use the Sharedpreference getxxx (key) method to get the data directly.

Comprehensive Example:

 Find from a single case, if not present, read the

 private string Getcityname () {
  string cityname = City.getcity () in Sharedpreferences. Getcityname ();
  if (Cityname==null | | cityname== "") {context
   CTX =mainactivity.this;
   Sharedpreferences sp =ctx.getsharedpreferences ("City", mode_private);
   City.getcity (). Setcityname (Sp.getstring ("CityName", "Guangzhou"));
  Return city.getcity (). Getcityname ();
 

Attention
In the Getsharedprerences (key, [mode]) method, the first argument actually corresponds to the XML file name, and the same key data is saved to the same file.
When using Sharedpreference's GetXXX (key) method to obtain data, if key does not exist, there will be no error, return none. It is recommended that you specify a default value when using GetXXX ().

Sqlite
SQLite is a lightweight relational database, and since it is a relational database, it actually operates like MySQL, SQL Server.
One thing to note is that SQLite has only null, INTEGER, real (floating-point), TEXT (String), and blob (large data) five types, and no Boolean and date types exist.

1), create a database
Created by the Openorcreatedatabase (String path, Sqlitedatabase.cursorfactory Factory) method, open the database if the library has been created.

Copy Code code as follows:
Sqlitedatabase db =this.openorcreatedatabase ("Test_db.db", context.mode_private, NULL);

2), create a table
Sqlitedatabase does not provide a way to create a table, so it is implemented by the Execsql () method. See the name also know Execsql () is used to execute SQL directly.
Copy Code code as follows:
String sql= "CREATE TABLE T_user (ID INTEGER PRIMARY KEY autoincrement, Name text not Null,password text not NULL)";
Db.execsql (SQL);

Increase
Inserts data using the Sqlitedatabase Insert (string table, String nullcolumnhack, Contentvalues values) method. The Contentvalues class, similar to the map in Java, holds data in a key-value pair.

Contentvalues values=new contentvalues ();
Values.put ("name", "Liangjh");
Values.put ("Password", "123456");
Db.insert ("T_user", "id", values);

By deleting
deleting data is more straightforward. Implemented using Sqlitedatabase's Delete (string table, String Whereclause, string[] whereargs). If you do not want to write the parameters in the Whereargs inside, you can directly write the conditions in the whereclause inside.

Mode 1 directly to the condition to write the conditions inside (personally feel easy to be injected, but in fact, the data are in the client, nothing safe to say)
Db.delete ("T_user", "id=1", null);
The way 2 conditions are written separately, feeling safer
db.delete ("T_user", "Name=?"). and password =? ", New string[]{" Weiyg "," 112233 "});

Check
Queries have 2 methods, query () and Rawquery () two methods, except that query () extracts the parameters from the SQL in query (). Refer to the example below.

Use Rawquery
//Cursor C = Db.rawquery ("SELECT * from T_user", null);
Db.rawquery ("select * from T_user where id=1", null);
Db.rawquery ("select * from T_user where id=?", New string[]{"1"});
 
Use Query ()
Cursor C = db.query ("T_user", new string[]{"id", "name"}, "Name=?", New string[]{"Weiyg"}, NULL, NULL, NUL l);
C.movetofirst ();
while (!c.isafterlast ()) {
 String msg= "";
 for (int i=0,j=c.getcolumncount (); i<j;i++) {
  msg+= "--" +c.getstring (i);
 }
 LOG.V ("SQLite", "Data:" +msg);
 C.movetonext ();
}

Change
You can modify the data using Sqlitedatabase Update (string table, contentvalues values, String whereclause, string[] whereargs). Whereclause and Whereargs are used to set their conditions. The Contentvalues object is data.

Contentvalues values=new contentvalues ();
Values.put ("Password", "111111");
Mode 1 conditions are written within the string
db.update ("T_user", Values, "id=1", null);
Mode 2 conditions and strings separate
db.update ("T_user", Values, "Name=?") Or password=? ", New string[]{" Weiyg "," 123456 "});

Other
whenever you open a database, remember to close it.

Db.close ()
In addition, you can set up transactions using BeginTransaction () and Endtransaction ().

File
The way the file is stored has been said long ago, it is not stated here.

ContentProvider
ContentProvider is more complicated than other ways, and of course its function is revolutionary in other ways. It enables the operation of data across applications. Using the Contentresolver object's Delete, update, insert, query and other methods to manipulate ContentProvider object, let ContentProvider object method to the data operation. Implemented in the following ways:

Define a ContentProvider in a program, overload its additions and deletions, and so on;
Register the ContentProvider in the Androidmanifest.xml in a program;
The ContentProvider data are obtained by Contentresolver and URI in B program, and the data is obtained and processed by using the resolver method.
1), creates a new class in a program definition provider
, inherits ContentProvider, and overloads its delete (), insert (), query (), update (), GetType (), OnCreate () method. For example, the following examples overload their OnCreate and query methods.

public class MyProvider extends ContentProvider {@Override public int delete (URI Uri, String selection, string[] Sele
 Ctionargs) {//TODO auto-generated method stub return 0;
 @Override public String getType (URI uri) {//TODO auto-generated method stub return null;
 @Override public URI inserts (URI Uri, contentvalues values) {//TODO auto-generated method stub return null; @Override public boolean onCreate () {///create a new database and insert a data sqlitedatabase db=this.getcontext (). Openorcreatedatabase ("
  Test_db2.db ", context.mode_private, NULL);
  Db.execsql ("CREATE TABLE t_user (id INTEGER PRIMARY KEY autoincrement,name TEXT not NULL)");
  Contentvalues values=new contentvalues ();
  Values.put ("name", "Liangjh2");
  Db.insert ("T_user", "id", values);
  Db.close ();
 return false; @Override public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, String Sorto Rder) {//Get Data sqlitedatabase db=this.getcontext (). openorcreatEdatabase ("Test_db2.db", context.mode_private, NULL);
  Cursor C = db.query ("T_user", NULL, NULL, NULL, NULL, NULL, NULL);
  Db.close ();
 return C; @Override public int update (URI uri, contentvalues values, String selection, string[] Selectionargs) {//TODO A
 uto-generated method stub return 0;

 }

}

Register ContentProvider
declaring the Contentprovider,authorities property in Androidmanifest.xml defines the URI identity of the ContentProvider. The URI identifier is another category and is queried by itself. Provider logo should be placed in <application></application>. If you encounter a "Permission denial:opening provide ..." error, try adding "android:exported=" to the node.

<application ...> ...
 <provider android:name= ". MyProvider "android:authorities=" Com.example.androidtestdemo "android:exported=" true "/>
</application >

2), in the B program to obtain data
gets the current contentresolver using the context, and gets the data for program a based on the URI address and the Contentresolver query method. The URI address and the Androidmanifest.xml defined in the a program are autorities consistent. Of course, the same kind can do other things.

Context Ctx=mainactivity.this;
Contentresolver resolver =ctx.getcontentresolver ();
Uri uri=uri.parse ("Content://com.example.androidtestdemo");
Cursor C = resolver.query (URI, NULL, NULL, NULL, NULL);
C.movetofirst ();
while (!c.isafterlast ()) {
 for (int i=0,j=c.getcolumncount (); i<j;i++) {
  log.v ("Android2", "" +c.getstring ( i));
 C.movetonext ();
}

The above is the entire content of this article, I hope to help you learn.

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.