Android系统下读写Sqlite数据库的源码

将开发过程经常用的内容片段做个备份,如下内容是关于Android系统下读写Sqlite数据库的的内容。

Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

package com.commonsware.android.constants;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.SensorManager;

public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME=“db”;
public static final String TITLE=“title”;
public static final String VALUE=“value”;

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(“CREATE TABLE constants (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, value REAL);”);

ContentValues cv=new ContentValues();

cv.put(TITLE, “Gravity, Death Star I”);
cv.put(VALUE, SensorManager.GRAVITY_DEATH_STAR_I);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Earth”);
cv.put(VALUE, SensorManager.GRAVITY_EARTH);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Jupiter”);
cv.put(VALUE, SensorManager.GRAVITY_JUPITER);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Mars”);
cv.put(VALUE, SensorManager.GRAVITY_MARS);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Mercury”);
cv.put(VALUE, SensorManager.GRAVITY_MERCURY);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Moon”);
cv.put(VALUE, SensorManager.GRAVITY_MOON);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Neptune”);
cv.put(VALUE, SensorManager.GRAVITY_NEPTUNE);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Pluto”);
cv.put(VALUE, SensorManager.GRAVITY_PLUTO);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Saturn”);
cv.put(VALUE, SensorManager.GRAVITY_SATURN);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Sun”);
cv.put(VALUE, SensorManager.GRAVITY_SUN);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, The Island”);
cv.put(VALUE, SensorManager.GRAVITY_THE_ISLAND);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Uranus”);
cv.put(VALUE, SensorManager.GRAVITY_URANUS);
db.insert(“constants”, TITLE, cv);

cv.put(TITLE, “Gravity, Venus”);
cv.put(VALUE, SensorManager.GRAVITY_VENUS);
db.insert(“constants”, TITLE, cv);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.w(“Constants”, “Upgrading database, which will destroy all old data”);
db.execSQL(“DROP TABLE IF EXISTS constants”);
onCreate(db);
}
}
复制代码

ConstantsBrowser.java

Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

package com.commonsware.android.constants;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.method.NumberKeyListener;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ConstantsBrowser extends ListActivity {
private static final int ADD_ID = Menu.FIRST+1;
private static final int DELETE_ID = Menu.FIRST+3;
private static final int CLOSE_ID = Menu.FIRST+4;
private SQLiteDatabase db=null;
private Cursor constantsCursor=null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

db=(new DatabaseHelper(this)).getWritableDatabase();
constantsCursor=db.rawQuery("SELECT _ID, title, value "+
“FROM constants ORDER BY title”,
null);

ListAdapter adapter=new SimpleCursorAdapter(this,
R.layout.row, constantsCursor,
new String[] {“title”, “value”},
new int[] {R.id.title, R.id.value});

setListAdapter(adapter);
registerForContextMenu(getListView());
}

@Override
public void onDestroy() {
super.onDestroy();

constantsCursor.close();
db.close();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, ADD_ID, Menu.NONE, “Add”)
.setIcon(R.drawable.add)
.setAlphabeticShortcut(‘a’);
menu.add(Menu.NONE, CLOSE_ID, Menu.NONE, “Close”)
.setIcon(R.drawable.eject)
.setAlphabeticShortcut(‘c’);

return(super.onCreateOptionsMenu(menu));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ADD_ID:
add();
return(true);

case CLOSE_ID:
finish();
return(true);
}

return(super.onOptionsItemSelected(item));
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, DELETE_ID, Menu.NONE, “Delete”)
.setIcon(R.drawable.delete)
.setAlphabeticShortcut(‘d’);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterView.AdapterContextMenuInfo info=
(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

delete(info.id);
return(true);
}

return(super.onOptionsItemSelected(item));
}

private void add() {
LayoutInflater inflater=LayoutInflater.from(this);
View addView=inflater.inflate(R.layout.add_edit, null);
final DialogWrapper wrapper=new DialogWrapper(addView);

new AlertDialog.Builder(this)
.setTitle(R.string.add_title)
.setView(addView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
processAdd(wrapper);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
})
.show();
}

