Android SQLiteDatabase帮助类SQLiteOpenHelper的使用
Posted 人间神话
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android SQLiteDatabase帮助类SQLiteOpenHelper的使用相关的知识,希望对你有一定的参考价值。
SQLiteOpenHelper是SQLiteDatabse的一个帮助类,用来管理数据的创建和版本更新。一般的用法是定义一个类继承SQLiteOpenHelper,并实现两个回调方法,OnCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabse, int oldVersion, int newVersion)来创建和更新数据库,我利用数据库做了一个类似电话本的功能,插入数据,查询数据,和删除数据,界面很丑,主要是讲解SQLiteOpenHelper类的用法,截图如下
首先我们创建一个DBHelper继承SQLiteOpenHelper,这个是数据库的一个帮助类
package com.example.utils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private final static int VERSION = 1;
private final static String DB_NAME = "phones.db";
private final static String TABLE_NAME = "phone";
private final static String CREATE_TBL = "create table phone(_id integer primary key autoincrement, name text, sex text, number text, desc text)";
private SQLiteDatabase db;
//SQLiteOpenHelper子类必须要的一个构造函数
public DBHelper(Context context, String name, CursorFactory factory,int version) {
//必须通过super 调用父类的构造函数
super(context, name, factory, version);
}
//数据库的构造函数,传递三个参数的
public DBHelper(Context context, String name, int version){
this(context, name, null, version);
}
//数据库的构造函数,传递一个参数的, 数据库名字和版本号都写死了
public DBHelper(Context context){
this(context, DB_NAME, null, VERSION);
}
// 回调函数,第一次创建时才会调用此函数,创建一个数据库
@Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
System.out.println("Create Database");
db.execSQL(CREATE_TBL);
}
//回调函数,当你构造DBHelper的传递的Version与之前的Version调用此函数
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("update Database");
}
//插入方法
public void insert(ContentValues values){
//获取SQLiteDatabase实例
SQLiteDatabase db = getWritableDatabase();
//插入数据库中
db.insert(TABLE_NAME, null, values);
db.close();
}
//查询方法
public Cursor query(){
SQLiteDatabase db = getReadableDatabase();
//获取Cursor
Cursor c = db.query(TABLE_NAME, null, null, null, null, null, null, null);
return c;
}
//根据唯一标识_id 来删除数据
public void delete(int id){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME, "_id=?", new String[]{String.valueOf(id)});
}
//更新数据库的内容
public void update(ContentValues values, String whereClause, String[]whereArgs){
SQLiteDatabase db = getWritableDatabase();
db.update(TABLE_NAME, values, whereClause, whereArgs);
}
//关闭数据库
public void close(){
if(db != null){
db.close();
}
}
}
第一个MainActivity
package com.example.phonebooks;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import com.example.utils.DBHelper;
public class MainActivity extends Activity implements OnClickListener{
private DBHelper dbHelper;
//定义三个输入框
private EditText name, number, desc;
//定义两个按钮
private Button submit ,look;
//定义一个RadioGroup
private RadioGroup radio;
private String nameStr, numberStr, descStr;
private String sexStr = "男";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//实例化DBHelper
dbHelper = new DBHelper(this);
//根据id 获取到相对应的控件
name = (EditText)findViewById(R.id.editText1);
number = (EditText)findViewById(R.id.editText2);
desc = (EditText)findViewById(R.id.editText3);
submit = (Button)findViewById(R.id.button1);
look = (Button)findViewById(R.id.button2);
radio = (RadioGroup)findViewById(R.id.radioGroup1);
//按钮设置点击监听
submit.setOnClickListener(this);
look.setOnClickListener(this);
//单选群组的监听
radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.radio0){
RadioButton r = (RadioButton) group.findViewById(checkedId);
sexStr = r.getText().toString();
}
if(checkedId == R.id.radio1){
RadioButton r = (RadioButton) group.findViewById(checkedId);
sexStr = r.getText().toString();
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
if(name.getText().toString().length() != 0){
nameStr = name.getText().toString();
}else{
Toast.makeText(getApplication(), "姓名不能为空", Toast.LENGTH_SHORT).show();
return;
}
if(number.getText().toString().length() != 0){
numberStr = number.getText().toString();
}else{
Toast.makeText(getApplication(), "电话号码不能为空", Toast.LENGTH_SHORT).show();
return;
}
if(desc.getText().toString().length() != 0){
descStr = desc.getText().toString();
}else{
Toast.makeText(getApplication(), "备注不能为空", Toast.LENGTH_SHORT).show();
return;
}
//实例化一个ContentValues, ContentValues是以键值对的形式,键是数据库的列名,值是要插入的值
ContentValues values = new ContentValues();
values.put("name", nameStr);
values.put("sex", sexStr);
values.put("number", numberStr);
values.put("desc", descStr);
//调用insert插入数据库
dbHelper.insert(values);
//将三个输入框重置下
reset();
break;
case R.id.button2:
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setClass(this, ResultActivity.class);
startActivity(intent);
break;
default:
break;
}
}
//重置edittext
private void reset(){
name.setText("");
number.setText("");
desc.setText("");
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="姓名"
android:textSize="15dp" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText1" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="男" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/radioGroup1"
android:layout_toRightOf="@+id/textView2"
android:text="女" />
</RadioGroup>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/radioGroup1"
android:text="电话号码" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView2"
android:ems="10" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText2"
android:text="备注" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView3"
android:lines="5"
android:ems="10"
android:inputType="textMultiLine" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="查看" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/editText3"
android:text="插入" />
</RelativeLayout>
用一个Person类来封装姓名,性别,电话,备注这些数据。里面只有get()和set()方法
package com.example.mode;
public class Person {
private String name;
private String sex;
private String number;
private String desc;
private int _id;
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
查看数据的ResultActivity
package com.example.phonebooks;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.mode.Person;
import com.example.utils.DBHelper;
public class ResultActivity extends Activity implements OnItemClickListener{
private ListView listView;
private DbAdapter adapter;
DBHelper dbHelper;
List<Person> bookList = new ArrayList<Person>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
//获取ListView
listView = (ListView)findViewById(R.id.listView1);
bookList = queryData();
//实例化DbAdapter
adapter = new DbAdapter(getApplication(), bookList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
//查询数据库,将每一行的数据封装成一个person 对象,然后将对象添加到List中
private List<Person> queryData(){
List<Person> list = new ArrayList<Person>();
dbHelper = new DBHelper(this);
//调用query()获取Cursor
Cursor c = dbHelper.query();
while (c.moveToNext()){
int _id = c.getInt(c.getColumnIndex("_id"));
String name = c.getString(c.getColumnIndex("name"));
String sex = c.getString(c.getColumnIndex("sex"));
String number = c.getString(c.getColumnIndex("number"));
String desc = c.getString(c.getColumnIndex("desc"));
//用一个Person对象来封装查询出来的数据
Person p = new Person();
p.set_id(_id);
p.setName(name);
p.setSex(sex);
p.setNumber(number);
p.setDesc(desc);
list.add(p);
}
return list;
}
//自定义DbAdapter
public class DbAdapter extends BaseAdapter{
private List<Person> list;
private Context context;
private LayoutInflater layoutInflater;
public DbAdapter(Context context, List<Person> list){
layoutInflater = LayoutInflater.from(context);
this.context = context;
this.list = list;
}
//刷新适配器
public void refresh(List<Person> list){
this.list = list;
notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Person p = list.get(position);
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.item, null);
holder.name = (TextView)convertView.findViewById(R.id.textView1);
holder.sex = (TextView)convertView.findViewById(R.id.textView2);
holder.number = (TextView)convertView.findViewById(R.id.textView3);
holder.desc = (TextView)convertView.findViewById(R.id.textView4);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(p.getName());
holder.sex.setText(p.getSex());
holder.number.setText(p.getNumber());
holder.desc.setText(p.getDesc());
return convertView;
}
public class ViewHolder {
public TextView name;
public TextView sex;
public TextView number;
public TextView desc;
public TextView id;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
final Person p = bookList.get(position);
final long temp = id;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("真的要删除该记录?").setPositiveButton("是", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//调用delete()删除某条数据
dbHelper.delete(p.get_id());
//重新刷新适配器
adapter.refresh(queryData());
}
}).setNegativeButton("否", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create().show();
// 关闭数据库
dbHelper.close();
}
}
显示数据的布局result.xml,里面只有一个ListView
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:cacheColorHint="#00000000"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
ListView 的item
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView4"
android:layout_alignParentRight="true"
android:text="TextView" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView4"
android:layout_centerHorizontal="true"
android:text="TextView" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="19dp"
android:text="TextView" />
</RelativeLayout>
主要不要忘了在AndroidManifest.xml 注册ResultActivity
以上是关于Android SQLiteDatabase帮助类SQLiteOpenHelper的使用的主要内容,如果未能解决你的问题,请参考以下文章
Android的SQLiteDataBase小项目,实现user类登陆注册以及student类增删改查
安卓9SQLiteDatabase类ContentValues 类