Android学习中关于SQLite的一个小Demo(数据库的创建、数据的增删查改)
来源:互联网 发布:c语言中文网知乎 编辑:程序博客网 时间:2024/05/22 23:58
最近学习Android,做了一些小的东西,一直没有时间做个总结。经常总结对于学习新东西是很好的,说以今天整理一下自己做的东西,希望这样也有助于其他人学习。
我做的是一个基于Android平台,使用SQLite构建数据库,并且创建表来存储数据,还会涉及到数据的增删查改。整体的效果图如下:
上面就是Demo在调试时的几幅图,下面将会一一介绍这个Demo中用到的一些核心技术。
首先就是用到了SQLiteOpenHelper这个类,通过创建一个自己的帮助类来继承这个抽象类,来实现简单的对数据库创建和升级。SQLiteOpenHelper中有两个抽象方法,分别是onCreate()和onUpgrade(),我们必须在自己的帮助类里面重写这两个方法,然后分别在这两个方法中去实现创建、升级数据库的逻辑。SQLiteOpenHelper中有两个非常重要的实例方法,getReadableDatabase()和getWritableDatabase()。这两个方法都可以创建和打开一个现有的数据库(如果数据库已经存在则直接打开,否则创建一个新的数据库),并返回一个可对数据库进行读写操作的对象。不同的是,当数据库不可写入的时候(如磁盘空间已满)getReadabelDatabase()方法返回的对象将以只读的方式去打开数据库,而getWritableDatabase()方法则会出现异常。
MyDatabaseHelper.java
public class MyDatabaseHelper extends SQLiteOpenHelper { private static final String CREATE_TABLE = "create table peopleinfo (_id integer primary key autoincrement,name text not null,age integer,height float);"; private Context mContext; public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); mContext = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exists peopleinfo"); onCreate(db); }}
“drop table if exists peopleinfo”这句代码的作用就是当发现数据库中已经存在peopleinfo表,就将这两个表删除掉 ,然后调用onCreate()方法去重新创建。
构建People用来存储输入的People信息,方便向数据库中存储。
People.java
public class People { public int ID; public String Name; public int Age; public float Height; public int getID() { return ID; } public void setID(int iD) { ID = iD; } public String getName() { return Name; } public void setName(String name) { Name = name; } public int getAge() { return Age; } public void setAge(int age) { Age = age; } public float getHeight() { return Height; } public void setHeight(float height) { Height = height; } @Override public String toString(){ String result = ""; result += "ID:" + this.ID + ","; result += "姓名:" + this.Name + ","; result += "年龄:" + this.Age + ", "; result += "身高:" + this.Height ; return result; }}
activity_main.xml:主界面的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 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" android:layout_margin="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="姓名:" android:textSize="23sp"/> <EditText android:id="@+id/edt_name" 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" android:layout_marginLeft="10dp" android:layout_marginRight="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="年龄:" android:textSize="23sp"/> <EditText android:id="@+id/edt_age" android:layout_width="match_parent" android:layout_height="wrap_content" android:numeric="integer" android:hint="请输入年龄"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="身高:" android:textSize="23sp"/> <EditText android:id="@+id/edt_height" android:layout_width="match_parent" android:layout_height="wrap_content" android:numeric="decimal" android:hint="请输入身高"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:orientation="horizontal"> <Button android:id="@+id/bt_adddata" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="添加数据" android:textSize="12sp" android:layout_weight="1"/> <Button android:id="@+id/bt_showalldata" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="全部显示" android:textSize="12sp" android:layout_weight="1"/> <Button android:id="@+id/bt_clearshowdata" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清除显示" android:textSize="12sp" android:layout_weight="1"/> <Button android:id="@+id/bt_deletealldata" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="全部删除" android:textSize="12sp" android:layout_weight="1"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ID:" android:textSize="23sp"/> <EditText android:id="@+id/edt_id" android:layout_width="40dp" android:layout_height="wrap_content" android:numeric="integer" android:layout_weight="1"/> <Button android:id="@+id/bt_deteleid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ID删除" android:textSize="12sp" android:layout_weight="1"/> <Button android:id="@+id/bt_queryid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ID查询" android:textSize="12sp" android:layout_weight="1"/> <Button android:id="@+id/bt_updateid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ID更新" android:textSize="12sp" android:layout_weight="1"/> </LinearLayout> <TextView android:layout_margin="10dp" android:id="@+id/txt_sjk" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="数据库:" android:textSize="23sp"/> <ListView android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:id="@+id/listview_show" android:layout_width="match_parent" android:layout_height="wrap_content"/></LinearLayout>
MainActivity.java
public class MainActivity extends Activity implements OnClickListener { private MyDatabaseHelper dbHelper; private SQLiteDatabase db; private EditText edt_Name; private EditText edt_Age; private EditText edt_Height; private EditText edt_Id; private Button bt_AddData; private Button bt_ShowAllData; private Button bt_ClearShowData; private Button bt_DeleteAllData; private Button bt_DeleteById; private Button bt_QueryById; private Button bt_UpdateById; private ListView listview_show; private String strName = ""; private String strAge = ""; private String strHeight = ""; private int m_Id; private List<People> PeopleList = new ArrayList<People>(); private MyAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper = new MyDatabaseHelper(this, "people.db", null, 1); db = dbHelper.getWritableDatabase(); // 初始化控件 initShow(); // 添加数据 bt_AddData.setOnClickListener(this); // 全部显示 bt_ShowAllData.setOnClickListener(this); // 清楚显示 bt_ClearShowData.setOnClickListener(this); // 全部删除 bt_DeleteAllData.setOnClickListener(this); // ID删除 bt_DeleteById.setOnClickListener(this); // ID查询 bt_QueryById.setOnClickListener(this); // ID更新 bt_UpdateById.setOnClickListener(this); } // 初始化控件 private void initShow() { edt_Name = (EditText) findViewById(R.id.edt_name); edt_Age = (EditText) findViewById(R.id.edt_age); edt_Height = (EditText) findViewById(R.id.edt_height); edt_Id = (EditText) findViewById(R.id.edt_id); bt_AddData = (Button) findViewById(R.id.bt_adddata); bt_ShowAllData = (Button) findViewById(R.id.bt_showalldata); bt_ClearShowData = (Button) findViewById(R.id.bt_clearshowdata); bt_DeleteAllData = (Button) findViewById(R.id.bt_deletealldata); bt_DeleteById = (Button) findViewById(R.id.bt_deteleid); bt_QueryById = (Button) findViewById(R.id.bt_queryid); bt_UpdateById = (Button) findViewById(R.id.bt_updateid); listview_show = (ListView) findViewById(R.id.listview_show); } // listview显示数据库数据 private void showData() { mAdapter = new MyAdapter(MainActivity.this, android.R.layout.simple_list_item_1, PeopleList); listview_show.setAdapter(mAdapter); } // 获取edittext中输入的ID public int getEd_ID() { if (!edt_Id.getText().toString().equals("")) { String strId = edt_Id.getText().toString(); m_Id = Integer.parseInt(strId); } else { m_Id = -1; } return m_Id; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { switch (v.getId()) { // 添加数据 case R.id.bt_adddata: addData(); edt_Name.setText(""); edt_Age.setText(""); edt_Height.setText(""); break; // 全部显示 case R.id.bt_showalldata: showAllData(); showData(); break; // 清楚显示 case R.id.bt_clearshowdata: clearListView(); showData(); break; // 全部删除 case R.id.bt_deletealldata: deleteData(); showData(); break; // ID删除 case R.id.bt_deteleid: m_Id = getEd_ID(); deleteById(m_Id); showAllData(); showData(); edt_Id.setText(""); break; // ID查询 case R.id.bt_queryid: m_Id = getEd_ID(); queryById(m_Id); showData(); edt_Id.setText(""); break; // ID更新 case R.id.bt_updateid: m_Id = getEd_ID(); updateById(m_Id); showData(); edt_Id.setText(""); break; } } // ID更新 private void updateById(int mId) { if (mId == -1) { Toast.makeText(MainActivity.this, "请输入ID号", Toast.LENGTH_SHORT) .show(); } else { // 先找到这条数据 db = dbHelper.getReadableDatabase(); final People people = new People(); List<People> tempList=new ArrayList<People>(); Cursor cursor = db.query("peopleinfo", null, "_id" + "=" + mId, null, null, null, null); if (cursor.moveToFirst()) { do { int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor .getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); float height = cursor.getFloat(cursor .getColumnIndex("height")); people.setID(id); people.setName(name); people.setAge(age); people.setHeight(height); tempList.add(people); } while (cursor.moveToNext()); } cursor.close(); if (tempList.size()==0) { Toast.makeText(MainActivity.this, "数据库中没有这条信息", Toast.LENGTH_SHORT).show(); } else { // 弹出自定义的AlertDialog LayoutInflater factory = LayoutInflater.from(this); final View textChangeView = factory.inflate(R.layout.custom, null); final EditText editTextName = (EditText) textChangeView .findViewById(R.id.cEdt_name); final EditText editTextAge = (EditText) textChangeView .findViewById(R.id.cEdt_age); final EditText editTextHeight = (EditText) textChangeView .findViewById(R.id.cEdt_height); editTextName.setText(people.getName()); editTextAge.setText(Integer.toString(people.getAge())); editTextHeight.setText(Float.toString(people.getHeight())); AlertDialog.Builder ad = new AlertDialog.Builder( MainActivity.this); ad.setTitle("ID更新:"); ad.setIcon(android.R.drawable.ic_dialog_info); ad.setView(textChangeView); ad.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ContentValues updateValues = new ContentValues(); strName = editTextName.getText().toString(); strAge = editTextAge.getText().toString(); strHeight = editTextHeight.getText().toString(); int iAge = Integer.parseInt(strAge); float fHeight = Float.parseFloat(strHeight); // 开始组装一条数据 updateValues.put("name", strName); updateValues.put("age", iAge); updateValues.put("height", fHeight); db.update("peopleinfo", updateValues, "_id" + "=" + people.getID(), null); Toast.makeText(MainActivity.this, "更新成功", Toast.LENGTH_SHORT).show(); Cursor cursor = db.query("peopleinfo", null, "_id" + "=" + people.getID(), null, null, null, null); PeopleList.clear(); if (cursor.moveToFirst()) { do { int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor .getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); float height = cursor.getFloat(cursor .getColumnIndex("height")); people.setID(id); people.setName(name); people.setAge(age); people.setHeight(height); PeopleList.add(people); } while (cursor.moveToNext()); } cursor.close(); } }); ad.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); ad.show(); } } } // ID查询 private void queryById(int mId) { if (mId == -1) { Toast.makeText(MainActivity.this, "请输入ID号", Toast.LENGTH_SHORT) .show(); } else { db = dbHelper.getReadableDatabase(); People people = new People(); PeopleList.clear(); Cursor cursor = db.query("peopleinfo", null, "_id" + "=" + mId, null, null, null, null); if (cursor.moveToFirst()) { do { int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor .getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); float height = cursor.getFloat(cursor .getColumnIndex("height")); people.setID(id); people.setName(name); people.setAge(age); people.setHeight(height); PeopleList.add(people); } while (cursor.moveToNext()); } cursor.close(); if (PeopleList.size() == 0) { Toast.makeText(MainActivity.this, "数据库中没有这条数据", Toast.LENGTH_SHORT).show(); } } } // ID删除 private void deleteById(int mId) { if (mId == -1) { Toast.makeText(MainActivity.this, "请输入ID号", Toast.LENGTH_SHORT) .show(); } else { db = dbHelper.getWritableDatabase(); People people = new People(); PeopleList.clear(); Cursor cursor = db.query("peopleinfo", null, "_id" + "=" + mId, null, null, null, null); if (cursor.moveToFirst()) { do { int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor .getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); float height = cursor.getFloat(cursor .getColumnIndex("height")); people.setID(id); people.setName(name); people.setAge(age); people.setHeight(height); PeopleList.add(people); } while (cursor.moveToNext()); } cursor.close(); if (PeopleList.size() == 0) { Toast.makeText(MainActivity.this, "数据库中没有这条数据", Toast.LENGTH_SHORT).show(); } else { db.delete("peopleinfo", "_id" + "=" + mId, null); Toast.makeText(MainActivity.this, "成功删除" + mId + "这条数据", Toast.LENGTH_SHORT).show(); } } } // 全部删除 private void deleteData() { db = dbHelper.getWritableDatabase(); db.delete("peopleinfo", null, null); PeopleList.clear(); Toast.makeText(MainActivity.this, "数据清除成功", Toast.LENGTH_SHORT).show(); } // 清除显示 private void clearListView() { PeopleList.clear(); } // 全部显示 private void showAllData() { PeopleList.clear(); Cursor cursor = db.query("peopleinfo", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { People people = new People(); // 遍历表 int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); float height = cursor.getFloat(cursor.getColumnIndex("height")); people.setID(id); people.setName(name); people.setAge(age); people.setHeight(height); PeopleList.add(people); } while (cursor.moveToNext()); } cursor.close(); if (PeopleList.size() == 0) { Toast.makeText(MainActivity.this, "数据库中没有数据", Toast.LENGTH_SHORT) .show(); } } // 添加数据 private void addData() { if (edt_Name.getText().toString().equals("") && edt_Age.getText().toString().equals("") && edt_Height.getText().toString().equals("")) { AlertDialog.Builder dialog = new AlertDialog.Builder( MainActivity.this); dialog.setTitle("Warn"); dialog.setMessage("请输入完整信息"); dialog.setCancelable(false); dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { edt_Name.setText(""); edt_Age.setText(""); edt_Height.setText(""); } }); dialog.show(); } else { ContentValues values = new ContentValues(); strName = edt_Name.getText().toString(); strAge = edt_Age.getText().toString(); strHeight = edt_Height.getText().toString(); int iAge = Integer.parseInt(strAge); float fHeight = Float.parseFloat(strHeight); // 开始组装一条数据 values.put("name", strName); values.put("age", iAge); values.put("height", fHeight); // 插入数据 db.insert("peopleinfo", null, values); Toast.makeText(MainActivity.this, "数据添加成功", Toast.LENGTH_SHORT) .show(); } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { // TODO Auto-generated method stub if (ev.getAction() == MotionEvent.ACTION_DOWN) { // 获得当前得到焦点的View,一般情况下就是EditText(特殊情况就是轨迹求或者实体案件会移动焦点) View v = getCurrentFocus(); if (isShouldHideInput(v, ev)) { hideSoftInput(v.getWindowToken()); } } return super.dispatchTouchEvent(ev); } /** * 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时没必要隐藏 * * @param v * @param event * @return */ private boolean isShouldHideInput(View v, MotionEvent event) { if (v != null && (v instanceof EditText)) { int[] l = { 0, 0 }; v.getLocationInWindow(l); int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth(); if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) { // 点击EditText的事件,忽略它。 return false; } else { return true; } } // 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditView上,和用户用轨迹球选择其他的焦点 return false; } /** * 多种隐藏软件盘方法的其中一种 * * @param token */ private void hideSoftInput(IBinder token) { if (token != null) { InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS); } }}
custom.xml:自定义布局文件 ,用在ID更新时弹出的AlertDialog中。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 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:layout_margin="10dp" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="姓名:" android:textSize="23sp" /> <EditText android:id="@+id/cEdt_name" 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:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="年龄:" android:textSize="23sp" /> <EditText android:id="@+id/cEdt_age" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入年龄" android:numeric="integer" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="身高:" android:textSize="23sp" /> <EditText android:id="@+id/cEdt_height" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入身高" android:numeric="decimal" /> </LinearLayout></LinearLayout>
这个Demo还是很简单的,我就不做过多的解释了 。各位看了之后,有什么见解欢迎留言交流交流共同进步。
- Android学习中关于SQLite的一个小Demo(数据库的创建、数据的增删查改)
- iOS-->sqlite数据库,数据表创建,数据的增删改查
- Android学习(27) -- 数据存储之SQLite数据库的增删改查
- Android数据库的SQLite增删改查
- android SQLite数据库的增删改查
- android sqlite数据库的增删改查
- Android SQLite数据库的增删改查
- Android数据库Sqlite的增删改查
- android-一个文件搞定SQLite数据库的创建与更新以及增删查改
- android中SQLite数据库的增删改查
- android中数据库sqlite的增删改查
- 学习Android的SQLite中增删改查功能!
- 数据库的增删改查 →创建sqlite数据库
- Android中数据库的创建与增删改查操作
- SQLite数据库的创建、常用方法增删改查
- 数据库:SQLite数据库的增删改查
- SQLite数据库---数据库的增删改查
- Android SQLite的创建以及增删查改的实现
- xfire配置webService的方法步骤
- 欧拉回路、欧拉路径
- VS2008中定位代码前一个大括号的方法
- 微商快速有效获得精准粉丝的技巧分析
- Kafka学习之producer配置(0.8.1版)
- Android学习中关于SQLite的一个小Demo(数据库的创建、数据的增删查改)
- 搭建Qt 5.3.1 for Windows Phone 8开发环境
- 游戏中不能使用点卡
- XmlDocument.LoadXml上的坑
- WIN7 64位找不到Driver do Microsoft Access(*.mdb)ODBC驱动程序
- Android 退出整个应用程序
- IOS开发基础—UITableView的基本使用。
- c#中XML解析文件出错解决方法
- mysql中列转行