andriod之SQLite--SQLiteOpenHelper用法

前端之家收集整理的这篇文章主要介绍了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();




private void createTable(sqliteDatabase db) {
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();

int count = (int) db.insert(TABLE_NAME,0); white-space:pre">return count;
//修改数据:
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();
}
});
}

}

效果




猜你在找的Sqlite相关文章