Sqlitedatabase help use of sqliteopenhelper

Source: Internet
Author: User

Sqliteopenhelper is a help class for sqlitedatabse to manage data creation and version updates. The general usage is to define a class that inherits sqliteopenhelper and implement two callback Methods: oncreate (sqlitedatabase dB) and onupgrade (sqlitedatabse, int oldversion, int newversion) to create and update databases, I used the database to provide a function similar to a telephone book, which inserts data, queries data, and deletes data. The interface is ugly. It mainly explains the usage of the sqliteopenhelper class, as shown below:

 

First, we create a dbhelper inherited from sqliteopenhelper, which is a help class of the database.

Package COM. example. utils; import android. content. contentvalues; import android. content. context; import android. database. cursor; import android. database. SQLite. sqlitedatabase; import android. database. SQLite. sqlitedatabase. cursorfactory; import android. database. SQLite. sqliteopenhelper; public class dbhelper extends sqliteopenhelper {private final static int version = 1; private final static string db_name = "Phones. DB "; private final static string table_name =" phone "; private final static string create_tbl =" create table phone (_ id integer primary key autoincrement, Name text, sex text, number text, desc text) "; private sqlitedatabase dB; // a required constructor for the sqliteopenhelper subclass public dbhelper (context, string name, cursorfactory factory, int Version) {// The constructor super (context, name, factory, Ver) of the parent class must be called through Super Sion);} // database constructor. Public dbhelper (context, string name, int version) {This (context, name, null, version);} // database constructor. If a parameter is passed, the database name and version number are all written to public dbhelper (context) {This (context, db_name, null, version);} // callback function. This function is called only during the first creation to create a database @ overridepublic void oncreate (sqlitedatabase dB) {This. DB = dB; system. out. println ("create database" using mongodb.exe csql (create_tbl);} // callback function. When you construct The passed version and previous version call this function @ overridepublic void onupgrade (sqlitedatabase dB, int oldversion, int newversion) {system. out. println ("Update Database");} // Insertion Method public void insert (contentvalues values) {// obtain sqlitedatabase instance sqlitedatabase DB = getwritabledatabase (); // Insert the database. insert (table_name, null, values); dB. close () ;}// query method public cursor query () {sqlitedatabase DB = getreadabledatabase (); // obtain cursorcursor C = dB. query (table_name, null, null); Return C ;}// Delete public void Delete (int id) data based on the unique identifier _ id) {sqlitedatabase DB = getwritabledatabase (); dB. delete (table_name, "_ id =? ", New string [] {string. valueof (ID)});} // update public void Update (contentvalues values, string whereclause, string [] whereargs) {sqlitedatabase DB = getwritabledatabase (); dB. update (table_name, values, whereclause, whereargs);} // close the public void close () {If (DB! = NULL) {dB. Close ();}}}

The first mainactivity

Package COM. example. phonebooks; import android. app. activity; import android. content. contentvalues; import android. content. intent; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. radiobutton; import android. widget. radiogroup; import android. widget. radiogroup. oncheckedchangelistener; Import android. widget. toast; import COM. example. utils. dbhelper; public class mainactivity extends activity implements onclicklistener {private dbhelper; // define three input boxes private edittext name, number, DESC; // define two buttons private button submit, look; // define a radiogroupprivate radiogroup radio; private string namestr, numberstr, descstr; private string sexstr = "male"; @ overrideprotected void oncreate (bundle savedinst Ancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); // instantiate dbhelperdbhelper = new dbhelper (this); // obtain the corresponding control name = (edittext) findviewbyid (R. id. edittext1); number = (edittext) findviewbyid (R. id. edittext2); DESC = (edittext) findviewbyid (R. id. edittext3); Submit = (button) findviewbyid (R. id. button1); look = (button) findviewbyid (R. id. button2); Radio = (radiogroup) findviewb Yid (R. id. radiogroup1); // click the button to set the listener to submit. setonclicklistener (this); look. setonclicklistener (this); // listener for radio groups. setoncheckedchangelistener (New oncheckedchangelistener () {@ overridepublic void oncheckedchanged (radiogroup group, int checkedid) {If (checkedid = R. id. radio0) {radiobutton r = (radiobutton) group. findviewbyid (checkedid); sexstr = R. gettext (). tostring ();} If (checkedid = R. id. radio1) {radiobutto N r = (radiobutton) group. findviewbyid (checkedid); sexstr = R. gettext (). tostring () ;}}) ;}@ overridepublic void onclick (view v) {Switch (v. GETID () {case R. id. button1: If (name. gettext (). tostring (). length ()! = 0) {namestr = Name. gettext (). tostring ();} else {toast. maketext (getapplication (), "name cannot be blank", toast. length_short ). show (); return;} If (number. gettext (). tostring (). length ()! = 0) {numberstr = number. gettext (). tostring ();} else {toast. maketext (getapplication (), "the phone number cannot be blank", toast. length_short ). show (); return;} If (DESC. gettext (). tostring (). length ()! = 0) {descstr = DESC. gettext (). tostring ();} else {toast. maketext (getapplication (), "remarks cannot be blank", toast. length_short ). show (); return;} // instantiate a contentvalues. contentvalues is in the form of a key-value pair, and the key is the name of the database column, the value is the value contentvalues values = new contentvalues (); values. put ("name", namestr); values. put ("sex", sexstr); values. put ("Number", numberstr); values. put ("DESC", descstr); // call insert to insert database dbhelper. insert (values); // reset the reset (); break; case R. id. button2: intent = new intent (); intent. setflags (intent. flag_activity_clear_top); intent. setclass (this, resultactivity. class); startactivity (intent); break; default: Break ;}// reset edittextprivate void reset () {name. settext (""); number. settext (""); DESC. settext ("");}}

Activity_main.xml

<Relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Background = "#000000"> <textview Android: id = "@ + ID/textview1" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_alignparentleft = "true" Android: layout_alignparenttop = "true" Android: TEXT = "name" Android: textsize = "15 DP "/> <edittext Android: Id =" @ + ID/edittext1 "Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "Android: layout_alignparentleft =" true "Android: layout_alignparentright = "true" Android: layout_below = "@ + ID/textview1" Android: EMS = "10"> <requestfocus/> </edittext> <radiogroup Android: id = "@ + ID/radiogroup1" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" android Oid: layout_alignparentleft = "true" Android: layout_below = "@ + ID/edittext1"> <radiobutton Android: Id = "@ + ID/radio0" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: checked = "true" Android: text = "male"/> <radiobutton Android: id = "@ + ID/radio1" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_aligntop = "@ + ID/radiogroup1" Android: layout_tor Ightof = "@ + ID/textview2" Android: text = ""/> </radiogroup> <textview Android: Id = "@ + ID/textview2" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_alignparentleft = "true" Android: layout_below = "@ + ID/radiogroup1" Android: TEXT = "phone number"/> <edittext Android: Id = "@ + ID/edittext2" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_alig Nparentleft = "true" Android: layout_alignparentright = "true" Android: layout_below = "@ + ID/textview2" Android: EMS = "10"/> <textview Android: id = "@ + ID/textview3" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_alignparentleft = "true" Android: layout_below = "@ + ID/edittext2" Android: text = "Remarks"/> <edittext Android: Id = "@ + ID/edittext3" Android: layout_width = "wrap_content" Droid: layout_height = "wrap_content" Android: layout_alignparentleft = "true" Android: layout_alignparentright = "true" Android: layout_below = "@ + ID/textview3" Android: lines = "5" Android: EMS = "10" Android: inputtype = "textmultiline"/> <button Android: Id = "@ + ID/button2" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_alignparentbottom = "true" Android: layout_alignparentleft = "True" Android: layout_alignparentright = "true" Android: text = ""/> <button Android: Id = "@ + ID/button1" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: Rule = "true" Android: layout_alignparentright = "true" Android: layout_below = "@ + ID/edittext3" Android: TEXT = "insert"/> </relativelayout> uses a person class to encapsulate the data such as name, gender, phone number, and remarks. There are only get () and set () methods.
Package COM. example. mode; public class person {private string name; private string sex; private string number; private string DESC; private int _ id; Public int get_id () {return _ id ;} public void set_id (INT _ id) {This. _ id = _ id;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} Public String getsex () {return sex;} public void setsex (string sex) {This. sex = sex;} Public String getnumber () {return number;} public void setnumber (string number) {This. number = number;} Public String getdesc () {return DESC;} public void setdesc (string DESC) {This. desc = DESC ;}} view the resultactivity of the data
Package COM. example. phonebooks; import Java. util. arraylist; import Java. util. list; import android. app. activity; import android. app. alertdialog; import android. content. context; import android. content. dialoginterface; import android. content. dialoginterface. onclicklistener; import android. database. cursor; import android. OS. bundle; import android. view. layoutinflater; import android. view. view; import android. view. V Iewgroup; import android. widget. adapterview; import android. widget. adapterview. onitemclicklistener; import android. widget. baseadapter; import android. widget. listview; import android. widget. textview; import COM. example. mode. person; import COM. example. utils. dbhelper; public class resultactivity extends activity implements onitemclicklistener {private listview; private dbadapter adapter; dbhelper dbel Per; List <person> booklist = new arraylist <person> (); @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. result); // obtain listviewlistview = (listview) findviewbyid (R. id. listview1); booklist = querydata (); // instantiate dbadapteradapter = new dbadapter (getapplication (), booklist); listview. setadapter (adapter); listview. setonitemclicklistener (this );}/ /Query the database, encapsulate each row of data into a person object, and then add the object to the list private list <person> querydata () {list <person> List = new arraylist <person> (); dbhelper = new dbhelper (this); // call query () to obtain cursorcursor c = dbhelper. query (); While (C. movetonext () {int _ id = C. getint (C. getcolumnindex ("_ id"); string name = C. getstring (C. getcolumnindex ("name"); string sex = C. getstring (C. getcolumnindex ("sex"); string number = C. getstring (C. getco Lumnindex ("Number"); string DESC = C. getstring (C. getcolumnindex ("DESC"); // use a person object to encapsulate the queried data person P = new person (); p. set_id (_ id); p. setname (name); p. setsex (sex); p. setnumber (number); p. setdesc (DESC); list. add (p) ;}return list ;}// customize dbadapterpublic class dbadapter extends baseadapter {private list <person> list; private context; private layoutinflater; Public dbadapter (context cont EXT, list <person> List) {layoutinflater = layoutinflater. from (context); this. context = context; this. list = List;} // refresh the adapter public void refresh (list <person> List) {This. list = List; policydatasetchanged () ;}@ overridepublic int getcount () {return list. size () ;}@ overridepublic object getitem (INT position) {return list. get (position) ;}@ overridepublic long getitemid (INT position) {return position ;}@ overridepubli C view getview (INT position, view convertview, viewgroup parent) {person P = List. get (position); viewholder holder; If (convertview = NULL) {holder = new viewholder (); convertview = layoutinflater. inflate (R. layout. item, null); holder. name = (textview) convertview. findviewbyid (R. id. textview1); holder. sex = (textview) convertview. findviewbyid (R. id. textview2); holder. number = (textview) convertview. findvie Wbyid (R. id. textview3); holder. desc = (textview) convertview. findviewbyid (R. id. textview4); convertview. settag (holder);} else {holder = (viewholder) convertview. gettag ();} holder. name. settext (P. getname (); holder. sex. settext (P. getsex (); holder. number. settext (P. getnumber (); holder. desc. settext (P. getdesc (); Return convertview;} public class viewholder {public textview name; Public textview sex; Public textvi EW number; Public textview DESC; Public textview ID; }}@ overridepublic void onitemclick (adapterview <?> Parent, view, final int position, long ID) {final person P = Booklist. get (position); Final long temp = ID; alertdialog. builder = new alertdialog. builder (this); builder. setmessage ("are you sure you want to delete this record? "). Setpositivebutton ("yes", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {// call Delete () to delete a data record dbhelper. delete (P. get_id (); // refresh the adapter. refresh (querydata ());}}). setnegativebutton ("no", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which ){}}). create (). show (); // disable dbhelper. close () ;}display the Data Layout result. XML, which contains only one listview
<?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <ListView        android:id="@+id/listView1"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_alignParentLeft="true"        android:cacheColorHint="#00000000"        android:layout_alignParentTop="true" >    </ListView></RelativeLayout>

Item of listview

<?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:text="TextView" />    <TextView        android:id="@+id/textView3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_above="@+id/textView4"        android:layout_alignParentRight="true"        android:text="TextView" />    <TextView        android:id="@+id/textView2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_above="@+id/textView4"        android:layout_centerHorizontal="true"        android:text="TextView" />    <TextView        android:id="@+id/textView4"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true"        android:layout_below="@+id/textView1"        android:layout_marginTop="19dp"        android:text="TextView" /></RelativeLayout>
Do not forget to register resultactivity in androidmanifest. xml.

Download project code
 

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.