您的位置:首页 > 移动开发 > Android开发

Android的SQLiteDataBase小项目,实现user类登陆注册以及student类增删改查

2016-04-03 03:12 676 查看
关于SQLiteDataBase这块,大体有两种主要的实现方式,一种是不使用Helper类的方式,此种方式存在一个弊端,即不能oncreate两次,如果重复使用oncreate的button,则会报错,所以为了避免这种错误,在此项目中使用类继承SQLiteOpenHelper的方式进行SQLite3小型数据库的小项目开发,简单的实现登陆注册,以及对特定vo类的增删改查,中间还夹杂了ListView,ArrayAdapter,以及Intent的散知识点。

以下为正文:
首先介绍以下我写的项目的框架,总的为几个结构。
第一个部分为是所有项目都需要的简单java类,即与表对应的vo类。
第二个部分为Acitivty部分,总的有三个Activity:
1.LoginActivity,登陆界面
2.RegisterAcitivity ,注册界面
3.MainActivity,实现增删改查的界面
第三个部分为逻辑部分,即增删改查之类的方法,sql语句
第四个部分为Helper类

Helper类中

第二个方法OnUpgrade内容为空,因为此处用不到,也可加入DROP TABLE的语句,然后复写oncreate实现表的更新。
此类主要目的是提供构造方法,以及创建数据库表,参数为上下文环境,数据库名,工厂,数据库版本。
在逻辑层以及activity层,实例化此类,能够通过参数传递数据库的内容,实现增删改查,简单的说此类是数据库连接类。

代码如下:

package com.example.sqlitedatabase;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.iotek.entity.Student;

public class MainActivity extends Activity implements OnClickListener {
private EditText et_name;
private EditText et_age;
private EditText et_score;
private EditText et_query;

private Button bt_add;
private Button bt_del;
private Button bt_update;
private Button bt_query;
private Button bt_all;

private ArrayAdapter<String> adapter;
private ListView lv_adapter;
private List<Student> stuList = new ArrayList<Student>();
private String[] data;
// 用来使用其中的增删改查
private StudentBiz studentBiz = new StudentBiz(MainActivity.this);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 关联控件
initView();
// 注册监听button
registerListener();
}

// 注册监听button
private void registerListener() {
bt_add.setOnClickListener(this);
bt_del.setOnClickListener(this);
bt_update.setOnClickListener(this);
bt_query.setOnClickListener(this);
bt_all.setOnClickListener(this);

}

// 关联控件
private void initView() {
et_name = (EditText) findViewById(R.id.et_name);
et_age = (EditText) findViewById(R.id.et_age);
et_score = (EditText) findViewById(R.id.et_score);
et_query = (EditText) findViewById(R.id.et_query);

bt_add = (Button) findViewById(R.id.bt_add);
bt_del = (Button) findViewById(R.id.bt_del);
bt_update = (Button) findViewById(R.id.bt_update);
bt_query = (Button) findViewById(R.id.bt_query);
bt_all = (Button) findViewById(R.id.bt_all);
lv_adapter = (ListView) findViewById(R.id.listView1);
}

// 监听button
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_add:
if(et_age.getText().toString().equals("")||et_score.getText().toString().equals("")||et_name.getText().toString().equals("")){
break;
}
String name = et_name.getText().toString();
int age = Integer.valueOf(et_age.getText().toString());
int score = Integer.valueOf(et_score.getText().toString());
Student student = new Student(name, age, score);
studentBiz.addStudent(student);// 添加到数据库
DynamicData();
break;
case R.id.bt_del:
if(et_query.getText().toString().equals("")){
break;
}
int _id = Integer.valueOf(et_query.getText().toString());

studentBiz.delStudent(_id);

