Android的SQLiteDataBase小项目,实现user类登陆注册以及student类增删改查
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android的SQLiteDataBase小项目,实现user类登陆注册以及student类增删改查相关的知识,希望对你有一定的参考价值。
关于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层,实例化此类,能够通过参数传递数据库的内容,实现增删改查,简单的说此类是数据库连接类。
代码如下:
1 package com.example.sqlitedatabase; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import android.app.Activity; 7 import android.os.Bundle; 8 import android.util.Log; 9 import android.view.View; 10 import android.view.View.OnClickListener; 11 import android.widget.ArrayAdapter; 12 import android.widget.Button; 13 import android.widget.EditText; 14 import android.widget.ListView; 15 import android.widget.Toast; 16 17 import com.iotek.entity.Student; 18 19 public class MainActivity extends Activity implements OnClickListener { 20 private EditText et_name; 21 private EditText et_age; 22 private EditText et_score; 23 private EditText et_query; 24 25 private Button bt_add; 26 private Button bt_del; 27 private Button bt_update; 28 private Button bt_query; 29 private Button bt_all; 30 31 private ArrayAdapter<String> adapter; 32 private ListView lv_adapter; 33 private List<Student> stuList = new ArrayList<Student>(); 34 private String[] data; 35 // 用来使用其中的增删改查 36 private StudentBiz studentBiz = new StudentBiz(MainActivity.this); 37 38 @Override 39 protected void onCreate(Bundle savedInstanceState) { 40 super.onCreate(savedInstanceState); 41 setContentView(R.layout.activity_main); 42 // 关联控件 43 initView(); 44 // 注册监听button 45 registerListener(); 46 } 47 48 // 注册监听button 49 private void registerListener() { 50 bt_add.setOnClickListener(this); 51 bt_del.setOnClickListener(this); 52 bt_update.setOnClickListener(this); 53 bt_query.setOnClickListener(this); 54 bt_all.setOnClickListener(this); 55 56 } 57 58 // 关联控件 59 private void initView() { 60 et_name = (EditText) findViewById(R.id.et_name); 61 et_age = (EditText) findViewById(R.id.et_age); 62 et_score = (EditText) findViewById(R.id.et_score); 63 et_query = (EditText) findViewById(R.id.et_query); 64 65 bt_add = (Button) findViewById(R.id.bt_add); 66 bt_del = (Button) findViewById(R.id.bt_del); 67 bt_update = (Button) findViewById(R.id.bt_update); 68 bt_query = (Button) findViewById(R.id.bt_query); 69 bt_all = (Button) findViewById(R.id.bt_all); 70 lv_adapter = (ListView) findViewById(R.id.listView1); 71 } 72 73 // 监听button 74 @Override 75 public void onClick(View v) { 76 switch (v.getId()) { 77 case R.id.bt_add: 78 if(et_age.getText().toString().equals("")||et_score.getText().toString().equals("")||et_name.getText().toString().equals("")){ 79 break; 80 } 81 String name = et_name.getText().toString(); 82 int age = Integer.valueOf(et_age.getText().toString()); 83 int score = Integer.valueOf(et_score.getText().toString()); 84 Student student = new Student(name, age, score); 85 studentBiz.addStudent(student);// 添加到数据库 86 DynamicData(); 87 break; 88 case R.id.bt_del: 89 if(et_query.getText().toString().equals("")){ 90 break; 91 } 92 int _id = Integer.valueOf(et_query.getText().toString()); 93 94 studentBiz.delStudent(_id); 95 96 DynamicData(); 97 break; 98 case R.id.bt_update: 99 if(et_query.getText().toString().equals("")||et_age.getText().toString().equals("")||et_score.getText().toString().equals("")||et_name.getText().toString().equals("")){ 100 break; 101 } 102 int _id1 = Integer.valueOf(et_query.getText().toString()); 103 String name1 = et_name.getText().toString(); 104 int age1 = Integer.valueOf(et_age.getText().toString()); 105 int score1 = Integer.valueOf(et_score.getText().toString()); 106 Student stu_update = new Student(_id1, name1, age1, score1); 107 studentBiz.updateStudent(stu_update); 108 if(studentBiz.updateStudent(stu_update)==0){ 109 break; 110 } 111 DynamicData(); 112 break; 113 case R.id.bt_query: 114 if(et_query.getText().toString().equals("")){ 115 break; 116 } 117 int id2 = Integer.valueOf(et_query.getText().toString()); 118 119 Student stu1 = studentBiz.getStudentById(id2); 120 if(stu1==null){ 121 Toast.makeText(MainActivity.this, "没有这个学生", Toast.LENGTH_LONG).show(); 122 break; 123 } 124 125 data = new String[] { stu1.toString() }; 126 MakeAdapter(); 127 128 break; 129 case R.id.bt_all: 130 DynamicData(); 131 for (Student stu : stuList) { 132 Log.i("student", stu.toString()); 133 } 134 break; 135 136 default: 137 break; 138 } 139 } 140 141 /** 142 * 实时刷新数据 143 */ 144 private void DynamicData() { 145 studentBiz = new StudentBiz(MainActivity.this); 146 stuList = studentBiz.getAllStudents(); 147 SetData(); 148 MakeAdapter(); 149 } 150 151 /** 152 * 设置adapter数据 153 */ 154 private void SetData() { 155 data = new String[stuList.size()]; 156 for (int i = 0; i < data.length; i++) { 157 data[i] = stuList.get(i).toString(); 158 } 159 } 160 161 /** 162 * 适配器 163 */ 164 private void MakeAdapter() { 165 166 adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.item, 167 R.id.tv_item, data); 168 lv_adapter.setAdapter(adapter); 169 170 } 171 172 /** 173 * 查询所有数据 174 */ 175 private void SelectAll() { 176 studentBiz = new StudentBiz(MainActivity.this); 177 stuList = studentBiz.getAllStudents(); 178 for (Student stu : stuList) { 179 Log.i("student", stu.toString()); 180 } 181 } 182 }
1 package com.example.sqlitedatabase; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 import android.widget.EditText; 10 import android.widget.TextView; 11 import android.widget.Toast; 12 13 public class LoginActivity extends Activity implements OnClickListener { 14 private EditText et_username, et_password; 15 private Button bt_log, bt_reg; 16 private UserService userService = new UserService(LoginActivity.this); 17 18 @Override 19 protected void onCreate(Bundle savedInstanceState) { 20 // TODO Auto-generated method stub 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.login); 23 findView(); 24 registerListener(); 25 } 26 27 private void registerListener() { 28 bt_log.setOnClickListener(this); 29 bt_reg.setOnClickListener(this); 30 31 } 32 33 private void findView() { 34 et_username = (EditText) findViewById(R.id.et_username); 35 et_password = (EditText) findViewById(R.id.et_password); 36 bt_log = (Button) findViewById(R.id.bt_log); 37 bt_reg = (Button) findViewById(R.id.bt_reg); 38 } 39 40 @Override 41 public void onClick(View view) { 42 switch (view.getId()) { 43 /** 44 * 登陆 45 */ 46 case R.id.bt_log: 47 String Uname = et_username.getText().toString(); 48 String Upass = et_password.getText().toString(); 49 // 登陆成功返回的flag是true 50 boolean flag = userService.Login(Uname, Upass); 51 if (flag) { 52 Intent intent = new Intent(); 53 intent.setClass(LoginActivity.this, MainActivity.class); 54 startActivity(intent); 55 } else { 56 Toast.makeText(LoginActivity.this, "没有此用户,请注册", 57 Toast.LENGTH_LONG).show(); 58 } 59 break; 60 /** 61 * 注册 62 */ 63 case R.id.bt_reg: 64 Intent intent = new Intent(); 65 intent.setClass(LoginActivity.this, RegisterActivity.class); 66 startActivity(intent); 67 break; 68 default: 69 break; 70 } 71 72 } 73 }
1 package com.example.sqlitedatabase; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 import android.widget.EditText; 10 import android.widget.Toast; 11 12 public class RegisterActivity extends Activity { 13 private EditText et_regname, et_regpsw; 14 private Button bt_reg; 15 private UserService service = new UserService(RegisterActivity.this); 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 // TODO Auto-generated method stub 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.register); 22 /** 23 * 关联控件 24 */ 25 findView(); 26 /** 27 * 注册button的监听 28 */ 29 registerListener(); 30 } 31 32 private void registerListener() { 33 bt_reg.setOnClickListener(new OnClickListener() { 34 35 @Override 36 public void onClick(View v) { 37 String Uname = et_regname.getText().toString(); 38 String Upass = et_regpsw.getText().toString(); 39 boolean flag = service.Register(Uname, Upass); 40 /** 41 * flag为Register方法返回值,成功为true 42 */ 43 if (flag) { 44 Intent intent = new Intent(); 45 intent.setClass(RegisterActivity.this, LoginActivity.class); 46 startActivity(intent); 47 } else { 48 Toast.makeText(RegisterActivity.this, "注册失败,重新注册", 49 Toast.LENGTH_LONG).show(); 50 } 51 52 } 53 }); 54 55 } 56 57 private void findView() { 58 et_regname = (EditText) findViewById(R.id.et_regname); 59 et_regpsw = (EditText) findViewById(R.id.et_regpsw); 60 bt_reg = (Button) findViewById(R.id.reg_button); 61 } 62 }
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以上是关于Android的SQLiteDataBase小项目,实现user类登陆注册以及student类增删改查的主要内容,如果未能解决你的问题,请参考以下文章Android使用SQLiteDatabase操作SQLite数据库
Android数据库源码分析-SQLiteDatabase的实现以及多线程行为
Android数据储存之SQLiteDatabase SQLiteOpenHelper类的简单使用
Android 高手进阶教程(十三)之----Android 数据库SQLiteDatabase的使用!!
尝试调用虚拟方法'long android.database.sqlite.SQLiteDatabase.insert [重复]