第66章、使用SQLite本地数据库(从零开始学Android)

  在Android平台上,集成了一个嵌入式关系型数据库—SQLite。以SQLite是一款轻型数据库:SQLite3支持 NULL、INTEGER、REAL(浮点数字)、TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的类型只有五种,但实际上sqlite3也接受varchar(n)、char(n)、decimal(p,s) 等数据类型,只不过在运算或保存时会转成对应的五种数据类型。

  SQLite可以解析大部分标准SQL语句。

 

一、设计界面

  1、布局文件

  打开res/layout/activity_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"
 	 android:background="#EFEFEF">

	<TextView  
	  	android:layout_width="fill_parent" 
	  	android:layout_height="wrap_content" 
 	 	android:text="@string/prompt"
 	  	android:textColor="@drawable/black" />
     
 	 <EditText  
 	 	android:id="@+id/editbook" 
 	 	android:layout_width="fill_parent" 
 		android:layout_height="wrap_content" 
 	  	android:textColor="@drawable/black" />
  
 	 <TextView  
  		android:layout_width="fill_parent" 
  		android:layout_height="wrap_content" 
  		android:text="作者:"
 		android:textColor="@drawable/black" />
     
  	<EditText  
 		 android:id="@+id/editauthor" 
 		 android:layout_width="fill_parent" 
  		 android:layout_height="wrap_content" 
 		 android:textColor="@drawable/black" />
  
 	 <TextView  
		 android:layout_width="fill_parent" 
 		 android:layout_height="wrap_content" 
  		 android:text="出版社:"
  		 android:textColor="@drawable/black" />
     
  	<EditText  
  		android:id="@+id/editpublisher" 
  		android:layout_width="fill_parent" 
  		android:layout_height="wrap_content" 
  		android:textColor="@drawable/black" />
 
  	<ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/black" />


</LinearLayout>

  2、自定义列表文件

  打开res/layout/list.xml文件。
  输入以下代码:

<?xml version="1.0" encoding="utf-8"?>
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
 
  <CheckedTextView android:id="@+id/textbookname"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />

  <ImageView
      android:id="@+id/imageView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@drawable/list_driver" />
 
   
   <CheckedTextView android:id="@+id/textauthor"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
 
   <ImageView
      android:id="@+id/imageView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@drawable/list_driver" />

   <CheckedTextView android:id="@+id/textpublisher"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
 
</LinearLayout>

  3、颜色文件

  打开res/values/color.xml文件。
  输入以下代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <drawable name="black">#000000</drawable>
  <drawable name="white">#FFFFFFFF</drawable>
  <drawable name="gray">#EFEFEF</drawable>
</resources>

  4、字符串文件

  打开res/values/string.xml文件。
  输入以下代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SQLite</string>
    <string name="prompt">书名:(请使用菜单:完成新增、修改、查询、刪除记录)</string>
    <string name="addrec">新增</string>
  	<string name="editrec">修改</string>
    <string name="queryrec">查询</string>
    <string name="delrec">刪除</string>

</resources>

二、程序文件

  1、SQLiteHelper.java文件

  打开“src/com.genwoxue.sqlite/SQLiteHelper.java”文件。
  然后输入以下代码:

package com.genwoxue.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
public class SQLiteHelper extends SQLiteOpenHelper {

       private final static String DATABASE_NAME = "Library";
       private final static int DATABASE_VERSION = 1;
       private final static String TABLE_NAME = "Book";
 
       //构造函数,创建数据库
       public SQLiteHelper(Context context) {
              super(context, DATABASE_NAME, null, DATABASE_VERSION);
       }
 
