如果您想了解android–SQLiteOpenHelper错误的知识,那么本篇文章将是您的不二之选。同时我们将深入剖析12.Android-SQLiteOpenHelper使用、andriod之SQ
如果您想了解android – SQLiteOpenHelper错误的知识,那么本篇文章将是您的不二之选。同时我们将深入剖析12.Android-SQLiteOpenHelper使用、andriod之SQLite--SQLiteOpenHelper用法、android SQLite 使用 SQLiteOpenHelper 类对数据库进行操作、Android SQLiteOpenHelper – 每个表的不同类?的各个方面,并给出实际的案例分析,希望能帮助到您!
本文目录一览:- android – SQLiteOpenHelper错误
- 12.Android-SQLiteOpenHelper使用
- andriod之SQLite--SQLiteOpenHelper用法
- android SQLite 使用 SQLiteOpenHelper 类对数据库进行操作
- Android SQLiteOpenHelper – 每个表的不同类?
android – SQLiteOpenHelper错误
sqliteOpenHelper dbHelper = new sqliteOpenHelper(this,"myDB.db3",null,1);
在我的应用程序onCreate方法中,我看到Ecplise告诉我
Cannot instantiate the type sqliteOpenHelper
我没有看到与SDK教程基本不同的东西(除了我对构造函数的调用没有包含在辅助类中).
谢谢.
解决方法
public class MyOpenHelper extends sqliteOpenHelper { ... } MyOpenHelper dbHelper = new MyOpenHelper(...);
12.Android-SQLiteOpenHelper使用
1.SQLite介绍
SQLite,是一款轻型的数据库,它的优缺点有如下:
- 轻量级,适合嵌入式设备,并且本身不依赖第三方的软件,使用它也不需要“安装”。
- 并发(包括多进程和多线程)读写方面的性能不太理想。可能会被写操作独占,从而导致其它读写操作阻塞或出错
2.SQLiteOpenHelper介绍
为了在本地创建SQLite数据库,我们需要创建一个SQLiteOpenHelper的子类,这里取名的为MyOpenHelper类,然后还要写构造方法来初始化父类、以及abstract修饰的抽象方法:onCreate(SQLiteDatabase)、onUpgrade(SQLiteDatabase,int,int).
2.1 为什么要创建SQLiteOpenHelper的子类(MyOpenHelper类)?
因为SQLiteOpenHelper不知道我们要创建的数据库是什么名字,以及表的内容,所以我们要创建MyOpenHelper类.
3.SQLiteOpenHelper构造方法
构造方法用来创建数据库文件的,构造方法如下:
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version);
//第一个参数:上下文
//第二个参数:数据库文件的名字,如果传入null 则表示创建临时数据库,在应用退出之后,数据就会丢失
//第三个参数:游标工厂 如果使用系统默认的游标工厂就传入null,一般都填null
//第四个参数:数据库的版本号 用版本号来控制数据库的升级和降级 版本号从1开始
比如创建一个demo.db,我们只需要在MyOpenHelper类构造方法里填入下面代码即可:
super(context, "demo.db", null, 1);
4.public abstract void onCreate (SQLiteDatabase db)
- 参数db : 数据库对象,这里通过db.execSQL(String)来创建表.
onCreate用来创建数据库表结构的,该函数在第一次创建数据库时调用,也就是在调用SQLiteOpenHelper类的getWritableDatabase()或者getReadableDatabase()时会调用该方法,如下图所示:
可以看到只有调用getWritableDatabase()或者getReadableDatabase()时,才会真正创建数据库。
- getReadableDatabase() : 获取一个只读数据库(不能写入)
- getWritableDatabase () : 获取一个可写的数据库,不再操作的时候,一定要close()关闭数据库,如果磁盘已满,获取将会报错.
比如创建一个student学生表,标题分别为id、name、score、class,填入下面代码即可:
5.public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)
- db : 数据库对象,通过db.execSQL(String)来执行sql语句
- oldVersion : 显示之前旧的数据库版本。
- newVersion : 显示升级之后的新数据库版本。
当数据库需要升级时调用。使用此方法删除表、添加表或执行升级到新模式版本所需的任何其他操作。
如果添加新列,可以使用ALTER TABLE将它们插入活动表。如果重命名或删除列,可以使用ALTER TABLE重命名旧表,然后创建新表,然后用旧表的内容填充新表。
6.数据库增删改查
实现了SQLiteOpenHelper的子类(MyOpenHelper类)后,就有了数据库了,接下来我们便可以对SQLiteDatabase类进行数据库增删改查
6.1 通过SQLiteDatabase getWritableDatabase()来获取SQLiteDatabase类.
SQLiteDatabase类中常用方法如下所示:
public Cursor rawQuery (String sql, String[] selectionArgs);
// rawQuery:查询数据库内容,并将查询到的结果集保存在Cursor游标类中,并返回.
// sql:填入select查询语句
// selectionArgs:如果sql参数填入的内容是正常语句,则这里填NULL,如果是where子句中包含?,则将会被selectionArgs中的值替换.
void execSQL(String sql);
//用来执行INSERT、UPDATE 或 DELETE 的sql语句
Cursor类游标默认是指向所有结果之前的一行,然后通过moveToNext()方法就能获取每一行结果的内容
示例如下-读出student表里的内容:
SQLiteDatabase database = new MyOpenHelper(this).getWritableDatabase(); //获取数据库
Cursor cursor = database.rawQuery("select * from student", null); //查询student表内容
while (cursor.moveToNext()) {
//可以通过 getXXX方法 获取每一行数据
String name = cursor.getString(cursor.getColumnIndex("name")); //获取当前游标所在行下的name列内容
String score = cursor.getString(cursor.getColumnIndex("score"));//获取当前游标所在行下的score列内容
System.out.println("name=" + name + " score =" + score);
}
cursor.close();
database.close();
7.安卓示例-查询添加删除示例
界面如下:
操作示例如下:
如下图所示,可以看到我们刚刚操作的数据库:
打开后,如下图所示,就可以看到我们刚刚写入的数据:
8.具体代码实现
8.1 activity_main.xml如下所示:
<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" >
<EditText
android:id="@+id/et_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="这里显示要查询的内容"
android:textSize="12sp"
android:minLines="10" />
<Button
android:id="@+id/btn_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@id/et_query"
android:text="查询内容"
/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@id/btn_query"
android:paddingTop="50dp"
android:text="名字:" />
<EditText
android:id="@+id/et_nameAdd"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/textView1"
android:layout_toRightOf="@id/textView1"
android:textSize="11sp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/et_nameAdd"
android:layout_alignBaseline="@id/textView1"
android:text="成绩:" />
<EditText
android:id="@+id/et_scoreAdd"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/textView1"
android:layout_toRightOf="@id/textView2"
android:textSize="11sp" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/et_scoreAdd"
android:layout_alignBaseline="@id/textView1"
android:text="班级:" />
<EditText
android:id="@+id/et_classAdd"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/textView1"
android:layout_toRightOf="@id/textView3"
android:textSize="11sp" />
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/textView1"
android:layout_toRightOf="@id/et_classAdd"
android:text="添加"
android:textSize="11sp" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:paddingBottom="20dp"
android:text="要删除的id:" />
<EditText
android:id="@+id/et_deleteId"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView4"
android:layout_toRightOf="@+id/textView4"
android:textSize="11sp" />
<Button
android:id="@+id/btn_deleteId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/et_deleteId"
android:layout_alignParentRight="true"
android:textSize="13sp"
android:text="删除"/>
</RelativeLayout>
8.2 MyOpenHelper.java如下所示:
public class MyOpenHelper extends SQLiteOpenHelper {
public MyOpenHelper(Context context) {
//这里创建一个数据库,名字为demo.db
super(context, "demo.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//onCreate用来创建数据库表结构的,这里创建一个student学生表,标题分别为id、name、score、class
db.execSQL("CREATE TABLE student ("
+"id INTEGER PRIMARY KEY AUTOINCREMENT, "
+"name VARCHAR(40) NOT NULL, "
+"score INTEGER NOT NULL, "
+"class VARCHAR(40) NOT NULL)");
System.out.println("onCreate 创建表");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//实现版本升级的函数
System.out.println("onupgrade oldVersion"+oldVersion+"newVersion"+newVersion);
switch (oldVersion) {
case 1: //如果之前版本号为1.(标题只有id、name、score、class),那么将添加科目和考号标题
db.execSQL("alter table info add age 科目");
db.execSQL("alter table info add age 考号");
break;
}
}
}
8.3 MainActivity.java如下所示:
public class MainActivity extends Activity {
private MyOpenHelper openHelper;
private EditText et_nameAdd;
private EditText et_scoreAdd;
private EditText et_classAdd;
private EditText et_query;
private EditText et_deleteId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openHelper = new MyOpenHelper(this);
et_nameAdd = (EditText)findViewById(R.id.et_nameAdd);
et_scoreAdd = (EditText)findViewById(R.id.et_scoreAdd);
et_classAdd = (EditText)findViewById(R.id.et_classAdd);
et_query = (EditText)findViewById(R.id.et_query);
et_deleteId = (EditText)findViewById(R.id.et_deleteId);
//实现查询数据库功能
Button btn_query = (Button)findViewById(R.id.btn_query);
btn_query.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase readableDatabase = openHelper.getReadableDatabase();
Cursor rawQuery = readableDatabase.rawQuery("select * from student", null);
StringBuilder text = new StringBuilder();
text.append("query length:"+String.valueOf(rawQuery.getCount()));
while(rawQuery.moveToNext()){
String id = rawQuery.getString(rawQuery.getColumnIndex("id"));//获取当前游标所在行下的id列内容
String name = rawQuery.getString(rawQuery.getColumnIndex("name")); //获取当前游标所在行下的name列内容
String score = rawQuery.getString(rawQuery.getColumnIndex("score"));//获取当前游标所在行下的score列内容
String classs = rawQuery.getString(rawQuery.getColumnIndex("class"));//获取当前游标所在行下的class列内容
text.append("\r\n id:"+id+" 名字:"+name+" 成绩:"+score+" 班级:"+classs);
}
rawQuery.close();
readableDatabase.close();
et_query.setText(text.toString());
}
});
//实现添加数据项功能
Button btn_add = (Button)findViewById(R.id.btn_add);
btn_add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String name = et_nameAdd.getText().toString().trim();
String score = et_scoreAdd.getText().toString().trim();
String classs = et_classAdd.getText().toString().trim();
if(TextUtils.isEmpty(name)||TextUtils.isEmpty(score)||TextUtils.isEmpty(classs))
{
Toast.makeText(MainActivity.this, "添加的内容不能为空", Toast.LENGTH_SHORT).show();
return;
}
String sql = "INSERT INTO student(name, score,class) "
+"VALUES (''"+name+"'', "+score+", ''"+classs+"'')";
SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
writableDatabase.execSQL(sql);
writableDatabase.close();
System.out.println(sql);
}
});
//实现通过ID号来删除某一行数据项功能
Button btn_deleteId = (Button)findViewById(R.id.btn_deleteId);
btn_deleteId.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String id = et_deleteId.getText().toString().trim();
if(TextUtils.isEmpty(id)){
Toast.makeText(MainActivity.this, "删除的内容不能为空", Toast.LENGTH_SHORT).show();
return;
}else if(!TextUtils.isDigitsOnly(id)){
Toast.makeText(MainActivity.this, "请填入要删除的数字!", Toast.LENGTH_SHORT).show();
return;
}
SQLiteDatabase readableDatabase = openHelper.getReadableDatabase();
readableDatabase.execSQL("DELETE FROM student WHERE id = "+id+"");
System.out.println("DELETE FROM student WHERE id = "+id+"");
Toast.makeText(MainActivity.this, "已删除ID"+id+"所在的一行!", Toast.LENGTH_SHORT).show();
}
});
}
@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;
}
}
原文出处:https://www.cnblogs.com/lifexy/p/12206278.html
andriod之SQLite--SQLiteOpenHelper用法
主显示布局以及代码:
activity_main.xml:
<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">
<ListView android:id="@+id/lvUsers"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
主要布局的java代码:
package com.example.day05_01;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBaractivity;
import android.text.TextUtils;
import android.util.Log;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.database.sqlite.sqliteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ActionBaractivity {
private ListView lvUsers;//listView组件
private List<UserBean> users;//显示的数据集合
private UserAdapter userAdapter;//用于适配listView的适配器
private UserDBHelper userDao;//用于操作数据库的类
private final int USER_ADD=0;
//跳转到另一个intent后,把该值默认传递过去,另一个intent处理后,返回结果后,改值默认传递回来,这里的话是标识添加操作
private final int USER_UPDATE=1;
//跳转到另一个intent后,把该值默认传递过去,另一个intent处理后,返回结果后,改值默认传递回来,这里的话是标识修改操作
private int mposition;//这个是处理修改的时候,得到修改的位置,好直接从users这个list直接给更新
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
setListener();
}
private void setListener() {
// Todo Auto-generated method stub
this.lvUsers.setonItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View view,
final int position,long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("请选择以下操作").setItems(new String[]{
"添加用户","修改用户","删除用户"
},new OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
switch (which) {
case 0://数组的下标,这里为了简单直接用数字了,添加操作
Intent intent = new Intent(MainActivity.this,UserAddActivity.class);
startActivityForResult(intent,USER_ADD);
break;
case 1://数组的下标,这里为了简单直接用数字了,修改操作
Intent intentupdate = new Intent(MainActivity.this,UserUpdateActivity.class);
intentupdate.putExtra("userBean",users.get(position));
mposition = position;
startActivityForResult(intentupdate,USER_UPDATE);
case 2://数组的下标,这里为了简单直接用数字了,删除操作
userAdapter.delete(users.get(position),position);default:
}
});
//下面一段话一定要加,不然显示不了
AlertDialog dialog = builder.create();
dialog.show();
private void initData() {
userDao = new UserDBHelper(this);
this.users = userDao.queryAll();
private void initView() {
lvUsers = (ListView) findViewById(R.id.lvUsers);
userAdapter = new UserAdapter(this,users);
lvUsers.setAdapter(userAdapter);
class UserAdapter extends BaseAdapter{
private Context context;
private List<UserBean> users;
public UserAdapter(Context context,List<UserBean> users){
this.context = context;
this.users = users;
//添加
public void add(UserBean userBean){
users.add(userBean);
this.notifyDataSetChanged();
userDao.insertUserBean(userBean);
};
//修改
public void update(UserBean userBean,int position){
users.set(position,userBean);
this.notifyDataSetChanged();
userDao.updateUserBean(userBean);
};
//删除
public void delete(UserBean userBean,int position){
users.remove(position);
this.notifyDataSetChanged();
userDao.deleteUserBean(userBean);
};
public int getCount() {
return users.size();
public Object getItem(int position) {
return users.get(position);
public long getItemId(int position) {
return position;
public View getView(int position,View convertView,ViewGroup parent) {
ViewHolder viewHolder = null;
if(convertView==null){
convertView = View.inflate(context,R.layout.userinfo,null);
TextView tvusername = (TextView) convertView.findViewById(R.id.username);
TextView tvuserhobby = (TextView) convertView.findViewById(R.id.userhobby);
TextView tvuserheight = (TextView) convertView.findViewById(R.id.userheight);
viewHolder = new ViewHolder(tvusername,tvuserhobby,tvuserheight);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag(); UserBean user = users.get(position);
viewHolder.tvusername.setText(user.getName());
viewHolder.tvhobby.setText(user.getHobby());
viewHolder.tvheight.setText(user.getHeight());
return convertView;
class ViewHolder{
TextView tvusername,tvhobby,tvheight;
private ViewHolder(TextView tvusername,TextView tvhobby,TextView tvheight){
this.tvheight = tvheight;
this.tvusername = tvusername;
this.tvhobby = tvhobby;
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if(resultCode!=RESULT_OK){
return;
switch(requestCode){
case USER_ADD:
UserBean userBean = (UserBean) data.getSerializableExtra("userBean");
userAdapter.add(userBean);
case USER_UPDATE:
UserBean userBean1 = (UserBean) data.getSerializableExtra("userBean");
userAdapter.update(userBean1,mposition);
}
}
entity类:
package com.example.day05_01;
import java.io.Serializable;
public class UserBean implements Serializable{
private int id;
private String name;
private String hobby;
private String height;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public UserBean(int id,String name,String hobby,String height) {
super();
this.id = id;
this.name = name;
this.hobby = hobby;
this.height = height;
}
public UserBean(String name,String height) {
super();
this.name = name;
this.hobby = hobby;
this.height = height;
}
@Override
public String toString() {
return "UserBean [id=" + id + ",name=" + name + ",hobby=" + hobby
+ ",height=" + height + "]";
}
}
操作数据库的类:(总结:1、这里的getReadableDatabase()和getWritableDatabase()都是得到数据库操作对象,不同的是,一般涉及到写的都用getWritableDatabase(),像查询之类的,一般用getReadableDatabase(),就是当内存不够用的时候用getReadableDatabase()。)
2、(onCreate:当数据库第一次被建立的时候被执行,例如创建表,初始化数据等。(通俗的说,就是么有创建数据库的时候,会调用创建数据库)
onUpgrade:当数据库需要被更新的时候执行,例如删除久表,创建新表。)
package com.example.day05_01;
import java.util.ArrayList;
import java.util.List;
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;
import android.provider.OpenableColumns;
public class UserDBHelper extends sqliteOpenHelper{
private static final String DB_NAME = "users.db";
private final String TABLE_NAME = "users";
private final String NAME= "name";
private final String HOBBY = "hobby";
private final String ID = "id";
private final String HEIGHT = "height";
public UserDBHelper(Context context) {
super(context,DB_NAME,null,1);
// Todo Auto-generated constructor stub
public void onCreate(sqliteDatabase db) {
createTable(db);
initData(db);
private void initData(sqliteDatabase db) {
ContentValues values = new ContentValues();
values.put(NAME,"小王");
values.put(HOBBY,"打游戏");
values.put(HEIGHT,2.5);
db.insert(TABLE_NAME,values);
values = new ContentValues();
String tableString = "create table if not exists "+TABLE_NAME
+" ("+ID+" integer primary key autoincrement,"+
NAME+" char(50),0); white-space:pre">HOBBY+" char(50),0); white-space:pre">HEIGHT+" real"+
")";
db.execsql(tableString);
public void onUpgrade(sqliteDatabase arg0,int arg1,int arg2) {
//查询所有
public List<UserBean> queryAll(){
sqliteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME,0); white-space:pre">List<UserBean> resultList = new ArrayList<UserBean>();
while(cursor.movetoNext()){
String name = cursor.getString(cursor.getColumnIndex(NAME));
String hobby = cursor.getString(cursor.getColumnIndex(HOBBY));
int id = cursor.getInt(cursor.getColumnIndex(ID));
double height = cursor.getDouble(cursor.getColumnIndex(HEIGHT));
UserBean userBean = new UserBean(id,name,hobby,height+"");
resultList.add(userBean);
return resultList;
//根据id查询信息
public List<UserBean> queryUserById(String userid){
//添加数据:
public int insertUserBean(UserBean userBean){
sqliteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
//修改数据:
public int updateUserBean(UserBean userBean){
int count = db.update(TABLE_NAME,values,new String[]{userBean.getId()+""});
//删除数据:
public int deleteUserBean(UserBean userBean){
int count = db.delete(TABLE_NAME,0); white-space:pre">}
}
添加的activity布局:activity_user_add.xml
<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">
<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="id" />
<EditText
android:id="@+id/etId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入id,用于删除和修改"/>
</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/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入姓名"/>
</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/etHobby"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入爱好"/>
</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/etHeight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入身高"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btAddOK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="确定"/>
<Button
android:id="@+id/btAddCancle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="返回"/>
</LinearLayout>
</LinearLayout>
添加操作的java代码:
package com.example.day05_01;
import android.support.v7.app.ActionBaractivity;
import android.text.TextUtils;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.sqliteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class UserAddActivity extends ActionBaractivity {
private EditText etId,etUserName,etHobby,etHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_add);
init();
setListener();
}
private void init() {
// Todo Auto-generated method stub
etId = (EditText) findViewById(R.id.etId);
etUserName = (EditText) findViewById(R.id.etUserName);
etHobby = (EditText) findViewById(R.id.etHobby);
etHeight = (EditText) findViewById(R.id.etHeight);
}
private void setListener() {
// Todo Auto-generated method stub
findViewById(R.id.btAddOK).setonClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Todo Auto-generated method stub
String name = etUserName.getText().toString();
if(TextUtils.isEmpty(name)){
etUserName.setError("姓名必填");
return;
}
String hobby = etHobby.getText().toString();
if(TextUtils.isEmpty(hobby)){
etHobby.setError("爱好必填");
return;
}
String height = etHeight.getText().toString();
if(TextUtils.isEmpty(height)){
etHeight.setError("身高必填");
return;
}
Intent intent = new Intent(UserAddActivity.this,MainActivity.class);
UserBean userBean = new UserBean(name,height);
intent.putExtra("userBean",userBean);
setResult(RESULT_OK,intent);
finish();
}
});
findViewById(R.id.btAddCancle).setonClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// Todo Auto-generated method stub
finish();
}
});
}
}
修改操作的布局:activity_user_update.xml
<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">
<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="id" />
<EditText
android:id="@+id/etupdateId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入id,用于删除和修改"/>
</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/etUpdateUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入姓名"/>
</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/etUpdateHobby"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入爱好"/>
</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/etUpdateHeight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入身高"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btUpdateOK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="确定"/>
<Button
android:id="@+id/btUpdateCancle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="返回"/>
</LinearLayout>
</LinearLayout>
修改操作的java代码:
package com.example.day05_01;
import android.support.v7.app.ActionBaractivity;
import android.text.TextUtils;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
public class UserUpdateActivity extends ActionBaractivity {
private int id;
private EditText etUpdateId,etUpdateUserName,etUpdateHobby,etUpdateHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_update);
init();
initData();
setListener();
}
private void init() {
// Todo Auto-generated method stub
etUpdateId = (EditText) findViewById(R.id.etupdateId);
etUpdateUserName = (EditText) findViewById(R.id.etUpdateUserName);
etUpdateHobby = (EditText) findViewById(R.id.etUpdateHobby);
etUpdateHeight = (EditText) findViewById(R.id.etUpdateHeight);
}
private void initData() {
// Todo Auto-generated method stub
Intent intent = getIntent();
UserBean userBean = (UserBean) intent.getSerializableExtra("userBean");
etUpdateId.setText(userBean.getId()+"");
etUpdateUserName.setText(userBean.getName());
etUpdateHobby.setText(userBean.getHobby());
etUpdateHeight.setText(userBean.getHeight());
id = userBean.getId();
}
private void setListener() {
// Todo Auto-generated method stub
findViewById(R.id.btUpdateOK).setonClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Todo Auto-generated method stub
String userId = etUpdateId.getText().toString();
if(TextUtils.isEmpty(userId)){
etUpdateId.setError("id必填");
return;
}
String name = etUpdateUserName.getText().toString();
if(TextUtils.isEmpty(name)){
etUpdateUserName.setError("姓名必填");
return;
}
String hobby = etUpdateHobby.getText().toString();
if(TextUtils.isEmpty(hobby)){
etUpdateHobby.setError("爱好必填");
return;
}
String height = etUpdateHeight.getText().toString();
if(TextUtils.isEmpty(height)){
etUpdateHeight.setError("身高必填");
return;
}
Intent intent = new Intent(UserUpdateActivity.this,MainActivity.class);
UserBean userBean = new UserBean(id,intent);
finish();
}
});
findViewById(R.id.btUpdateCancle).setonClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// Todo Auto-generated method stub
finish();
}
});
}
}
效果:
android SQLite 使用 SQLiteOpenHelper 类对数据库进行操作
一、 SQLite 介绍SQLite 是 android 内置的一个很小的关系型数据库。
SQLite 的官网是 http://www.sqlite.org/,可以去下载一些文档或相关信息。
博客中有一篇有稍微详细一点的介绍,大家可以去看一下。
二、 SQLiteOpenHelper 的使用方法
SQLiteOpenHelper 是一个辅助类来管理数据库的创建和版本。
可以通过继承这个类,实现它的一些方法来对数据库进行一些操作。
所有继承了这个类的类都必须实现下面这样的一个构造方法:
public DatabaseHelper(Context context, String name, CursorFactory factory, int version)
第一个参数:Context 类型,上下文对象。
第二个参数:String 类型,数据库的名称
第三个参数:CursorFactory 类型
第四个参数:int 类型,数据库版本
下面是这个类的几个方法:
方法名 返回类型 描述 备注
getReadableDatabase () synchronized SQLiteDatabase 创建或打开一个数据库 可以通过这两个方法返回的 SQLiteDatabase 对象对数据库进行一系列的操作,如新建一个表,插入一条数据等
getWritableDatabase () synchronized SQLiteDatabase 创建或打开一个可以读写的数据库
onCreate (SQLiteDatabase db) abstract void 第一次创建的时候调用
onOpen (SQLiteDatabase db) void 打开数据库
onUpgrade (SQLiteDatabase db,int oldVersion,int newVersion) abstract void 升级数据库
close () synchronized void 关闭所有打开的数据库对象
下面有一个例子,当点击按钮时进行相应的操作,效果图如下:

介于代码中有详细备注了,在此我就不多写了,直接贴代码了,代码如下:
DatabaseHelper 类:

- package android.sqlite;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- /**
- * SQLiteOpenHelper 是一个辅助类,用来管理数据库的创建和版本他,它提供两个方面的功能
- * 第一,getReadableDatabase ()、getWritableDatabase () 可以获得 SQLiteDatabase 对象,通过该对象可以对数据库进行操作
- * 第二,提供了 onCreate ()、onUpgrade () 两个回调函数,允许我们再创建和升级数据库时,进行自己的操作
- */
- public class DatabaseHelper extends SQLiteOpenHelper {
- private static final int VERSION = 1;
- /**
- * 在 SQLiteOpenHelper 的子类当中,必须有该构造函数
- * @param context 上下文对象
- * @param name 数据库名称
- * @param factory
- * @param version 当前数据库的版本,值必须是整数并且是递增的状态
- */
- public DatabaseHelper(Context context, String name, CursorFactory factory,
- int version) {
- // 必须通过 super 调用父类当中的构造函数
- super(context, name, factory, version);
- }
- public DatabaseHelper(Context context, String name, int version){
- this(context,name,null,version);
- }
- public DatabaseHelper(Context context, String name){
- this(context,name,VERSION);
- }
- // 该函数是在第一次创建的时候执行,实际上是第一次得到 SQLiteDatabase 对象的时候才会调用这个方法
- @Override
- public void onCreate(SQLiteDatabase db) {
- // TODO Auto-generated method stub
- System.out.println("create a database");
- //execSQL 用于执行 SQL 语句
- db.execSQL("create table user(id int,name varchar(20))");
- }
- @Override
- public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
- // TODO Auto-generated method stub
- System.out.println("upgrade a database");
- }
- }
Activity 类:

- package android.sqlite;
- import android.app.Activity;
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class SQLiteActivity extends Activity {
- /** Called when the activity is first created. */
- private Button createDatabaseButton = null;
- private Button updateDatabaseButton = null;
- private Button insertButton = null;
- private Button updateButton = null;
- private Button selectButton = null;
- private Button deleteButton = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // 根据控件 id 获得相应的控件对象
- createDatabaseButton = (Button) findViewById(R.id.createDatabase);
- updateDatabaseButton = (Button) findViewById(R.id.updateDatabase);
- insertButton = (Button) findViewById(R.id.insert);
- updateButton = (Button) findViewById(R.id.update);
- selectButton = (Button) findViewById(R.id.select);
- deleteButton = (Button) findViewById(R.id.delete);
- // 为按钮设置监听器
- createDatabaseButton
- .setOnClickListener(new CreateDatabaseOnClickListener());
- updateDatabaseButton
- .setOnClickListener(new UpdateDatabaseOnClickListener());
- insertButton.setOnClickListener(new InsertOnClickListener());
- updateButton.setOnClickListener(new UpdateOnClickListener());
- selectButton.setOnClickListener(new SelectOnClickListener());
- deleteButton.setOnClickListener(new DeleteOnClickListener());
- }
- // createDatabaseButton 点击事件监听器
- class CreateDatabaseOnClickListener implements OnClickListener {
- public void onClick(View v) {
- // 创建了一个 DatabaseHelper 对象,只执行这句话是不会创建或打开连接的
- DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
- "test_yangyz_db");
- // 只有调用了 DatabaseHelper 的 getWritableDatabase () 方法或者 getReadableDatabase () 方法之后,才会创建或打开一个连接
- SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
- }
- }
- // updateDatabaseButton 点击事件监听器
- class UpdateDatabaseOnClickListener implements OnClickListener {
- public void onClick(View v) {
- // TODO Auto-generated method stub
- DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
- "test_yangyz_db", 2);
- // 得到一个只读的 SQLiteDatabase 对象
- SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
- }
- }
- // insertButton 点击事件监听器
- class InsertOnClickListener implements OnClickListener {
- public void onClick(View v) {
- // 创建 ContentValues 对象
- ContentValues values = new ContentValues();
- // 向该对象中插入键值对,其中键是列名,值是希望插入到这一列的值,值必须和数据库当中的数据类型一致
- values.put("id", 1);
- values.put("name", "yangyz");
- // 创建 DatabaseHelper 对象
- DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
- "test_yangyz_db", 2);
- // 得到一个可写的 SQLiteDatabase 对象
- SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
- // 调用 insert 方法,就可以将数据插入到数据库当中
- // 第一个参数:表名称
- // 第二个参数:SQl 不允许一个空列,如果 ContentValues 是空的,那么这一列被明确的指明为 NULL 值
- // 第三个参数:ContentValues 对象
- sqliteDatabase.insert("user", null, values);
- }
- }
- // updateButton 点击事件监听器
- class UpdateOnClickListener implements OnClickListener {
- public void onClick(View v) {
- // 创建一个 DatabaseHelper 对象
- DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
- "test_yangyz_db", 2);
- // 得到一个可写的 SQLiteDatabase 对象
- SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
- // 创建一个 ContentValues 对象
- ContentValues values = new ContentValues();
- values.put("name", "zhangsan");
- // 调用 update 方法
- // 第一个参数 String:表名
- // 第二个参数 ContentValues:ContentValues 对象
- // 第三个参数 String:where 字句,相当于 sql 语句 where 后面的语句,?号是占位符
- // 第四个参数 String []:占位符的值
- sqliteDatabase.update("user", values, "id=?", new String[] { "1" });
- System.out.println("-----------update------------");
- }
- }
- // selectButton 点击事件监听器
- class SelectOnClickListener implements OnClickListener {
- public void onClick(View v) {
- String id = null;
- String name = null;
- // 创建 DatabaseHelper 对象
- DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
- "test_yangyz_db", 2);
- // 得到一个只读的 SQLiteDatabase 对象
- SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
- // 调用 SQLiteDatabase 对象的 query 方法进行查询,返回一个 Cursor 对象:由数据库查询返回的结果集对象
- // 第一个参数 String:表名
- // 第二个参数 String []: 要查询的列名
- // 第三个参数 String:查询条件
- // 第四个参数 String []:查询条件的参数
- // 第五个参数 String: 对查询的结果进行分组
- // 第六个参数 String:对分组的结果进行限制
- // 第七个参数 String:对查询的结果进行排序
- Cursor cursor = sqliteDatabase.query("user", new String[] { "id",
- "name" }, "id=?", new String[] { "1" }, null, null, null);
- // 将光标移动到下一行,从而判断该结果集是否还有下一条数据,如果有则返回 true,没有则返回 false
- while (cursor.moveToNext()) {
- id = cursor.getString(cursor.getColumnIndex("id"));
- name = cursor.getString(cursor.getColumnIndex("name"));
- }
- System.out.println("-------------select------------");
- System.out.println("id: "+id);
- System.out.println("name: "+name);
- }
- }
- // deleteButton 点击事件监听器
- class DeleteOnClickListener implements OnClickListener {
- public void onClick(View v) {
- // 创建 DatabaseHelper 对象
- DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,"test_yangyz_db",2);
- // 获得可写的 SQLiteDatabase 对象
- SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
- // 调用 SQLiteDatabase 对象的 delete 方法进行删除操作
- // 第一个参数 String:表名
- // 第二个参数 String:条件语句
- // 第三个参数 String []:条件值
- sqliteDatabase.delete("user", "id=?", new String[]{"1"});
- System.out.println("----------delete----------");
- }
- }
- }
布局文件:

- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Button
- android:id="@+id/createDatabase"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/createDatabaseButton"
- />
- <Button
- android:id="@+id/updateDatabase"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/updateDatabaseButton"
- />
- <Button
- android:id="@+id/insert"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/insertButton"
- />
- <Button
- android:id="@+id/update"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/updateButton"
- />
- <Button
- android:id="@+id/select"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/selectButton"
- />
- <Button
- android:id="@+id/delete"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/deleteButton"
- />
- </LinearLayout>
String 文件:

- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="hello">Hello World, SQLiteActivity!</string>
- <string name="app_name">SQLiteTest</string>
- <string name="createDatabaseButton">createDatabase</string>
- <string name="updateDatabaseButton">updateDatabase</string>
- <string name="insertButton">insert</string>
- <string name="updateButton">update</string>
- <string name="selectButton">select</string>
- <string name="deleteButton">delete</string>
- </resources>
Android SQLiteOpenHelper – 每个表的不同类?
在文章中他有一个提示:
It is good practice to create a separate class per table. This class defines static onCreate() and onUpgrade() methods. These methods are called in the corresponding methods of sqliteOpenHelper. This way your implementation of sqliteOpenHelper stays readable,even if you have several tables.
如果我正确理解了这个提示,我应该为我的数据库中的每个表都有一个类?
这真的是最好的做法吗?
如果是这样,那么使用多个表的复杂查询呢?如果创建在不同的类中,我该如何管理?
如何正确保存数据库版本?对于每个表的更改,我会更改数据库版本号吗?
谢谢
解决方法
快速阅读一个可以解释作者主张为每个表创建一个单独的数据库助手(我最初做过),但事实并非如此.这本来是不好的建议.
重申作者的意图:
>一个数据库助手类.>帮助程序涉及单独的特定于表的帮助程序类,它们不是sqliteOpenHelpers,而只是为顶级数据库帮助程序执行部分工作.
今天的关于android – SQLiteOpenHelper错误的分享已经结束,谢谢您的关注,如果想了解更多关于12.Android-SQLiteOpenHelper使用、andriod之SQLite--SQLiteOpenHelper用法、android SQLite 使用 SQLiteOpenHelper 类对数据库进行操作、Android SQLiteOpenHelper – 每个表的不同类?的相关知识,请在本站进行查询。
本文标签: