Android [intermediate tutorial] Chapter 3 SQLite of data storage

Source: Internet
Author: User

In this chapter, we are going to learn about the android database SQLite. We still take the previous chapter. For the migration of Tang Seng to westday, the three younger siblings have to kill monsters, so we have to make a summary, there is a count. Here we use SQLite to store the number of monsters killed by each hacker. OK, go to main. XML

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" the number of monsters killed by the heroes of travel to the West "Android: id = "@ + ID/textview1"> </textview> <button Android: text = "add a leading role" Android: Id = "@ + ID/add_btn" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> </button> <button Android: text = "update the number of monsters killed by the protagonist" Android: id = "@ + ID/update_btn" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> </button> <button Android: TEXT = "delete a protagonist" Android: Id = "@ + ID/del_btn" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> </button> <listview Android: layout_height = "wrap_content" Android: Id = "@ + ID/listview1" Android: layout_width = "match_parent"> </listview> </linearlayout>

Three buttons are defined here, one listview, and three layout are defined to show "add a main character" and "update the number of monsters killed by the main character ", the "delete a main character" page is as follows:

Add_item.xml

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: padding = "10dp"> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" name "> </textview> <edittext Android: layout_height =" wrap_content "Android: layout_width = "match_parent" Android: Id = "@ + ID/add_name"> <requestfocus> </edittext> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" kill monsters "> </textview> <edittext Android: layout_height =" wrap_content "Android: layout_width = "match_parent" Android: Id = "@ + ID/add_number" Android: inputtype = "Number"> </edittext> </linearlayout>

Update_item.xml

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: padding = "10dp"> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" ID "> </textview> <edittext Android: layout_height =" wrap_content "Android: layout_width = "match_parent" Android: Id = "@ + ID/update_id" Android: inputtype = "Number"> <requestfocus> </edittext> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" kill monsters "> </textview> <edittext Android: layout_height =" wrap_content "Android: layout_width = "match_parent" Android: Id = "@ + ID/update_number" Android: inputtype = "Number"> </edittext> </linearlayout>

Delete_item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent" android:padding="10dp"><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="ID"></TextView><EditText android:layout_height="wrap_content"android:layout_width="match_parent" android:id="@+id/delete_id"android:inputType="number"><requestFocus></requestFocus></EditText></LinearLayout>

Finally, define a list_item.xml file.

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <linearlayout Android: layout_height = "wrap_content" Android: Id = "@ + ID/linearlayout1" Android: layout_width = "match_parent"> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" ID: "Android: paddingleft =" 10dp "> </textview> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" textview "Android: Id =" @ + ID/ID "> </textview> <textview Android: layout_height = "wrap_content" Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" textview "Android: Id =" @ + ID/Name "Android: paddingleft = "30dp"> </textview> </linearlayout> <linearlayout Android: layout_height = "wrap_content" Android: Id = "@ + ID/linearlayout2" Android: layout_width = "match_parent"> <textview Android: layout_height = "wrap_content" Android: layout_width = "wrap_content" Android: text = "killed" Android: paddingleft = "10dp"> </textview> <textview Android: text = "textview" Android: Id = "@ + ID/number" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: textcolor = "# ff0000"> </textview> <textview Android: text = "only monsters" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> </textview> </linearlayout>

OK. After the definition is complete, we will create a database and create a databasehelper. Java

