通过一个小例子进行说明:期望达到的效果是共有五个按钮,点击查询之后可以弹出两外一个界面用于展示数据。
首先要创建两个布局,一个主布局,有五个按钮,另外一个布局里面包含一个listview。
<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/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/deleteItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/updateItem"
android:layout_below="@+id/updateItem"
android:layout_marginTop="16dp"
android:text="删除数据" />
<Button
android:id="@+id/updateItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/addItem"
android:layout_below="@+id/createdb"
android:layout_marginTop="104dp"
android:text="更新数据" />
<Button
android:id="@+id/createdb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/updateItem"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:text="创建数据库" />
<Button
android:id="@+id/addItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/createdb"
android:layout_marginLeft="42dp"
android:layout_marginTop="26dp"
android:text="增加数据" />
<Button
android:id="@+id/searchItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/deleteItem"
android:layout_below="@+id/deleteItem"
android:layout_marginTop="22dp"
android:text="查询数据" />
</RelativeLayout>
和
<?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" >
<ListView
android:id="@+id/listitems"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
针对两个布局都有一个活动类对应。讲活动类之前,先把与数据库交互的类给出:
public class MyDatabaseHelper extends SQLiteOpenHelper {
//继承自SQLiteOpenHelper
public static final String CREATE_BOOK = "create table Book ( id integer primary key autoincrement, pages integer, name text)";
public static final String CREATE_CATEGORY = "create table Category(id integer primary key autoincrement, category_name text, category_code integer)";
private Context mContext;
public MyDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
//如果当前数据库不存在,那么该方法被执行,如果数据库已经存在,即使有新表,也不会执行了。就要借助ouUpgrade方法
@Override
public void onCreate(SQLiteDatabase arg0) {
arg0.execSQL(CREATE_BOOK);
arg0.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext, "Database onCreate", Toast.LENGTH_SHORT);
}
//存在数据库更新的时候该方法就会用到
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
arg0.execSQL("drop table if exists book");
arg0.execSQL("drop table if exists Category");
onCreate(arg0);
}
}
两个活动分别如下:
public class MainActivity extends Activity {
private Button createDBButton;
private Button addItem;
private Button updateItem;
private Button deleteItem;
private Button searchItem;
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createDBButton = (Button)findViewById(R.id.createdb);
addItem = (Button)findViewById(R.id.addItem);
updateItem = (Button)findViewById(R.id.updateItem);
deleteItem = (Button)findViewById(R.id.deleteItem);
searchItem = (Button)findViewById(R.id.searchItem);
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
//参数一 上下文 参数二数据库名 参数三用于查询时返回自定义的curson 第四个参数是版本号 一般更新的是偶版本号增加
createDBButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
dbHelper.getWritableDatabase();
}
});
addItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
//用ContentValues存储数据
values.put("name", "沧浪之水");
values.put("pages", 100);
db.insert("Book", null, values); //插入第一条数据
//三个参数 参数一数据表名 第二个参数用于给没有赋值的列自动赋值为null(一般用null) 参数三就是插入数值
values.clear();//清空数据
values.put("name", "三国演义");
values.put("pages", 500);
db.insert("Book", null, values);//插入第二条数据
}
});
updateItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("pages", 200);
db.update("Book", values, "name = ?", new String[]{"沧浪之水"});
//参数一 数据表 参数二 数值 参数三和四 共同构造类似于where语句
}
});
deleteItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("Book", "pages > ?", new String[]{"400"});
//数据表名 条件 数值
}
});
searchItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("Book", null, null, null, null, null, null);
//query方法比较复杂 但是都是通过不同的参数共同拼凑出一个sql语句而已
String items = "";
if(cursor.moveToFirst()){
do{
String name = cursor.getString(cursor.getColumnIndex("name"));
int pages = cursor.getInt(cursor.getColumnIndex("pages"));
items += name+" "+pages+"_";
}while(cursor.moveToNext());
}
//调用另外一个活动,并把数据传递过去
Intent intent = new Intent(MainActivity.this,DBListActivity.class);
intent.putExtra("items", items);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
以及
public class DBListActivity extends Activity {
private String[] data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listitems);
data = getIntent().getStringExtra("items").split("_");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DBListActivity.this, android.R.layout.simple_list_item_1,data);
ListView listView = (ListView)findViewById(R.id.listitems);
listView.setAdapter(adapter);
}
}
别忘了注册活动到配置文件喔!
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.databasetest.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=".DBListActivity"
>
</activity>
</application>
以上就是一个完整的小例子了。
从上面可以看出,Android提供了一套完整的api供用户操作数据库。有些人SQL可能比较牛,在Android里面提供直接运行sql语句的方式:
db.execSQL("insert into book(name, pages) values (?,?)", new String[]{"三毛",“200”});
主思路还是靠参数拼凑出SQL语句。
凡是数据库,应该支持事务功能,即保证一系列的活动完整的执行完。如何做呢?代码可以如下:
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
//一些列数据库操作
db.setTransactionSuccessful();
上面提到了数据库更新,通过改变代码实现更新,如果是一款产品,那相当挫了,所以必须找到一种好的数据库升级方法。
public void onUpgrade(SQLiteDatabase arg0, int oldVersion, int newVersion) {
switch(oldVersion){ //通过版本来控制这一次要更新什么事情
case 1:
db.execSQL(SQL语句);
}
default:
}
其实就是控制要修改的数据库内容在哪~