手机版
你好,游客 登录 注册
背景:
阅读新闻

Android 数据存储和IO

SQLite(三)

[日期:2012-05-27] 来源:Linux社区  作者:tianfeng [字体:大 中 小]

该实例是用户将自己不熟悉的单词添加到数据库中,当用户需要查询某个单词或是解释时,在相应的文本框中输入相应的关键词,就会出来相应的结果。

本实例主要是用来学习,只是实现了简单的添加和模糊查询,提供一条思路。(很多Bolg上都有类似的例子,如有雷同,纯属巧合吐舌头)

上代码:

1. 布局文件的主界面:dict_sqlite.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:Android="http://schemas.android.com/apk/res/android"  
  4.   android:orientation="vertical"  
  5.   android:layout_width="fill_parent"  
  6.   android:layout_height="fill_parent">  
  7.     
  8.   <EditText  
  9.   android:id="@+id/word"  
  10.   android:layout_width="fill_parent"  
  11.   android:layout_height="wrap_content"  
  12.   android:focusable="true"  
  13.   android:hint="生词"  
  14.   />  
  15.     
  16.   <EditText  
  17.   android:id="@+id/detail"  
  18.   android:layout_width="fill_parent"  
  19.   android:layout_height="wrap_content"  
  20.   android:hint="生词解释"   
  21.   />  
  22.   <Button  
  23.   android:id="@+id/insert"  
  24.   android:layout_width="wrap_content"  
  25.   android:layout_height="wrap_content"  
  26.   android:text="添加生词"  
  27.   />    
  28.   <EditText  
  29.   android:id="@+id/key"  
  30.   android:layout_width="fill_parent"  
  31.   android:layout_height="wrap_content"  
  32.   />  
  33.   <Button  
  34.   android:id="@+id/search"  
  35.   android:layout_width="wrap_content"  
  36.   android:layout_height="wrap_content"  
  37.   android:text="查找 "  
  38.   />  
  39.     
  40. </LinearLayout>  

2.查询结果的ListView的布局文件:popup.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:orientation="vertical"  
  5.   android:layout_width="fill_parent"  
  6.   android:layout_height="fill_parent">  
  7.     
  8.   <ListView  
  9.   android:id="@+id/show_dict"  
  10.   android:layout_width="fill_parent"  
  11.   android:layout_height="fill_parent"  
  12.   />  
  13.     
  14. </LinearLayout>  

3. 查询结果中ListView中适配器的布局文件:line.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:orientation="vertical"  
  5.   android:layout_width="fill_parent"  
  6.   android:layout_height="fill_parent">  
  7.  <TextView  
  8.    android:id="@+id/textView_Result_Dict"   
  9.    android:layout_width="wrap_content"  
  10.    android:layout_height="wrap_content"  
  11.    android:text="找到的单词"  
  12.  />  
  13.  <EditText  
  14.  android:id="@+id/word_result_dict"  
  15.  android:layout_width="fill_parent"  
  16.  android:layout_height="wrap_content"  
  17.  />  
  18.  <TextView  
  19.  android:layout_width="fill_parent"  
  20.  android:layout_height="wrap_content"  
  21.  android:text="解释"  
  22.  />  
  23.  <EditText  
  24.  android:id="@+id/detail_result_dict"  
  25.  android:layout_width="fill_parent"  
  26.  android:layout_height="wrap_content"  
  27.  />  
  28. </LinearLayout>  

4. 主程序的代码:

(1.) 自定义的SQLiteOpenHelper的子类来管理数据库的连接:MyDatabaseHelper.Java:

  1. package com.infy.configuration;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  7.   
  8. public class MyDatabaseHelper extends SQLiteOpenHelper{  
  9.   
  10.     final String CREATE_TABLE_SQL="create table dict(_id integer primary key autoincrement,word,detail)";  
  11.       
  12.     public MyDatabaseHelper(Context context, String name,  
  13.             CursorFactory factory, int version) {  
  14.         super(context, name, factory, version);  
  15.         // TODO Auto-generated constructor stub   
  16.     }  
  17.   
  18.     @Override  
  19.     public void onCreate(SQLiteDatabase db) {  
  20.         // TODO Auto-generated method stub   
  21.         //第一个使用数据库时自动建表   
  22.         db.execSQL(CREATE_TABLE_SQL);  
  23.           
  24.     }  
  25.   
  26.     @Override  
  27.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  28.         // TODO Auto-generated method stub         
  29.     }  
  30.   
  31. }  

(2.) 主界面的代码:Dict.java:

  1. package com.infy.configuration;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import android.app.Activity;  
  8. import android.content.Intent;  
  9. import android.database.Cursor;  
  10. import android.database.sqlite.SQLiteDatabase;  
  11. import android.os.Bundle;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.widget.Button;  
  15. import android.widget.EditText;  
  16. import android.widget.Toast;  
  17.   
  18. public class Dict extends Activity{  
  19.   
  20.     MyDatabaseHelper dbHelper;  
  21.     Button insert= null;  
  22.     Button search = null;  
  23.       
  24.       
  25.     @Override  
  26.     protected void onCreate(Bundle savedInstanceState) {  
  27.         // TODO Auto-generated method stub   
  28.         super.onCreate(savedInstanceState);  
  29.         setContentView(R.layout.dict_sqlite);  
  30.         //创建MyDatabaseHelper对象,指定数据库版本为1,此处使用相对路径即可数据库文件会自动保存在程序的数据文件夹的database目录下   
  31.         dbHelper = new MyDatabaseHelper(this, "my_Dict.db3", null, 1);  
  32.           
  33.         insert = (Button)findViewById(R.id.insert);  
  34.         search = (Button)findViewById(R.id.search);  
  35.         final EditText word = (EditText)findViewById(R.id.word);  
  36.         final EditText detail =(EditText)findViewById(R.id.detail);  
  37.         final EditText key=(EditText)findViewById(R.id.key);  
  38.           
  39.         //插入生词的操作   
  40.         insert.setOnClickListener(new OnClickListener() {  
  41.               
  42.             @Override  
  43.             public void onClick(View v) {  
  44.                 // TODO Auto-generated method stub   
  45.                 //获取用户的输入   
  46.                 String word_user= word.getText().toString();  
  47.                 String detail_word=detail.getText().toString();  
  48.                   
  49.                 //插入生词记录   
  50.                 insertData(dbHelper.getReadableDatabase(),word_user,detail_word);  
  51.                   
  52.                 //提示信息   
  53.                 Toast.makeText(Dict.this, "添加生词成功!", Toast.LENGTH_LONG).show();  
  54.             }  
  55.         });  
  56.           
  57.         //收索生词的记录   
  58.         search.setOnClickListener(new OnClickListener() {  
  59.               
  60.             @Override  
  61.             public void onClick(View v) {  
  62.                 // TODO Auto-generated method stub   
  63.             //获取用户的输入   
  64.             String key_user = key.getText().toString();  
  65.                   
  66.             //执行查询操作   
  67.             Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select *from dict where word like ? or detail like ?", new String[]{  
  68.                     "%" +key_user +"%" ,"%" +key +"%"});  
  69.               
  70.             //创建一个Bundle对象   
  71.             Bundle data = new Bundle();  
  72.             data.putSerializable("data", converCursorToList(cursor));  
  73.             //创建一个Intent   
  74.             Intent intent = new Intent(Dict.this,ResultActivity.class);  
  75.               
  76.             intent.putExtras(data);  
  77.             startActivity(intent);  
  78.             }  
  79.         });  
  80.       
  81.     }  
  82.     //把cursor转化成list   
  83.     protected ArrayList<Map<String, String> > converCursorToList(Cursor cursor){  
  84.         ArrayList<Map<String, String>> result = new ArrayList<Map<String,String>>();  
  85.         //遍历Cursor结果集   
  86.         while(cursor.moveToNext()){  
  87.             //将结果集集中地数据存入Arraylist中   
  88.             Map<String,String> map = new HashMap<String, String>();  
  89.             map.put("word", cursor.getString(1));  
  90.             map.put("detail", cursor.getString(2));  
  91.             result.add(map);  
  92.         }  
  93.         return result;  
  94.           
  95.     }  
  96.       
  97.     private void insertData(SQLiteDatabase db,String word,String detail){  
  98.         //执行插入语句   
  99.         db.execSQL("insert into dict values(null,?,?)",new String[]{word,detail});  
  100.     }  
  101.       
  102.     @Override  
  103.     protected void onDestroy() {  
  104.         // TODO Auto-generated method stub   
  105.         super.onDestroy();  
  106.     //退出程序时关闭MyDatabaseHelper里的SQLiterDatabse   
  107.         if(dbHelper != null){  
  108.             dbHelper.close();  
  109.         }  
  110.       
  111.     }  
  112.       
  113.       
  114. }  

(3.)查询结果的代码:ResultActivity.java

  1. package com.infy.configuration;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import android.app.Activity;  
  7. import android.content.Intent;  
  8. import android.os.Bundle;  
  9. import android.widget.ListView;  
  10. import android.widget.SimpleAdapter;  
  11.   
  12. public class ResultActivity extends Activity {  
  13.   
  14.     @Override  
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         // TODO Auto-generated method stub   
  17.         super.onCreate(savedInstanceState);  
  18.       
  19.         setContentView(R.layout.popup);  
  20.           
  21.         ListView listView = (ListView)findViewById(R.id.show_dict);  
  22.       
  23.         Intent intent = getIntent();  
  24.           
  25.         //获取该Intent中的数据   
  26.         Bundle data = intent.getExtras();  
  27.           
  28.         //从Bundle数据包中获取数据   
  29.         @SuppressWarnings("unchecked")  
  30.         List<Map<String, String>> list = (List<Map<String,String>>)data.getSerializable("data");  
  31.           
  32.         //将List封装成SimpleAdapter   
  33.         SimpleAdapter adapter = new SimpleAdapter(ResultActivity.this,list,R.layout.line,new String[]{"word","detail"},new int[]{R.id.word_result_dict,R.id.detail_result_dict});  
  34.         //填充ListView   
  35.         listView.setAdapter(adapter);  
  36.     }  
  37.       
  38. }  

上面的ResultActivity设为了对话框风格的Activitiy.以对话框的方式来显示查询结果。

清单文件AndroidManifest.xml为:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.infy.configuration"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".Dict"  
  8.                     
  9.                   android:label="@string/app_name">  
  10.             <intent-filter>  
  11.                 <action android:name="android.intent.action.MAIN" />  
  12.                 <category android:name="android.intent.category.LAUNCHER" />  
  13.             </intent-filter>  
  14.         </activity>  
  15.       <activity android:name=".ResultActivity" android:theme="@android:style/Theme.Dialog"/>  
  16.     </application>  
  17.     <uses-sdk android:minSdkVersion="8" />  
  18.     <uses-permission android:name ="android.permission.INTERENT"/>  
  19.  </manifest>   

结果图:

(1.)添加生词的界面:

(2.))查询结果的界面:在查找按钮上面的文本框中输入P字母,点击查找按钮将出现如下查询结果的界面:

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
【内容导航】
第1页:SharedPreferences 第2页:SQLite(二)
第3页:SQLite(三)
相关资讯       Android编程入门 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款