DynamicData();
break;
case R.id.bt_update:
if(et_query.getText().toString().equals("")||et_age.getText().toString().equals("")||et_score.getText().toString().equals("")||et_name.getText().toString().equals("")){
break;
}
int _id1 = Integer.valueOf(et_query.getText().toString());
String name1 = et_name.getText().toString();
int age1 = Integer.valueOf(et_age.getText().toString());
int score1 = Integer.valueOf(et_score.getText().toString());
Student stu_update = new Student(_id1, name1, age1, score1);
studentBiz.updateStudent(stu_update);
if(studentBiz.updateStudent(stu_update)==0){
break;
}
DynamicData();
break;
case R.id.bt_query:
if(et_query.getText().toString().equals("")){
break;
}
int id2 = Integer.valueOf(et_query.getText().toString());

Student stu1 = studentBiz.getStudentById(id2);
if(stu1==null){
Toast.makeText(MainActivity.this, "没有这个学生", Toast.LENGTH_LONG).show();
break;
}

data = new String[] { stu1.toString() };
MakeAdapter();

break;
case R.id.bt_all:
DynamicData();
for (Student stu : stuList) {
Log.i("student", stu.toString());
}
break;

default:
break;
}
}

/**
* 实时刷新数据
*/
private void DynamicData() {
studentBiz = new StudentBiz(MainActivity.this);
stuList = studentBiz.getAllStudents();
SetData();
MakeAdapter();
}

/**
* 设置adapter数据
*/
private void SetData() {
data = new String[stuList.size()];
for (int i = 0; i < data.length; i++) {
data[i] = stuList.get(i).toString();
}
}

/**
* 适配器
*/
private void MakeAdapter() {

adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.item,
R.id.tv_item, data);
lv_adapter.setAdapter(adapter);

}

/**
* 查询所有数据
*/
private void SelectAll() {
studentBiz = new StudentBiz(MainActivity.this);
stuList = studentBiz.getAllStudents();
for (Student stu : stuList) {
Log.i("student", stu.toString());
}
}
}


package com.example.sqlitedatabase;

import android.app.Activity;
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.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {
private EditText et_username, et_password;
private Button bt_log, bt_reg;
private UserService userService = new UserService(LoginActivity.this);

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
findView();
registerListener();
}

private void registerListener() {
bt_log.setOnClickListener(this);
bt_reg.setOnClickListener(this);

}

private void findView() {
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
bt_log = (Button) findViewById(R.id.bt_log);
bt_reg = (Button) findViewById(R.id.bt_reg);
}

@Override
public void onClick(View view) {
switch (view.getId()) {
/**
* 登陆
*/
case R.id.bt_log:
String Uname = et_username.getText().toString();
String Upass = et_password.getText().toString();
// 登陆成功返回的flag是true
boolean flag = userService.Login(Uname, Upass);
if (flag) {
Intent intent = new Intent();
intent.setClass(LoginActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "没有此用户,请注册",
Toast.LENGTH_LONG).show();
}
break;
/**
* 注册
*/
case R.id.bt_reg:
Intent intent = new Intent();
intent.setClass(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
break;
default:
break;
}

}
}


package com.example.sqlitedatabase;

import android.app.Activity;
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.Toast;

public class RegisterActivity extends Activity {
private EditText et_regname, et_regpsw;
private Button bt_reg;
private UserService service = new UserService(RegisterActivity.this);

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
/**
* 关联控件
*/
findView();
/**
* 注册button的监听
*/
registerListener();
}

private void registerListener() {
bt_reg.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
String Uname = et_regname.getText().toString();
String Upass = et_regpsw.getText().toString();
boolean flag = service.Register(Uname, Upass);
/**
* flag为Register方法返回值,成功为true
*/
if (flag) {
Intent intent = new Intent();
intent.setClass(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
} else {
Toast.makeText(RegisterActivity.this, "注册失败,重新注册",
Toast.LENGTH_LONG).show();
}

}
});

}

private void findView() {
et_regname = (EditText) findViewById(R.id.et_regname);
et_regpsw = (EditText) findViewById(R.id.et_regpsw);
bt_reg = (Button) findViewById(R.id.reg_button);
}
}