private void delete(final long rowId) {
if (rowId>0) {
new AlertDialog.Builder(this)
.setTitle(R.string.delete_title)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
processDelete(rowId);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
})
.show();
}
}

private void processAdd(DialogWrapper wrapper) {
ContentValues values=new ContentValues(2);

values.put(“title”, wrapper.getTitle());
values.put(“value”, wrapper.getValue());

db.insert(“constants”, “title”, values);
constantsCursor.requery();
}

private void processDelete(long rowId) {
String[] args={String.valueOf(rowId)};

db.delete(“constants”, “_ID=?”, args);
constantsCursor.requery();
}

class DialogWrapper {
EditText titleField=null;
EditText valueField=null;
View base=null;

DialogWrapper(View base) {
this.base=base;
valueField=(EditText)base.findViewById(R.id.value);
}

String getTitle() {
return(getTitleField().getText().toString());
}

float getValue() {
return(new Float(getValueField().getText().toString())
.floatValue());
}

private EditText getTitleField() {
if (titleField==null) {
titleField=(EditText)base.findViewById(R.id.title);
}

return(titleField);
}

private EditText getValueField() {
if (valueField==null) {
valueField=(EditText)base.findViewById(R.id.value);
}

return(valueField);
}
}
}

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

android:orientation=“horizontal”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”



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

android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”

<LinearLayout
android:orientation=“horizontal”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”




<LinearLayout
android:orientation=“horizontal”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”




一.创建一个DataBaseHelper DataBaseHelper是一个访问SQLite的助类,提供两个方面的功能 1.getReadableDatebase(),getWriteableDatabase()可以获取SQLiteDatabase对象,通过 2.提供了onCreate()和onUpdate()两个回调函数,允许我们常见和升级数据库是进行使用 A、 在SQLiteOpenHelper的子类当中,必须要有的构造函数 B、该函数是在第一次创建数据库的时候执行,实际上是在第一次得到SQLiteDataBase对象的时候onCreate 二、创建一个实体person类并且给字段和封装 三、创建一个业务类对SQL的CRUD操作 1.getWritableDatabase()和getReadableDatabase()的区别 ,两个方法都可以获取一个用于操作数据库SQLiteDatabase实例 2.execSQL(增,删,改都是这个方法)和close();android内部有缓存可关闭也不关闭也行,查询rawQuery是方法 3.在分页有到Cursor(游标)取游标下一个值cursor.moveToNext(),用游标对象接数据 "select * from person limit ?,?" person不能加上where 关键字 4.在删除注意:sb.deleteCharAt(sb.length() - 1); 四、AndroidCRUD业务对SQLite的CRUD操作 1.ContentValues对象的使用 2.android内部insert添加数据的方法,而且values这个不给值也必须要执行,而主键是不是null的其他字段的值是为null 3.insert update query delete 五、单元测试类要注意的 AndroidCRUDService curdService = new AndroidCRUDService(this.getContext()); /* * 注意:getContext必须在我们使用前已经注解进去的,在使用前要实力化,而且是使用后才有上下文 *一般设置为局部对象 */ 六、AndroidManifest.xml的配置 <!-- 配置用户类库android.test.runner测试 --> package jll.sqlitedb; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; /** * *@author Administrator DataBaseHelper是一个访问SQLite的助类,提供两个方面的功能 * 1.getReadableDatebase(),getWriteableDatabase()可以获取SQLiteDatabase对象,通过 * 2.提供了onCreate()和onUpdate()两个回调函数,允许我们常见和升级数据库是进行使用 */ public class DataBaseHelper extends SQLiteOpenHelper { // 给一个默认的SQLite数据库名 private static final String DataBaseName = "SQLite_DB"; private static final int VERSION = 2; // 在SQLiteOpenHelper的子类当中,必须要有的构造函数 public DataBaseHelper(Context context, String name, CursorFacto
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值