Example of using an Android SQLite database

Source: Internet
Author: User

In brief, today's mainstream mobile devices like Android, iphone and so on are using SQLite as a storage engine for complex data, when we develop applications for mobile devices, we may have to use SQLite to store our large amount of data, So we need to master the SQLite development techniques on mobile devices. For the Android platform, the system has built-in rich API for developers to operate SQLite, we can easily complete the access to data.


Below we use SQLite to develop an English dictionary. is the project structure ...


Mysqlite.java

Package Sn.qdj.sqlitedemo;import Android.content.context;import Android.database.databaseerrorhandler;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqlitedatabase.cursorfactory;import Android.database.sqlite.sqliteopenhelper;import android.util.log;/** * SQLite database operation * @author Qingdujun * */public class Mysqlite extends Sqliteopenhelper {/** * construct SQL statement CREATE TABLE */final String create_table_sql = "CREATE Table dict (UID integer prima Ry Key AutoIncrement, "+" word interge, "+" detail varchar) ";p ublic mysqlite (context context, String name, cursorfactory FAC Tory,int version) {Super (context, name, Factory, version);//TODO auto-generated constructor stub}public Mysqlite ( Context context, String name, cursorfactory factory,int version, Databaseerrorhandler ErrorHandler) {Super (context, name , factory, version, ErrorHandler);//TODO auto-generated constructor stub} @Overridepublic void OnCreate (sqlitedatabase db) {//the table Db.execsql (Create_table_sql) is automatically built when the database is used for the first time; LOG.I ("Create", "OK ");} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated method stub}}
Mainacticity.java

Package Sn.qdj.sqlitedemo;import Java.util.arraylist;import Java.util.hashmap;import java.util.map;import Android.app.activity;import Android.content.intent;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.os.bundle;import Android.util.log;import Android.view.View; Import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.toast;public class Mainactivity extends Activity {mysqlite dbhelpher; Button insert = null;    Button search = null;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main);        /** * Create Mysqlite object, specify database version 1 */dbhelpher = new Mysqlite (This, "mydict.db3", null,1);        Insert = (Button) Findviewbyid (R.id.btn_insert);        Search = (Button) Findviewbyid (R.id.btn_search); /** * Insert Event */Insert.setonclicklisTener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method stublog.i ("Insert", "fro NT "); String Word = ((EditText) Findviewbyid (R.id.et_word)). GetText (). toString (); String detail = ((EditText) Findviewbyid (R.id.et_detail)). GetText (). toString ();//INSERT Statement Myinsert ( Dbhelpher.getreadabledatabase (), Word, detail); LOG.I ("Insert", "after");        Toast.maketext (Getapplicationcontext (), "Insert succeeded", "N"). Show ();});  /** * Query Event */Search.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method stubstring key = ((EditText) Findviewbyid (R.id.et_word)). GetText (). toString (); String sql = "SELECT * from Dict WHERE is word like?" Or detail like? "; String selectionargs[] = {"%" +key+ "%", "%" +key+ "%"}; cursor cursor = Dbhelpher.getreadabledatabase (). Rawquery (SQL, Selectionargs);//Create a Bundle object bundle data = new bundle (); Data.putserializable ("Data", convercursortolist (cursor));//Create a intentintent intent = new IntenT (Mainactivity.this, Resultactivity.class); Intent.putextras (data);//Start activitystartactivity (intent);}}); } protected Arraylist<map<string, string>> convercursortolist (cursor cursor) {Arraylist<map<s    Tring, string>> result = new arraylist<map<string,string>> (); Traverse the result set while (Cursor.movetonext ()) {map<string, string> Map = new hashmap<string, string> (); Map.put ("word" , cursor.getstring (1)), Map.put ("detail", cursor.getstring (2)); Result.add (map);    return result;} /** * * @param db * @param word Word * @param detail explanation */private void Myinsert (Sqlitedatabase db    , string Word, string detail) {Db.execsql ("INSERT into dict values (null,?,?)", New String[]{word, detail});    } @Override public void OnDestroy () {Super.ondestroy ();    /** * When exiting the program, close Sqlitedatabase */if (dbhelpher! = null) {Dbhelpher.close ();} }}
Activity_main.xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: context= "Sn.qdj.sqlitedemo.MainActivity" > <edittext android:id= "@+id/et_word" android:layout_width = "Fill_parent" android:layout_height= "wrap_content" android:hint= "word"/> <edittext Android : id= "@+id/et_detail" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android: layout_below= "@id/et_word" android:hint= "detail"/> <button android:id= "@+id/btn_search" and Roid:layout_width= "Wrap_content" android:layout_height="Wrap_content" android:layout_alignparentright= "true" android:layout_alignparentbottom= "true" Android : text= "Query"/> <button android:id= "@+id/btn_insert" android:layout_width= "Wrap_content" Andro id:layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_alignparentbottom= "true "android:text=" Insert "/></relativelayout>
Resultactivity.java

Package Sn.qdj.sqlitedemo;import Java.util.list;import Java.util.map;import android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.widget.listview;import Android.widget.simpleadapter;public class Resultactivity extends Activity {@Override protected void onCreate (Bundle sav        Edinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.result);                ListView ListView = (ListView) Findviewbyid (R.id.show);        Intent Intent = Getintent ();        Gets the data Bundle that the intent carries, which is Intent.getextras (); Remove data from bundle list<map<string, string>> List = (list<map<string,string>>) Data.getserializ        Able ("data");        Encapsulates the list into Simpleadapter simpleadapter adapter = new Simpleadapter (resultactivity.this, list, R.layout.line,        New string[]{"word", "detail"},new int[]{r.id.word,r.id.detail}); Populate the ListView Listview.setadapter (adapter);}}
Result.xml

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent ">    <listview        android:id= "@+id/show"        android:layout_width= "match_parent"        android:layout_height= "Wrap_content" >    </ListView></RelativeLayout>
Line.xml

<?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/find" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layou T_alignparenttop= "true" android:text= "found word"/> <textview android:id= "@+id/word" Android:lay Out_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@id/find" Android        : text= "TextView"/> <textview android:id= "@+id/explain" android:layout_width= "Wrap_content"         android:layout_height= "Wrap_content" android:layout_below= "@id/word" android:text= "explanation"/> <TextView        Android:id= "@+id/detail" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_below= "@id/exPlain "android:text=" "/></relativelayout> 
Mainifest.xml

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Sn.qdj.sqlitedemo "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "android:targetsdkversion=" "/> <application android:allowbackup=" Tru E "android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "android:theme=" @style/appthe Me "> <activity android:name=". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <activity android:name=". Resultactivity "android:label=" @string/app_name "> </activity> &LT;/APPLICATION&GT;&LT;/manifest> 

Download the source code, please click here!

Reference: "Crazy Android Handout (2nd edition)" by Li Gang


Example of using an Android SQLite database

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.