Data storage (i)

Source: Internet
Author: User

This period of time in writing their own player, found themselves in the data storage and extraction is not solid enough, so reference, re-organize this knowledge, and added their own understanding.
(a) Sharepreferences:
Sharepreferences is a program interface that stores key-value pairs in an XML file whose data can be accessed by all components that create it.
You can use the method activity.getpreferences (int mode) method to get the default preferences file operation mode, when an application requires multiple preferences, This can be accessed using the getsharedpreferences (String name,int mode) method of the context or activity.
Type access rights:
A. mode_private: Only the calling program has permission to access the XML file.
B. mode_world_readable: All programs can read the XML file.
C. mode_world_writeable: All programs can write the XML file.
Create and store shared preferences data (RPM):

SharedPreferences sharedPreferences = getSharedPreferences("myDataStorage",Context.MODE_PRIVATE);        Editor editor = sharedPreferences.edit();        editor.putString("username","almo");        editor.putString("password","123455");        editor.commit();

Retrieving Sharedpreferences data:

SharedPreferences prefs = getSharedPreferences("myDataStorage",Context.MODE_PRIVATE);        prefs.getString("username","");        prefs.getString("password","");

(ii) SQLite: When you need to store larger data, usually the form of a table such as contacts, songs, etc., you need to use SQLite, the database supports the SQL language. Applications that use SQLite have their own DB instance, which is only accessed by default and is stored under the/data/data//databases folder of the Android device. However, you can use content to provide ContentProvider to share database information between applications.

A. Create A Database:
First, you can create a class that defines the table name of your database tables and the name and an ID for each item, such as:

 Public  class Constants {     Public Static FinalString database_name ="Datastorage"; Public Static Final intDatabase_version =1; Public Static FinalString table_name ="Diaries"; Public Static FinalString title_name="title"; Public Static FinalString Content_name ="Content"; Public Static FinalString Date_name ="Recorddate"; Public Static FinalString key_id ="_id";}

This class defines the constants that are required to create the database.

Sqliteopenhelper:
You then need to create a sqliteopenhelper or its subclasses, which are used to create the database tables and update the database. The main function is to open a database and create it when the database does not exist, and update it as required. This class has the ability to defer opening, preventing the application from being blocked from updating the database for a long time when it starts.

 Public  class mydbhelper extends sqliteopenhelper {    Private Static FinalString TAG ="Mydbhelper";Private Static FinalString create_table ="CREATE TABLE"+ constants.table_name+"("+ constants.key_id+"Integer primary key AutoIncrement,"+ Constants.title_name +"text NOT NULL,"+ constants.content_name+"text NOT NULL,"+ constants.date_name+"long)"; Public Mydbhelper(Context context,string name,sqlitedatabase.cursorfactory Factory,intVersion) {Super(context,name,factory,version); }@Override     Public void OnOpen(Sqlitedatabase db) {Super. OnOpen (DB); }@Override     Public synchronized void Close() {Super. Close (); }@Override     Public void onCreate(Sqlitedatabase db) {LOG.D (TAG,"Oncreate:create all the Tables");        Db.execsql (create_table); LOG.D (TAG,"After on create"); }@Override     Public void Onupgrade(Sqlitedatabase DB,intOldversion,intNewVersion) {Db.execsql ("drop table if exits"+constants.table_name);    OnCreate (DB); }}

where Db.execsql (Sring sql) is used to execute SQL commands, such as Create, update, and so on. When you finish executing command db.execsql (create_table), you create a database and then call Getwritabledatabase () or getreadabledatabase () to open the database. Then you can add or extract the contents of the database, the common method is db.public long insert (string table, String nullcolumnhack, contentvalues values), Cursor C = Db.query (Constants.table_name,null,null,null,null,null,null);
Remember to close the database Db.close () after completing the action you need.

ImportAndroid.content.ContentValues;ImportAndroid.content.Context;ImportAndroid.database.Cursor;ImportAndroid.database.sqlite.SQLiteDatabase;/** * Created by Almo.liu on 2016/4/15. * * Public  class MyDB {    PrivateSqlitedatabase DB;Private FinalContext context;Private FinalMydbhelper DBHelper;Private Static FinalString TAG ="MyDB"; Public MyDB(Context c)        {context = C; DBHelper =NewMydbhelper (Context,constants.database_name,NULL, constants.database_version); } Public void Close() {db.close (); } Public void Openw() {db = Dbhelper.getwritabledatabase (); } Public void Openr() {db = Dbhelper.getreadabledatabase (); } Public Long insertdiary(String title,string content) {Contentvalues Newtaskvalue =NewContentvalues ();        Newtaskvalue.put (Constants.title_name,title);        Newtaskvalue.put (constants.content_name,content); Newtaskvalue.put (Constants.date_name,system.currenttimemillis ());returnDb.insert (Constants.table_name,NULL, Newtaskvalue); } PublicCursorgetdiaries() {Cursor c = db.query (Constants.table_name,NULL,NULL,NULL,NULL,NULL,NULL);returnC }}

There are a few noteworthy places to note:
First, the use of the Contentvalues class simplifies updating data to the database:

ContentValues contentValues = new ContentValues();        contentValues.put(Constants.TITLE_NAME,name.getText().toString());        contentValues.put(Constants.TITLE_CONTENT,introduction.getText().toString());        mDb.insert(Constants.TABLE_NAME,null,contentValues);

Then is the use of the class cursor, using the method query can get a reference to the cursor, you need to move the pointer to the place with the data, the default index is-1:

Cursor C = mDb. Query(Constants. TABLE_name,null,null,null,null,null,null);if (c. Movetofirst()) {do {title_name = c. getString(c. Getcolumnindex(Constants. TITLE_name));Content_name = C. getString(c. Getcolumnindex(Constants. TITLE_content));Marrayadapter. Add(Title_name +": \ n"+ content_name);} while (c. MoveToNext());}

Data storage (i)

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.