Android Development Practice Data storage

Source: Internet
Author: User

All applications must have data input and output, Android is the same, Android application parameter settings, running state data these need to be saved to external storage, to ensure that the data is not lost after shutdown, the following are several common Android data storage methods:
Sharedpreferences: Suitable for storing small amounts of data (some configuration information, integrals, etc.);
SQLite: A really lightweight database, no background process, the entire database corresponds to a file, suitable for a large number of data storage, access to the situation.
Come down in detail to see how they are used.

1.SharedPreferences

Sharedpreferences saved data is primarily a simple type of key-value pair.
1) Sharedpreferences Interface
Primarily responsible for reading the application's preferences data, provides the following common ways to access the Key-value pairs in sharedpreferences:

boolean contains(String key) // 判断是否包含key对应的数据abstract Map<String, ?> getAll() // 获取全部key-value对boolean getXxx(String key, xxx defValue) // 获取指定key的value值

The sharedpreferences itself is an interface that cannot create an instance, only the Getsharedpreferences (String name, int mode) method provided by the context to get the Sharedpreferences instance , the mode parameter supports several values:

Context.MODE_PRIVATE // 私有,只能被本应用程序读写Context.MODE_WORLD_READABLE // 能被其他应用程序读但不可写Context.MODE_WORLD_WRITEABLE // 能被其他应用程序读写

2) Editor
The Sharedpreferences interface itself does not have the ability to write data, but through the internal interface of Sharedpreferences, Sharedpreferences calls the edit () method to get the editor object. Editor provides the following methods for writing data:

Editor clear() // 清空所有数据Editor putXxx(String key, xxx value) // 存入指定key-valueEditor remove(String key) // 删除指定key-valueboolean commit() // 编辑完成后提交修改

3) sharedpreferences Storage location
Sharedpreferences data is always stored in XML format in the/data/data/package name/shared prefs directory

Usage of 2.SharedPreferences
 Public  class sharedpreferencestest extends Activity {Sharedpreferences sp; Editor editor;@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); SP = Getsharedpreferences ("config", mode_private);        Editor = Sp.edit (); ...//Deposit a random numberEditor.putint ("Random", (int) (Math.random () * -));        Editor.commit (); ...//Read string dataString Text = sp.getstring ("Text","Text"); }}

Read and write other applications sharedpreferences need to get other programs corresponding to the context

uContext= createPackageContext("com.gc.other", Context.CONTEXT_IGNORE_SECURITY);

Then use the context of the other program to get the corresponding sharedpreferences instance, and then you can read and write data similar to the above.

SharedPreferences sp = uContext.getSharedPreferences("uconfig",Context.MODE_WORLD_READABLE);
3.SQLite Database

SQLite is an embedded database engine for the right amount of data to be accessed on devices with limited resources (the SQLite database is just a file).

Sqlitedatabase represents a database (the underlying is a database file), and Android manages and operates the database through Sqlitedatabase objects.

4.SQLiteDatabaseHelper class

Sqlitedatabasehelper is a tool class for managing databases provided by Android that can be used to manage database creation and version updates.
The general usage is to create a subclass of Sqlitedatabasehelper and extend its oncreate (Sqlitedatabase db) and Onupgrade (sqlitedatabase db, int oldversion, int NewVersion) method.

Sqlitedatabasehelper contains the following common methods:

getReadableDatabase() // 以读写的方式打开数据库对应的SQLiteDatabase对象getWritableDatabase() // 以写的方式打开数据库对应的SQLiteDatabase对象onCreate(SQLiteDatabase db) // 第一次创建回调onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) // 当数据库版本更新时回调close() // 关闭所有打开的SQLiteDatabase
5. Create a SQLite database

