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



    

    

        
    

    

        

        
    

    

    

    

    

    
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 bookList = new ArrayList();

	@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 queryData(){
		List list = new ArrayList();
		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 list;
		private Context context;
		private LayoutInflater layoutInflater;
		
		public DbAdapter(Context context, List list){
			layoutInflater = LayoutInflater.from(context);
			this.context = context;
			this.list = list;
		}
		
		//刷新适配器
		public void refresh(List 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



    
    

ListView 的item




    

    

    

    

主要不要忘了在AndroidManifest.xml 注册ResultActivity

项目代码下载

你可能感兴趣的:(SQLiteDatabase帮助类SQLiteOpenHelper的使用)