       //建表
       public void onCreate(SQLiteDatabase db) {
              String sql = "CREATE TABLE " + TABLE_NAME 
            		  + "(_id INTEGER PRIMARY KEY," 
            		  + " BookName VARCHAR(30)	NOT NULL," 
            		  + " Author VARCHAR(20),"
            		  + " Publisher VARCHAR(30))";
              db.execSQL(sql);
       }
 
 
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
              String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
              db.execSQL(sql);
              onCreate(db);
       }
 
       //获取游标
       public Cursor select() {
              SQLiteDatabase db = this.getReadableDatabase();
              Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
              return cursor;
       }
 
       //插入一条记录
       public long insert(String bookName,String author,String publisher ) {
              SQLiteDatabase db = this.getWritableDatabase();
              ContentValues cv = new ContentValues();
              cv.put("BookName", bookName);
              cv.put("Author", author);
              cv.put("Publisher", publisher);
              long row = db.insert(TABLE_NAME, null, cv);
              return row;
       }
       
       //根据条件查询
       public Cursor query(String[] args) {
           SQLiteDatabase db = this.getReadableDatabase();
           Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE BookName LIKE ?", args);
           return cursor;
       }
 
       //删除记录
       public void delete(int id) {
              SQLiteDatabase db = this.getWritableDatabase();
              String where ="_id = ?";
              String[] whereValue = { Integer.toString(id) };
              db.delete(TABLE_NAME, where, whereValue);
       }
 
       //更新记录
       public void update(int id, String bookName,String author,String publisher) {
              SQLiteDatabase db = this.getWritableDatabase();
              String where = "_id = ?";
              String[] whereValue = { Integer.toString(id) };
              ContentValues cv = new ContentValues();
              cv.put("BookName", bookName);
              cv.put("Author", author);
              cv.put("Publisher", publisher);
              db.update(TABLE_NAME, cv, where, whereValue);
       }
}

  2、MainActivity.java文件

  打开“src/com.genwoxue.sqlite/MainActivity.java”文件。
  然后输入以下代码:

package com.genwoxue.sqlite;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends Activity {
	private SQLiteHelper helper;
    private Cursor cursor;
    private ListView lvBook;
    private EditText editBook;
    private EditText editAuthor;
    private EditText editPublisher;
    
    private int id=0;
    
    protected final static int MENU_ADD = Menu.FIRST;
    protected final static int MENU_EDIT = Menu.FIRST + 1;
    protected final static int MENU_QUERY = Menu.FIRST + 2;
    protected final static int MENU_DELETE = Menu.FIRST + 3;

    //执行菜单选项
    public boolean onOptionsItemSelected(MenuItem item)
    {
      super.onOptionsItemSelected(item);
      switch (item.getItemId())
      {
        case MENU_ADD:
          this.addRec();
          break;
        case MENU_EDIT:
          this.editRec();
          break;
        case MENU_QUERY:
            this.queryRec();
            break;
        case MENU_DELETE:
          this.deleteRec();
          break;
      }
      return true;
    }

    //初始化菜单
    public boolean onCreateOptionsMenu(Menu menu)
    {
      super.onCreateOptionsMenu(menu);
      menu.add(Menu.NONE, MENU_ADD, 0, R.string.addrec).setIcon(android.R.drawable.ic_menu_add);
      menu.add(Menu.NONE, MENU_EDIT, 0, R.string.editrec).setIcon(android.R.drawable.ic_menu_edit);
      menu.add(Menu.NONE,MENU_QUERY,0,R.string.queryrec).setIcon(android.R.drawable.ic_menu_search);
      menu.add(Menu.NONE, MENU_DELETE, 0, R.string.delrec).setIcon(android.R.drawable.ic_menu_delete);
      return true;
    }



    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      lvBook = (ListView) this.findViewById(R.id.listview);
      editBook = (EditText) this.findViewById(R.id.editbook);
      editAuthor=(EditText) this.findViewById(R.id.editauthor);
      editPublisher=(EditText) this.findViewById(R.id.editpublisher);
      
      //表中内容填充到自定义ListView
      helper = new SQLiteHelper(this);
      cursor = helper.select();
      SimpleCursorAdapter adapter = new SimpleCursorAdapter(
    		  this, 
              R.layout.list, 
              cursor, 
              new String[] {"BookName","Author","Publisher"}, 
              new int[] { R.id.textbookname,R.id.textauthor,R.id.textpublisher}
    		  );
      lvBook.setAdapter(adapter);

      // lvBook设置OnItemClickListener监听事件 
      lvBook.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    	  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
    		  cursor.moveToPosition(arg2);			// 将cursor移到所点击的值 
    		  id = cursor.getInt(0);				// 取得字段_id的值 
    		  editBook.setText(cursor.getString(1));	// 取得字段Rec_text的值 
    		  editAuthor.setText(cursor.getString(2));
    		  editPublisher.setText(cursor.getString(3));
    	  }
      });

    }

    //添加记录
    private void addRec()
    {
      if (editBook.getText().toString().equals(""))
    	  return;
      helper.insert(editBook.getText().toString(),editAuthor.getText().toString(),editPublisher.getText().toString());	
      //重新加载数据
      cursor.requery();
      lvBook.invalidateViews();
      editBook.setText("");
      editAuthor.setText("");
      editPublisher.setText("");
    }

    // 修改记录
    private void editRec()
    {
      if (editBook.getText().toString().equals(""))
        return;
      helper.update(id, editBook.getText().toString(),editAuthor.getText().toString(),editPublisher.getText().toString());
      
      //重新加载数据
      cursor.requery();
      lvBook.invalidateViews();
      editBook.setText("");
      editAuthor.setText("");
      editPublisher.setText("");
    }

    //根据书名查询
    private void queryRec()
    {
      String et=editBook.getText().toString();
      String args[]=new String[]{"%"+et+"%"};
      cursor=helper.query(args);
      SimpleCursorAdapter adapter = new SimpleCursorAdapter(
    		  this, 
              R.layout.list, 
              cursor, 
              new String[] {"BookName","Author","Publisher"}, 
              new int[] { R.id.textbookname,R.id.textauthor,R.id.textpublisher}
    		  );
      lvBook.setAdapter(adapter);
    }
    
    //删除记录
    private void deleteRec()
    {
      helper.delete(id);
      cursor.requery();
      lvBook.invalidateViews();
      editBook.setText("");
 }

}

三、配置文件

  打开“AndroidManifest.xml”文件。
  然后输入以下代码: 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.genwoxue.sqlite"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.genwoxue.sqlite.MainActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

  注意:在Android4.0中,如果想显示2.3版本中样式的菜单,需要在配置文件中填加以上红色代码。 

四、运行结果

     

   说明:输入内容,单击“新增”菜单,则添加一条记录;也可以根据书名查询相应书籍;也可以选中某条记录,然后单击“修改”或“删除”菜单。

   

 附:

(一)如何删除Sqlite数据库

  常有人问:如何删除自己创建的数据库?

  在Activity中,提供有现成的方法:public boolean deleteDatabase (String name) 

(二)SimpleCursorAdapter简要说明

  描述:

  SimpleCurosrAdapter 是一个将 Cursor 中的 columns 与在 XML 文件中定义的 TextViews 或 ImageViews 进行匹配的简易 adapter。你可以指定选择 Cursor 中的哪些 columns、用哪些 views 来显示这些 columns 、以及指定定义这些 views 的 xml 文件。

也就是说,SimpleCursorAdapter 允许绑定一个 Cursor 的 columns 到 ListView 上,并使用自定义的 layout 显示 List中的每个项目。

可以使用 SimpleCursorAdapter 作为中间桥梁,将从 sqlite 数据库中查询出来的数据直接显示到 ListView 中。

  原型:

  public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {

     super(context, layout, c);
      mTo = to;
      mOriginalFrom = from;
      findColumns(from);
   }

  参数:

  Context context, 这个与 SimpleListItemFactory 相关的 ListView 所处运行上下文(context)。也就是这个 ListView 所在的 Activity。

  int layout, 显示 list item 的 布局文件。这个 layout 文件中至少要包含在 "to" 参数中命名的 views。

  Cursor c,数据库的光标( Cursor )。如果 cursor 无效,则该参数可以为 null

  String[] from, 指定 column 中的哪些列的数据将绑定(显示)到 UI 中。如果 cursor 无效, 则该参数可为 null。

  int[] to, 指定用于显示 "from" 参数指定的数据列表的 views。 这些 views 必须都是 TextViews。 "from" 参数的前 N 个值(valus)和 "to" 参数的前 N 个 views 是一一对应的关系。如果 cursor 无效,则该参数可为 null。

 

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒋会全

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值