Inherit Sqliteopenhelper, create Userinfosqliteopenhelper Database helper class

 Public  class userinfosqliteopenhelper extends sqliteopenhelper {     PublicUserinfosqliteopenhelper (Context context) {/** * Contextual context * Name: Database file name * Factory: Used to create cursor object (default NULL, typically NULL is specified in company development) * Version: The release number of the database (starting at 1), the Onupgrade method will be called if a change occurs, * Verison can be degraded in the Android4.0 below, and cannot be degraded in versions 4.0 and later */Super (context,"Userinfo.db",NULL,2); }/** * The database is called the first time it is created (for table structure initialization, SQL statements are executed, SQL statements are executed using Sqlitedatabase database objects) */@Override Publicvoid OnCreate (Sqlitedatabase db) {//execute an SQL statement to create a tableDb.execsql ("CREATE table info (ID integer primary key autoincrement, name varchar (), email varchar (20)); /** * This method is called when the database version is upgraded (for table-structured upgrades, SQL statements are required) */@Override public void Onupgrade (Sqlitedatabase db, int. Version, int newversion) {db.execsql ("ALTER TABLE info add email varchar ( One)"); }}

You can then create the database in the Xxxactivity

//创建一个数据库帮助类对象new UserInfoSqliteOpenHelper(this);//调用帮助类对象的getReadableDatabase()方法,帮助我们将数据库创建出来SQLiteDatabase db = dbHelper.getReadableDatabase();//SQLiteDatabase db = dbHelper.getWritableDatabase();
6.SQLite Database Deletion and modification

First create the user entity class Userbean

publicclass UserBean {    publicint id;    public String name;    public String email;}

Next, the USERINFODB is packaged as follows:

 Public  class userinfodb {    PrivateUserinfosqliteopenhelper DBHelper; Public Userinfodb(Context context) {//Create a Database helper class objectDBHelper =NewUserinfosqliteopenhelper (context); }/** * * Increase * *     Public Boolean Add(UserBean Bean) {/** * Table: Table name * Nullcolumnhack: can be NULL, general NULL is passed in company development. * Values: The data content of the row added in the table, contentvalues in map package */Sqlitedatabase db = Dbhelper.getreadabledatabase (); Contentvalues contentvalues =NewContentvalues (); Contentvalues.put ("Name", bean.name); Contentvalues.put ("Email", Bean.email);//Execute INSERT, return value (if insert succeeds in inserting successful line number back, failure returns-1)        Longresult = Db.insert ("Info","NULL", contentvalues);//Internal SQL statement in the Assembly        //Close DatabaseDb.close ();if(Result = =-1){return false; }Else{return true; }    }/** * Delete * *     Public int del(String name) {Sqlitedatabase db = Dbhelper.getreadabledatabase ();/** * Table: Table name: * Whereclause: Delete condition * Whereargs: Delete parameter of condition placeholder */        The //return value is: How many rows were successfully deleted        intresult = Db.delete ("Info","name =?",NewString[]{name});//Close DatabaseDb.close ();returnResult }/** * * Change * *     Public int Update(UserBean Bean) {Sqlitedatabase db = Dbhelper.getreadabledatabase ();/** * Tables: Table name * Values: Change the contents of a field in map package * Whereclause: Update condition * Whereargs: Update parameters for conditional placeholders */        //sql:update Info Set email= ' [email protected] ' where name= ' Zhangsan ';Contentvalues contentvalues =NewContentvalues (); Contentvalues.put ("Email", Bean.email);//value returned: How many rows were successfully modified        intresult = Db.update ("Info", Contentvalues,"name =?",NewString[]{bean.name});//Close DatabaseDb.close ();returnResult }/** * * Check * *     Public void Query(String name) {Sqlitedatabase db = Dbhelper.getreadabledatabase ();/** * Table: Table name * Columns: The column name of the query (if NULL represents all queries) * Selection: Query condition * Selectionargs: Query condition placeholder Parameter * GroupBy: What to Group * having: grouping conditions * ORDER by: Which field to sort * *cursor cursor = Db.query ("Info",Newstring[]{"id","Name","Email"},"name =?",NewString[] {name},NULL,NULL,"id desc");/** * Determine if there is data in the result set * /        if(Cursor! =NULL&& Cursor.getcount () >0){//Iterate through the result set to get the contents of the result set             while(Cursor.movetonext ()) {//Get all the data content on this line                intid = cursor.getint (0); String name2 = cursor.getstring (1); String email = cursor.getstring (2); System.out.println (id+":"+name2+":"+email); }        }//Close DatabaseDb.close (); }}

So we can create a Userinfodb instance, call the method of the instance to delete the change database.

Userinfodb Userinfodb = new Userinfodb (this);Add UserBean UserBean = new UserBean ();UserBean. Name="Wangwu";UserBean. Email="[email protected]";Boolean result = Userinfodb. Add(UserBean); Delete int num = Userinfodb. del("Zhangsan");Toast. Maketext(Mcontext,"successfully deleted"+num+"line",0). Show();Change UserBean userBean1 = new UserBean ();UserBean1. Name="Lisi";UserBean1. Email="[email protected]";int num2 = Userinfodb. Update(USERBEAN1);Toast. Maketext(Mcontext,"Successful modification"+num2+"line",0). Show();Check Userinfodb. Query("Wangwu");

Android Development Practice Data storage

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.