Summary of four data access methods for Android applications

Source: Internet
Author: User
ArticleDirectory
    • 1. Use shared preferences:
    • 2. Use file:
    • 3. Network Space: (omitted)
    • 4. SQLite database:
1. Use shared preferences:

Save Android applications in one sentenceProgramConfiguration information:

Save: getpreferences (activity. mode_private). Edit (). putstring (strkey, strvalue). Commit ();

Read: strvalue = getpreferences (activity. mode_private). getstring (strkey, strdefault );

Note: getsharedpreferences () is used for configuration data sharing between different activities in the application ().

2. Use file:

Files data storage mainly uses properties and works with fileinputstream or fileoutputstream to write files.

Save:

Fileoutputstream stream = This. openfileoutput (filename, context. mode_private );

New properties (). Put (strkey, strvalue). Store (stream ,"");

Read:

Fileinputstream stream = This. openfileinput (filename );

Strvalue = string. valueof (new properties (). Load (Stream). getproperty (strkey ));

Note: using the setproperty () method of properties, You can package key-value pairs, and finally call the storexxx method to write data to the file.

3. Network Space: (Omitted) 4. SQLite database:

A, SQLitePrerequisites:

Default database path:Data/data/mypackage/databases/

Open the database:Sqlite3 dbname

Operation:. HelpHelp;. TableView All Tables

Every sentenceSQLA semicolon is required to end the statement.;

B, JDBCDriver:

Class. forname ("org. SQLite. JDBC ");

Connection conn = drivermanager. getconnection ("JDBC: SQLite: FILENAME"); // filenameFor yourSQLiteData name

C,UseSqliteopenhelperDatabase Operations:

Obtain database instances:

Getreadabledatabase ()Obtain readableSqlitedatabase

Getwritabledatabase ()Obtain writableSqlitedatabase

SqliteopenhelperCommon events to be overwritten in subclass:

Oncreate (sqlitedatabase)

Ondowngrade (sqlitedatabase dB, int oldversion, int newversion)

Onupgrade (sqlitedatabase dB, int oldversion, int newversion)

EncapsulatedDbhelpClass to perform database operations:

Public class dbhelp extends sqliteopenhelper {

Public dbhelp (context, string name, cursorfactory factory,

Int version ){

Super (context, name, factory, version );

}

@ Override

Public void oncreate (sqlitedatabase dB ){

Db.exe csql (createtablesql );//RunSQLNeed to useExecsql()

}

@ Override

Public void onupgrade (sqlitedatabase dB, int oldversion, int newversion ){

}

@ Override

Public void onopen (sqlitedatabase dB ){

}

Insertdata ()

Updatedata ()

Deletedata ()

Rawquery ()

Query ()

}

Create and open a database:

Sqlitedatabase DB = new dbhelp (sqliteactivity. This). getreadabledatabase ();

Add data:

Dbhelp = new dbhelp (sqliteactivity. This );

Sqlitedatabase DB = dbhelp. getwritabledatabase ();

Contentvalues = new contentvalues ();

Contentvalues. Put ("sname", txtname. gettext (). tostring ());

Contentvalues. Put ("ssex ","Male");

Dbhelp. insertdata (dB, contentvalues);

Modify data:

Dbhelp = new dbhelp (sqliteactivity. This );

Sqlitedatabase DB = dbhelp. getwritabledatabase ();

Contentvalues = new contentvalues ();

Contentvalues. Put ("sname", txtsname. gettext (). tostring ());

String whereclause = "SID =? ";//Which of the following conditions must be modified? Placeholder

String [] whereargs = new string [] {txtsid. gettext (). tostring ()};

Dbhelp. updatedata (dB, contentvalues, whereclause, whereargs);

Delete data:

Dbhelp = new dbhelp (sqliteactivity. This );

Sqlitedatabase DB = dbhelp. getwritabledatabase ();

String whereclause = "SID =? ";//Use the condition value of the data to be deleted? Placeholder

String [] whereargs = new string [] {txtid. gettext (). tostring ()};

Dbhelp. deletedata (dB, whereclause, whereargs);

Query data:

Cursor cur = dB. rawquery ("select * from student where Sid = 1 and sname = 'hangsan'", null );

Cursor cur = dB. rawquery (...)

EveryRawquery ()OrQuery ()ReturnsSQLiteDatabaseCursor.

Operation cursor:

UseGetcount ()Method to obtain the number of records in the result set;

PassMovetofirst (), movetonext (),AndIsafterlast ()Method to traverse all records;

PassGetcolumnnames ()Obtain the field name;

PassGetcolumnindex ()Convert to a field number;

PassGetstring (),Getint ()To obtain the value of the current record of the given field;

PassRequery ()Method re-run the query to get the cursor;

PassClose ()Method to release the cursor resource;

Simplecursoradapter: Associated with the cursor, boundListviewTo present data,Prerequisites: The table has_ IdColumn, which is the primary key.

Simplecursoradapter simple = new simplecursoradapter (sqliteactivity. this, android. r. layout. simple_list_item_1, cur, new string [] {"sname", "ssex"}, new int [] {android. r. id. text1, android. r. id. text2 });

Studentlist. setadapter (simple );

When_ IdWhen it is not a primary key, the cursor first retrieves the data and then usesSimpleadapterTo present data:

Arraylist

Hashmap <string, Object> HS;

For (cur. movetofirst ();! Cur. isafterlast (); cur. movetonext ()){

HS = new hashmap <string, Object> ();

HS. Put ("Sid", cur. getint (cur. getcolumnindex ("Sid ")));

HS. Put ("sname", cur. getstring (cur. getcolumnindex ("sname ")));

HS. Put ("ssex", cur. getstring (cur. getcolumnindex ("ssex ")));

Students. Add (HS );

}

Simpleadapter SIM = new simpleadapter (sqliteactivity. this, students, android. r. layout. simple_list_item_1, new string [] {"sname", "ssex"}, new int [] {android. r. id. text1, android. r. id. text2 });

Studentlist. setadapter (SIM );

 

Conclusion

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.