Android (SQLite database and contentprovider)

Source: Internet
Author: User
In Android, there are several data storage methods, such as file storage and file database storage. Android comes with an SQLite database, embedded developers are certainly not unfamiliar with this cross-platform local file database. In Android, a new method is proposed for data access. The contentprovider method is similar to the contentprovider method of Ms, oledb and ODBC data.
First, let's take a look at the usage of SQLite in Android. The simplest way to use it in Android is to use openorcreatedatabase of the context object.
Let's look at a piece of code:

Package test. dB;

Import Android. App. activity;
Import Android. content. intent;
Import Android. database. cursor;
Import Android. database. SQLite. sqlitedatabase;
Import Android. OS. Bundle;
Import Android. View. Menu;
Import Android. View. menuitem;
Import Android. widget. textview;

Public class dbactivity extends activity {
Private sqlitedatabase MDB = NULL;
/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Initdatabase ();
Setcontentview (R. layout. Main );
}
@ Override
Public Boolean oncreateoptionsmenu (menu ){
// Todo auto-generated method stub
Super. oncreateoptionsmenu (menu );
Menu. Add (1, menu. First + 1, 1, "getname ");
Menu. Add (1, menu. First + 2, 2, "test ");
Return true;
}

Public Boolean onoptionsitemselected (menuitem item ){
// Todo auto-generated method stub
Super. onoptionsitemselected (item );
Switch (item. getitemid ())
{
Case menu. First + 1:
{
Textview TV = (textview) This. findviewbyid (R. Id. view_main );
TV. settext (this. getname ());
Break;
}
Case menu. First + 2:
{
This. settitle ("del item ...");
Break;
}
}
Return true;
}

Private void initdatabase ()
{
MDB = This. openorcreatedatabase ("dbfile", 0, null );
String SQL _create = "CREATE TABLE test (ID int, Name text )";
Mdb.exe csql (SQL _create );
String SQL _insert = "insert into test (ID, name) values (3, 'name3 ')";
Mdb.exe csql (SQL _insert );
}
Private string getname ()
{
String name = NULL;

Cursor cur = MDB. rawquery ("select * from test", null );
Cur. movetofirst ();
While (! Cur. islast ())
{
Name = Name + cur. getstring (1) + "\ r \ n ";
Cur. movetonext ();
}
Return name;
}
}

Let's take a look at the separate use of sqliteopenhelper:
Sqliteopenhelper first inherits a database operation class, where oncreate and onupgrade must be overloaded and implemented,

Package test. dB;

Import Android. content. context;
Import Android. database. cursor;
Import Android. database. SQLite. sqlitedatabase;
Import Android. database. SQLite. sqliteopenhelper;

Public class databasehelper extends sqliteopenhelper {
@ Override
Public void oncreate (sqlitedatabase dB ){
// Todo auto-generated method stub
}
@ Override
Public void onupgrade (sqlitedatabase dB, int oldversion, int newversion ){
// Todo auto-generated method stub
}
Public databasehelper (context CT, string dbname)
{
Super (CT, dbname, null, 1 );
}
Public Boolean insert (string insert)
{
This.getwritabledatabase(.exe csql (insert );
Return true;
}
Public Boolean Update (string update)
{
This.getwritabledatabase(.exe csql (update );
Return true;
}
Public Boolean Delete (string del)
{
This.getwritabledatabase(.exe csql (DEL );
Return true;
}
Public cursor query (string query)
{
Cursor cur = This. getreadabledatabase (). rawquery (query, null );
Return cur;
}
}

Create another user (consumer)

Package test. dB;

Import Android. App. activity;
Import Android. content. intent;
Import Android. database. cursor;
Import Android. database. SQLite. sqlitedatabase;
Import Android. OS. Bundle;
Import Android. View. Menu;
Import Android. View. menuitem;
Import Android. widget. textview;

Public class dbactivity extends activity {
Private sqlitedatabase MDB = NULL;
Private databasehelper helper = NULL;
/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Initdatabase ();
Setcontentview (R. layout. Main );
}
@ Override
Public Boolean oncreateoptionsmenu (menu ){
// Todo auto-generated method stub
Super. oncreateoptionsmenu (menu );
Menu. Add (1, menu. First + 1, 1, "getname ");
Menu. Add (1, menu. First + 2, 2, "test ");
Return true;
}

Public Boolean onoptionsitemselected (menuitem item ){
// Todo auto-generated method stub
Super. onoptionsitemselected (item );
Switch (item. getitemid ())
{
Case menu. First + 1:
{
Textview TV = (textview) This. findviewbyid (R. Id. view_main );
TV. settext (this. getname ());
Break;
}
Case menu. First + 2:
{
This. settitle ("del item ...");
Break;
}
}
Return true;
}

Private void initdatabase ()
{
Helper = new databasehelper (this, "dbfile ");
// MDB = This. openorcreatedatabase ("dbfile", 0, null );
// String SQL _create = "CREATE TABLE test (ID int, Name text )";
// Mdb.exe csql (SQL _create );
String SQL _insert = "insert into test (ID, name) values (55, 'namexx ')";
// Mdb.exe csql (SQL _insert );
Helper. insert (SQL _insert );
}
Private string getname ()
{
String name = NULL;
// MDB = helper. getreadabledatabase ();
Cursor cur = helper. Query ("select * from test ");
Cur. movetofirst ();
Do
{
Name = Name + cur. getstring (1) + "\ n ";

} While (cur. movetonext ());

Return name;
}
}

Does the Code read visual basic? Well, maybe later. net, Android, Java, and blackberry eventually become consistent APIs. Of course, this is just our expectation, so that you don't have to spend so much time learning these boring interfaces all day.

Now, our contentprovider is ready. Like components such as service and broadcastreceiver, It inherits the specific interface and declares this contentprovider in androidmanifest. xml. The caller can use it.
 First, we define a contentprovider:

Package test. dB;

Import Android. content. contentprovider;
Import Android. content. contentvalues;
Import Android. database. cursor;
Import android.net. Uri;
Import Android. widget. Toast;

Public class testprovider extends contentprovider {
Private databasehelper mdbhelper = NULL;
Final Static string table_name = "test ";
@ Override
Public int Delete (URI arg0, string arg1, string [] arg2 ){
Mdbhelper. getwritabledatabase (). Delete (table_name, arg1, arg2 );
Return 0;
}

@ Override
Public String GetType (URI ){
// Todo auto-generated method stub
Return NULL;
}

@ Override
Public URI insert (URI Uri, contentvalues values ){
// Todo auto-generated method stub
Mdbhelper. getwritabledatabase (). insert (table_name, "", values );
Return NULL;
}

@ Override
Public Boolean oncreate (){
// Todo auto-generated method stub
Mdbhelper = new databasehelper (this. getcontext (), "dbfile ");
Return true;
}

@ Override
Public cursor query (URI Uri, string [] projection, string selection,
String [] selectionargs, string sortorder ){
Cursor cur = mdbhelper. getreadabledatabase (). Query (table_name, projection, selection, null );
Toast. maketext (this. getcontext (), "test cur! ", Toast. length_short );
Return cur;
}

@ Override
Public int Update (URI Uri, contentvalues values, string selection,
String [] selectionargs ){
Mdbhelper. getwritabledatabase (). Update (table_name, values, selection, null );
Return 0;
}

}

 Old rule: androidmanifest. xmlTo define this provider
<Provider Android: Label = "test_provider" Android: Authorities = "com. My. provider" Android: Name = "testprovider">
</Provider>
Here
Android: Authorities = "com. My. provider" indicates the contentprovider, which can be found by the caller,
Let's combine a URI that can find it,
Public class providerconst {
Public static final URI my_test_uri = URI. parse ("content: // com. My. provider/test ");

}

Content refers to the content provider contentprovider.
// Com. My. provider maps to the defined contentprovider ID
/Test is passed as a parameter to contentprovider. You can determine the operation target based on this parameter, such as the table in the database and the part of the data in the file.

Let's operate on this content provider:
Private string getname ()
{
String name = NULL;
Cursor cur = This. getcontentresolver (). Query (providerconst. my_test_uri, new string [] {"ID", "name"}, null );
If (cur = NULL)
Return NULL;
Cur. movetofirst ();
Do
{
Name = Name + cur. getstring (1) + "\ n ";

} While (cur. movetonext ());

Return name;
}
We can also use:
Private string getname ()
{
String name = NULL;
Cursor cur = This. managedquery (providerconst. my_test_uri, new string [] {"ID", "name"}, null );
If (cur = NULL)
Return NULL;
Cur. movetofirst ();
Do
{
Name = Name + cur. getstring (1) + "\ n ";

} While (cur. movetonext ());

Return name;
}
 

We have understood the simple usage method, so let's analyze the complicated content.

 

 

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.