Import android. content. context; import android. database. SQLite. sqlitedatabase; import android. database. SQLite. sqliteopenhelper; public class databasehelper extends sqliteopenhelper {// database name Private Static final string db_name = "sqlitedemo. DB "; // database version Private Static final int db_version = 1; // table name public static final string table_name =" Demo "; private Static final string db_create = "create table" + table_name + "(_ id integer primary key autoincrement, name varchar (20), number varchar (10 ))"; public databasehelper (context) {super (context, db_name, null, db_version);}/*** create table */@ overridepublic void oncreate (sqlitedatabase db1_mongodb.exe csql (db_create );} /*** update table */@ overridepublic void onupgrade (sqlitedatabase dB, int oldversion, int newversion) {// db.exe csql ("Drop table if exists" + table_name ); // oncreate (db );}}

Create a database operation helper class databaseserver. Java

Import android. content. contentvalues; import android. content. context; import android. database. cursor; import android. database. SQLite. sqlitedatabase; public class databaseserver {private databasehelper dbhelper; Public databaseserver (context) {This. dbhelper = new databasehelper (context);}/***** insert data ** @ Param name * @ Param Number * Data * @ return returns true if the call succeeds, otherwise, false */Public Boolean insert (Str Ing name, string number) {// create or open the database sqlitedatabase DB = dbhelper. getwritabledatabase (); contentvalues CV = new contentvalues (); cv. put ("name", name); cv. put ("Number", number); // insert data, return the insert data idlong id = dB. insert (dbhelper. table_name, null, CV); If (ID! = 0) {return true;} return false ;} /***** update data ** @ Param ID * data column _ id * @ Param Number * quantity * @ return true if the operation succeeds, otherwise, false */Public Boolean Update (int id, string number) {sqlitedatabase DB = dbhelper. getwritabledatabase (); // The contetvalues that comes with Android. Similar to map, the put (string key, xxx value) method is provided to store data contentvalues CV = new contentvalues (); cv. put ("Number", number); // update the data table through contentvalues, and return the updated ID value int result = dB. updat E (dbhelper. table_name, CV, "_ id =? ", New string [] {string. valueof (ID)}); If (result! = 0) {return true;} return false;}/*** delete data ** @ Param ID * data column _ id * @ return */Public Boolean Delete (int id) {sqlitedatabase DB = dbhelper. getwritabledatabase (); // Delete the specified id value int result = dB. delete (dbhelper. table_name, "_ id =? ", New string [] {string. valueof (ID)}); If (result! = 0) {return true;} return false;}/*** query data ** @ return data list */Public cursor fetchall () {sqlitedatabase DB = dbhelper. getreadabledatabase (); // query all fields in the data table. query (dbhelper. table_name, null, "_ id DESC"); If (cursor! = NULL) {return cursor;} return NULL ;}}

Here we will insert, update, delete, and query the simple encapsulation, OK, and finally the activity class.

Import android. app. activity; import android. app. alertdialog; import android. content. dialoginterface; import android. database. cursor; import android. OS. bundle; import android. view. layoutinflater; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. listview; import android. widget. simplecursoradapter; import android. widget. toast; public class sqlitedemo extends activity implements onclicklistener {private button add_btn; private button update_btn; private button del_btn; private listview; private databaseserver dbserver; @ define void oncreate (bundle savedinstancestate) {// todo auto-generated method stubsuper. oncreate (savedinstancestate); setcontentview (R. layout. SQLite); add_btn = (button) findviewbyid (R. id. add_btn); add_btn.setonclicklistener (this); update_btn = (button) findviewbyid (R. id. update_btn); update_btn.setonclicklistener (this); del_btn = (button) findviewbyid (R. id. del_btn); del_btn.setonclicklistener (this); listview = (listview) findviewbyid (R. id. listview1); dbserver = new databaseserver (this); // custom method setinadapter ();} /*** match the data queried in the database into listview */private void setinadapter () {cursor = dbserver. fetchall (); simplecursoradapter adapter = new simplecursoradapter (this, R. layout. list_item, cursor, new string [] {"_ id", "name", "Number"}, new int [] {R. id. ID, R. id. name, R. id. number}); listview. setadapter (adapter) ;}@ overridepublic void onclick (view v) {Switch (v. GETID () {case R. id. add_btn: // insert data_add (); break; case R. id. update_btn: // data update data_update (); break; case R. id. del_btn: // data deletion data_delete (); break ;}/ *** Delete the main character */private void data_delete () {// extended, put delete_item.xml in the final view delete_view = layoutinflater. from (this ). inflate (R. layout. delete_item, null); alertdialog. builder dialog = new alertdialog. builder (this); dialog. settitle (""); // set the display view to delete_item.xmldialog.setview (delete_view); dialog. setpositivebutton ("OK", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {// obtain the edittext control edittext delete_id = (edittext) delete_view.findviewbyid (R. id. delete_id); // obtain the input ID. Int id = integer. parseint (delete_id.gettext (). tostring (); // call the data deletion method Boolean flag = dbserver. delete (ID); If (FLAG) {showtoast ("");} else {showtoast ("");} dialog. dismiss (); // call the custom method to update listviewsetinadapter () ;}}; dialog. setnegativebutton ("cancel", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {// the dialog box cancels the dialog. dismiss () ;}}); dialog. show ();}/*** update the number of monsters killed by the main character */private void data_update () {// same as final view update_view = layoutinflater. from (this ). inflate (R. layout. update_item, null); alertdialog. builder dialog = new alertdialog. builder (this); dialog. settitle ("update the number of active role kill IDs"); dialog. setview (update_view); dialog. setpositivebutton ("OK", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {edittext update_id = (edittext) update_view.findviewbyid (R. id. update_id); int id = integer. parseint (update_id.gettext (). tostring (); edittext update_number = (edittext) update_view.findviewbyid (R. id. update_number); string number_str = update_number.gettext (). tostring (); Boolean flag = dbserver. update (ID, number_str); If (FLAG) {showtoast ("");} else {showtoast ("");} dialog. dismiss (); setinadapter () ;}}); dialog. setnegativebutton ("cancel", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss () ;}}); dialog. show ();}/*** Add a principal method */private void data_add () {// same as final view add_view = layoutinflater. from (this ). inflate (R. layout. add_item, null); alertdialog. builder dialog = new alertdialog. builder (this); dialog. settitle ("add a leading role"); dialog. setview (add_view); dialog. setpositivebutton ("OK", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {edittext add_name = (edittext) add_view.findviewbyid (R. id. add_name); string name_str = add_name.gettext (). tostring (); edittext add_number = (edittext) add_view.findviewbyid (R. id. add_number); string number_str = add_number.gettext (). tostring (); Boolean flag = dbserver. insert (name_str, number_str); If (FLAG) {showtoast ("");} else {showtoast ("");} dialog. dismiss (); setinadapter () ;}}); dialog. setnegativebutton ("cancel", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss () ;}}); dialog. show ();}/** display toast */protected void showtoast (string) {toast. maketext (this, String, 1 ). show ();}}

This is a bit long. I hope you can finish reading it, but it is not that difficult. Here:

In the next chapter, we will introduce the unit test testcase in Android. Thank you. If you want the source code, please leave your email and I will send it to you in time.

 

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.