package com.example.sqlitedatabase;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**
* 这个类是sqlite数据路的一个帮助类,主要用来创建数据库和表,或者多表进行修改(管理数据库)
*
* @author Administrator
*
*/
public class DBHelper extends SQLiteOpenHelper {
private static final String DBNAME = "data.db";
private static final int VERSION = 1;

/**
* 数据库和oncreate方法都是在第一次调用getWritableDatabase() or getReadableDatabase()
* 方法的时候才会创建数据库和数据表
*
* @param context
*/
public DBHelper(Context context) {
super(context, DBNAME, null, VERSION);
}

/**
* SQLiteDatabase用来操作数据库的一个对象,内部提供很多方法来操作
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table student(_id integer primary key autoincrement,name varchar(20)"
+ " not null,age integer check(age>=18 and age<=100),score integer);");
db.execSQL("create table user(id integer primary key autoincrement,username varchar(64),"
+ "password varchar(64))");
}

/**
* 当安装的时候发现数据库版本号比以前的数据库版本号高,就会执行此方法来进行对 数据库进行更新
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}


package com.example.sqlitedatabase;

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.util.Log;

import com.iotek.entity.Student;

public class StudentBiz {
private DBHelper dbHelper = null;

public StudentBiz(Context context) {
dbHelper = new DBHelper(context);
}

/**
* 添加一个学生
*
* @param stu
* @return
*/
public long addStudent(Student stu) {
/**
* 这行代码一定要有,getWritableDatabase()获取SQLiteDatabase实例,才能创建出表
*/
SQLiteDatabase db = dbHelper.getWritableDatabase();
/*
* db.execSQL("insert into student(name,age,score)values(?,?,?)", new
* Object[] { stu.getName(), stu.getAge(), stu.getScore() });
*/
ContentValues values = new ContentValues();
values.put("name", stu.getName());
values.put("age", stu.getAge());
values.put("score", stu.getScore());
// insert into student() values()
long id = db.insert("student", null, values);// 返回的是记录的id
Log.i("add", id+"");
return id;
}

/**
* 删除一个学生
*
* @param _id
* @return
*/
public int delStudent(int _id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// db.execSQL("delete from student where _id=?", new Object[] { _id });
int rows = db.delete("student", "_id=?", new String[] { _id + "" });// 返回影响的行数
return rows;
}

/**
* 更新一个学生信息
*
* @param stu
* @return
*/
public int updateStudent(Student stu) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
/*
* db.execSQL( "update student set name=?,age=?,score=? where _id=?",
* new Object[] { stu.getName(), stu.getAge(), stu.getScore(),
* stu.get_id() });
*/
ContentValues values = new ContentValues();
values.put("name", stu.getName());
values.put("age", stu.getAge());
values.put("score", stu.getScore());
int rows = db.update("student", values, "_id=?",
new String[] { stu.get_id() + "" });
return rows;
}

/**
* 得到所有的学生
*
* @return
*/
public List<Student> getAllStudents() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
List<Student> stuList = new ArrayList<Student>();
// 返回的是游标
/*
* Cursor cursor = db.rawQuery("select _id,name,age,score from student",
* null);
*/
Cursor cursor = db.query("student", new String[] { "_id", "name",
"age", "score" }, null, null, null, null, null);
while (cursor.moveToNext()) {
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
int score = cursor.getInt(cursor.getColumnIndex("score"));
stuList.add(new Student(_id, name, age, score));

}
return stuList;
}

/**
* 根据学号查询一个学生
*
* @param _id
* @return
*/
public Student getStudentById(int _id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Student stu = null;
// 返回的是游标
/*
* Cursor cursor = db.rawQuery(
* "select _id,name,age,score from student where _id=?", new String[] {
* _id + "" });
*/

Cursor cursor = db.query("student", new String[] { "_id", "name", "age", "score" },
"_id=?", new String[] { _id + "" }, null, null, null);
if (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
int score = cursor.getInt(cursor.getColumnIndex("score"));
stu = new Student(id, name, age, score);

}
return stu;
}

}


