当我们需要存储大量数据的时候就需要数据库,Android自带了一种轻量级数据库SQLite。SQLite甚至不需要安装和启动服务进程,它只是一个后缀为.db的数据库文件,但它支持SQL语句。
关于SQLite的使用需要一个SQLiteDataBase类,该类底层就是一个数据库文件,一个该类代表一个数据库,对数据库的操作也要通过SQLiteDataBase类。
SQLiteDatabase提供如下静态方法来打开一个对应的数据库文件:
openDatabase(String path,SQLiteDatabase.CursorFactory,int)
打开path文件所代表的SQLite数据库
openOrCreateDatabase(String path,SQLiteDatabase.CursorFactory)
打开或者创建path文件所代表的SQLite数据库
openOrCreateDatabase(File file,SQLiteDatabase.CursorFactory)
打开或者创建file文件所代表的SQLite数据库
执行SQL的语句如下
execSQL(String sql,Object[] bindArgs)
execSQL(String sql)
执行增加、删除、更新等没有返回值的SQL语句,第一种第二个参数为SQL语句中可包含的占位符
Cursor rawQuery(String,String[])
执行查询语句,返回Cursor
Cursor即如SQL中的resultSet,是一个结果集,我们这里将使用SimpleCursorAdapter这个适配器配置ListView,其中可直接使用该结果集。
使用完毕后需要调用SQLiteDataBase.close()方法关闭数据库。
SQLite内部只支持5种数据类型,但实际上SQLite完全可以接受varchar,char等数据类型,只不过SQLite会在运算或保存时将他们转换成下面的五种数据类型中相应的类型:
NULL: 空值
INTEGER: 整数,依据值的大小可以依次被存储为1,2,3,4,5,6,7,8个字节
REAL: 浮动的数值,被存储为8字节的IEEE浮动标记序号.
TEXT: 文本字符串,使用数据库编码存储(TUTF-8,UTF-16BE or UTF-16-LE).
BLOB: BLOB数据,如何输入就如何存储,不改变格式.
除此之外,SQLite还有一个特点:允许把各种类型的数据保存到任何类型字段中,开发者可以不用关心申明该字段所使用的数据类型。例如程序可以把字符串类型的值存入INTEGER类型的字段中,也可以吧数值类型的值存储到布尔类型中。
但有一种情况例外:定义INTEGERPRIMARY KEY的字段只能存储64位整数(主键)。
由于SQLite允许存入数据时忽略底层数据列实际的数据类型,因此在编写建表语句时可以省略数据列后面的类型声明。但实际上,sqlite3也接受如下的数据类型:
smallint 16位的整数。
interger 32位的整数。
decimal(p,s) 精确值p是指全部有几个十进制数,s是指小数点后可以有几位小数。如果没有特别指定,则系统会默认为p=5s=0 。
float 32位元的实数。
double 64位元的实数。
char(n) n 长度的字串,n不能超过 254。
varchar(n) 长度不固定且其最大长度为 n 的字串,n不能超过 4000。
graphic(n) 和 char(n) 一样,不过其单位是两个字节, n不能超过127。这个形态是为了支持两个字节长度的字体,如中文字。
vargraphic(n) 可变长度且其最大长度为n的双字元字串,n不能超过2000
date 包含了 年份、月份、日期。
time 包含了 小时、分钟、秒。
timestamp 包含了年、月、日、时、分、秒、千分之一秒
同时在Android SDK中提供了一个sqlite3工具,供我们对Android中的数据库文件进行操作,但需要将手机或模拟机中的数据库导出到电脑,在电脑终端使用。
大概可以这般使用(文件位置为data/data/包名/files/xxx.db)
以下我们使用SQLite对用户名和密码的增删改查做一个简单的实现。首先我们通过文本输入框输入信息,建表然后保存,再以列表的形式显示保存好的内容,实现点击更行、长按删除。
布局文件如下
- <LinearLayout 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:orientation="vertical"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context="com.briup.sqlite.MainActivity" >
-
- <EditText
- android:id="@+id/username"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="User name" />
-
- <EditText
- android:id="@+id/userpwd"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="Password" />
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:onClick="save"
- android:text="SAVE" />
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:onClick="read"
- android:text="READ" />
-
- <ListView
- android:id="@+id/values_list"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
-
- </LinearLayout>
values_item.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"
- android:orientation="horizontal" >
-
- <TextView
- android:id="@+id/tv_id"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="20sp"
- android:visibility="gone" />
-
- <TextView
- android:id="@+id/tv_username"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginLeft="10dp"
- android:textSize="20sp" />
-
- <TextView
- android:id="@+id/tv_password"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginLeft="20dp"
- android:textSize="20sp" />
-
- </LinearLayout>
alertdialog.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"
- android:orientation="vertical" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="姓名" />
-
- <EditText
- android:id="@+id/alert_name"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="密码" />
-
- <EditText
- android:id="@+id/alert_pass"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
-
- </LinearLayout>
MainActivity类文件如下
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.app.AlertDialog.Builder;
- import android.content.DialogInterface;
- import android.content.DialogInterface.OnClickListener;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemClickListener;
- import android.widget.AdapterView.OnItemLongClickListener;
- import android.widget.EditText;
- import android.widget.ListView;
- import android.widget.SimpleCursorAdapter;
- import android.widget.TextView;
- import android.widget.Toast;
-
- public class MainActivity extends Activity {
- private EditText username, password;
- private SQLiteDatabase DB;
-
- private ListView values;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- username = (EditText) findViewById(R.id.username);
- password = (EditText) findViewById(R.id.userpwd);
- values = (ListView) findViewById(R.id.values_list);
-
- DB = SQLiteDatabase.openOrCreateDatabase(getFilesDir() + "/info.db",
- null);
-
- values.setOnItemLongClickListener(new OnItemLongClickListener() {
-
- @Override
- public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
- int arg2, long arg3) {
-
- TextView tv = (TextView) arg1.findViewById(R.id.tv_id);
- final String id = tv.getText().toString();
-
- AlertDialog.Builder builder = new AlertDialog.Builder(
- MainActivity.this);
- builder.setMessage("确定要删除吗?");
-
- builder.setPositiveButton("确定", new OnClickListener() {
-
- @Override
- public void onClick(DialogInterface dialog, int which) {
- delete(id);
- replaceList();
- }
- });
-
- builder.setNegativeButton("取消", new OnClickListener() {
-
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- builder.create().show();
-
- return true;
- }
- });
-
- values.setOnItemClickListener(new OnItemClickListener() {
-
- @Override
- public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
- long arg3) {
-
- TextView tvId = (TextView) arg1.findViewById(R.id.tv_id);
- TextView tvName = (TextView) arg1
- .findViewById(R.id.tv_username);
- TextView tvPass = (TextView) arg1
- .findViewById(R.id.tv_password);
- final String id = tvId.getText().toString();
- String username = tvName.getText().toString();
- String password = tvPass.getText().toString();
-
- AlertDialog.Builder builder = new Builder(MainActivity.this);
- builder.setTitle("修改");
-
- View v = View.inflate(MainActivity.this, R.layout.alertdialog,
- null);
- final EditText etName = (EditText) v
- .findViewById(R.id.alert_name);
- final EditText etPass = (EditText) v
- .findViewById(R.id.alert_pass);
-
- etName.setText(username);
- etPass.setText(password);
-
- builder.setView(v);
-
- builder.setPositiveButton("保存", new OnClickListener() {
-
- @Override
- public void onClick(DialogInterface dialog, int which) {
- String newName = etName.getText().toString();
- String newPass = etPass.getText().toString();
- updata(newName, newPass, id);
- replaceList();
- }
- });
-
- builder.setNegativeButton("取消", new OnClickListener() {
-
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- builder.create().show();
- }
- });
- }
-
-
-
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- DB.close();
- }
-
-
-
-
- public void save(View v) {
- String name = username.getText().toString();
- String pass = password.getText().toString();
- try {
- insert(name, pass);
- } catch (Exception e) {
- create();
- insert(name, pass);
- }
- Toast.makeText(this, "Save Success", Toast.LENGTH_SHORT).show();
- username.setText("");
- password.setText("");
- }
-
-
-
-
- public void read(View v) {
- replaceList();
- }
-
-
-
-
- public void replaceList() {
- Cursor cursor = select();
- SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
- R.layout.values_item, cursor, new String[] { "_id", "username",
- "password" }, new int[] { R.id.tv_id, R.id.tv_username,
- R.id.tv_password },
- SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
- values.setAdapter(adapter);
- }
-
-
-
-
- public void create() {
- String createSql = "create table user(_id integer primary key autoincrement,username,password)";
- DB.execSQL(createSql);
- }
-
-
-
-
- public void insert(String username, String password) {
- String insertSql = "insert into user(username,password) values(?,?)";
- DB.execSQL(insertSql, new String[] { username, password });
- }
-
-
-
-
- public Cursor select() {
- String selectSql = "select _id,username,password from user";
- Cursor cursor = DB.rawQuery(selectSql, null);
- return cursor;
- }
-
-
-
-
- public void delete(String id) {
- String deleteSql = "delete from user where _id=?";
- DB.execSQL(deleteSql, new String[] { id });
- }
-
-
-
-
- public void updata(String username, String password, String id) {
- String updataSql = "update user set username=?,password=? where _id=?";
- DB.execSQL(updataSql, new String[] { username, password, id });
- }
- }
效果如下