Android 使用SQLite本地数据库

参考:http://blog.csdn.net/jianghuiquan/article/details/8569252

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

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

一、设计界面

  1、布局文件

  打开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、自定义列表文件

  打开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_drive1" />
    <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_drive1" />

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

</LinearLayout>

color.xml

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

 

string.xml

<resources>
    <string name="app_name">My</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</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文件

 
  然后输入以下代码:

package com.example.yanlei.my;

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文件

 
  然后输入以下代码:

package com.example.yanlei.my;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 AppCompatActivity {

    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.example.yanlei.my" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/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>
    </application>

</manifest>

实际上不需要任何修改

附:

(一)如何删除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。

原文地址:https://www.cnblogs.com/gisoracle/p/5212663.html