package com.example.sqlitedatabase;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class UserService {
private DBHelper helper=null;
public UserService(Context context) {
helper = new DBHelper(context);
}
/**
* 用户登录
* 参数为用户名和密码,在activity从editTEXT中获得
* @param username
* @param password
* @return
*/
public boolean Login(String username, String password) {
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
String sql = "select * from user where username = ? and password = ? ";
Cursor rawQuery = sqLiteDatabase.rawQuery(sql, new String[] { username,
password });
if (rawQuery.moveToFirst() == true) {
rawQuery.close();
return true;
}
return false;
}
public boolean Register(String username,String password){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
sqLiteDatabase.execSQL("insert into user(username,password)values(?,?)", new
Object[] { username, password});
return true;

}

}


<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"
tools:context=".MainActivity" >

<EditText
android:id="@+id/et_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="请输入名字" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/et_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/et_name"
android:ems="10"
android:hint="请输入年龄(18-100)" />

<EditText
android:id="@+id/et_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/et_age"
android:ems="10"
android:hint="请输入分数(数值类型)" />

<Button
android:id="@+id/bt_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/et_score"
android:text="添加" />

<Button
android:id="@+id/bt_del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/bt_add"
android:layout_alignBottom="@+id/bt_add"
android:layout_toRightOf="@+id/bt_add"
android:text="删除" />

<Button
android:id="@+id/bt_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/bt_del"
android:layout_alignBottom="@+id/bt_del"
android:layout_toRightOf="@+id/bt_del"
android:text="更新" />

<Button
android:id="@+id/bt_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/et_score"
android:layout_toRightOf="@+id/bt_update"
android:text="查询" />

<Button
android:id="@+id/bt_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/bt_query"
android:layout_alignBottom="@+id/bt_query"
android:layout_alignParentRight="true"
android:text="全部" />

<EditText
android:id="@+id/et_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/bt_add"
android:ems="10"
android:hint="请输入查询的(整数值)" />

<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/et_query" >
</ListView>

</RelativeLayout>


item:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/tv_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />

</LinearLayout>


login

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:id="@+id/bt_log"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/bt_reg"
android:text="登陆" />

<Button
android:id="@+id/bt_reg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="注册" />

<TextView
android:id="@+id/tv_psw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/bt_log"
android:layout_marginBottom="36dp"
android:layout_toLeftOf="@+id/bt_log"
android:text="密码" />

<EditText
android:id="@+id/et_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tv_psw"
android:layout_alignBottom="@+id/tv_psw"
android:layout_alignLeft="@+id/bt_log"
android:hint="请输入密码"
android:ems="10" />

<EditText
android:id="@+id/et_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="52dp"
android:layout_toRightOf="@+id/tv_username"
android:hint="请输入用户名"
android:ems="10" >

<requestFocus />
</EditText>

<TextView
android:id="@+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/et_username"
android:layout_alignBottom="@+id/et_username"
android:layout_alignRight="@+id/tv_psw"
android:text="用户名" />

</RelativeLayout>


register:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:id="@+id/reg_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="101dp"
android:layout_marginTop="177dp"
android:text="注册" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="32dp"
android:text="用户名" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="28dp"
android:text="密码" />

<EditText
android:id="@+id/et_regname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_marginLeft="24dp"
android:layout_toRightOf="@+id/textView1"
android:ems="10"
android:hint="请注册您的用户名"
android:inputType="textPersonName" />

<EditText
android:id="@+id/et_regpsw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/et_regname"
android:ems="10"
android:hint="请注册您的密码"
android:inputType="textPassword" >

<requestFocus />
</EditText>

</RelativeLayout>


以上就是整个项目的代码,整个流程是在Helper类里连接数据库,然后通过构造方法把参数传递,在逻辑层(增删改查,登陆注册方法sql语句)实例化helper打开数据库,再在Acitivity层做判断,实现button监听,以及Adapter的构造,Listview的刷新,Acitivity之间通过Intent切换,采用的是不带内容参数的传递,只需要界面切换即可,项目中还有一些细节没有进一步处理,基本的bug已解决,如输入的id为空或者不存在,根据id查询会Toast提醒没有此用户,还有一些细节感兴趣的朋友可以自己进行维护,谢谢大家。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: