Android SQLite database use example, androidsqlite

Source: Internet
Author: User

Android SQLite database use example, androidsqlite

For a brief introduction, mainstream mobile devices such as Android and iPhone all use SQLite as the storage engine for complex data. When we develop applications for mobile devices, we may need to use SQLite to store a large amount of data, so we need to master the SQLite development skills on mobile devices. For the Android platform, the system has built-in rich APIs for developers to operate SQLite. We can easily access data.


Now 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 an SQL statement to CREATE a TABLE */final String CREATE_TABLE_ SQL = "CREATE TABLE dict (uid integer primary key autoincrement, "+" word interge, "+" detail varchar) "; public MySQLite (Context context, String name, CursorFactory factory, 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.exe cSQL (CREATE_TABLE_ SQL) is automatically created when the data library is used for the first time. 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. E DitText; 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 a MySQLite object and specify the database version as 1 */dbHelpher = new MySQLite (this, "myDict. db3 ", null, 1); insert = (Button) findViewById (R. I D. 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", "front"); 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 (), "inserted successfully", 800 ). 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 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 an IntentIntent intent = new Intent (MainActivity. this, ResultActivity. class); intent. putExtras (data); // start ActivitystartActivity (intent) ;}});} protected ArrayList <Map <Strin G, String> converCursorToList (Cursor cursor) {ArrayList <Map <String, 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 * @ param detail explanation */private void myI Nsert (SQLiteDatabase db, String word, String detail) {db.exe cSQL ("insert into dict values (null ,?,?) ", New String [] {word, detail}) ;}@ Override public void onDestroy () {super. onDestroy ();/*** 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: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" 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" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignParentRight = "true" android: layout_alignParentBottom = "true" android: text = ""/> <Button android: id = "@ + id/btn_insert" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignParentLeft = "true" android: Allow = "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 savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. result); ListView listView = (ListView) findViewById (R. id. show); Intent intent = getIntent (); // gets the data Bundle data = intent. getExtras (); // retrieve data from Bundle List <Map <String, String> list = (List <Map <String, String>) data. getSerializable ("data"); // encapsulate the List into SimpleAdapter adapter = new SimpleAdapter (ResultActivity. this, list, R. layout. line, new String [] {"word", "detail"}, new int [] {R. id. word, R. id. detail}); // fill the 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: layout_alignParentTop = "true" android: text = "words found"/> <TextView android: id = "@ + id/word" android: layout_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 = ""/> <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="15"        android:targetSdkVersion="15" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <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>    </application></manifest>

Click here to download the source code!

References: edited by Li Gang, crazy Android handout (version 2nd)


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.