編輯:Android編程入門
關於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提醒沒有此用戶,還有一些細節感興趣的朋友可以自己進行維護,謝謝大家。
注:本文涉及的demo的地址:https://github.com/absfree/TouchDispatch1. 觸摸動作及事件序列(1)觸摸事件的動作 &n
activity_data1.xml<?xml version=1.0 encoding=utf-8?><LinearLayout xmlns:andr
當啟動Android Studio時,如果彈出adb not responding. you can wait more,or kill adb.exe pro
這個月裝逼有點少了,為什麼呢,因為去考軟件射雞師了,快到兒童節了,趕緊寫篇博紀念一下逝去的青春,唔,請忽略這句話。 二維碼其實有很多種,但是我們常見的微信使用的