Android开发之五大存储方式之一数据库存储
来源:互联网 发布:2018淘宝开店流程 编辑:程序博客网 时间:2024/04/28 18:39
废话不多说,直接看代码
activity_main:
<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"> <EditText android:id="@+id/et_search" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="请输入搜索的姓名"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="btn_search" android:text="搜索" /> </LinearLayout> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入姓名" /> <EditText android:id="@+id/et_sex" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入性别" /> <EditText android:id="@+id/et_age" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入年龄" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="btn_insert" android:text="添加" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="btn_delete" android:text="删除" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="btn_select" android:text="查询" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="btn_update" android:text="修改" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="#000000" > <TextView android:id="@+id/tv_id" android:layout_width="0dp" android:background="#ffffff" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="学号" android:layout_margin="3dp" android:textColor="#ff0000" /> <TextView android:id="@+id/tv_name" android:layout_width="0dp" android:background="#ffffff" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="姓名" android:layout_margin="3dp" android:textColor="#ff0000" /> <TextView android:layout_margin="3dp" android:background="#ffffff" android:id="@+id/tv_sex" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="性别" android:textColor="#ff0000" /> <TextView android:background="#ffffff" android:layout_margin="3dp" android:id="@+id/tv_age" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="年龄" android:textColor="#ff0000" /> </LinearLayout> <ListView android:id="@+id/lv_list" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /></LinearLayout>
item_layout:
<?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="wrap_content" android:orientation="horizontal" android:background="#000000" > <TextView android:id="@+id/tv_id" android:layout_width="0dp" android:background="#ffffff" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:layout_margin="3dp" android:textColor="#ff0000" /> <TextView android:id="@+id/tv_name" android:layout_width="0dp" android:background="#ffffff" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:layout_margin="3dp" android:textColor="#ff0000" /> <TextView android:layout_margin="3dp" android:background="#ffffff" android:id="@+id/tv_sex" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:textColor="#ff0000" /> <TextView android:background="#ffffff" android:layout_margin="3dp" android:id="@+id/tv_age" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:textColor="#ff0000" /></LinearLayout>
Student:
package com.example.jhl.jhllearn;/** * Created by Administrator on 2016/11/4. */public class Student { private int id; private String name; private String sex; private int age; 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 getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]"; } public Student(int id, String name, String sex, int age) { super(); this.id = id; this.name = name; this.sex = sex; this.age = age; } public Student() { super(); // TODO Auto-generated constructor stub }}
MyAdapter:
package com.example.jhl.jhllearn;/** * Created by Administrator on 2016/11/4. */import java.util.List;import android.content.Context;import android.view.InflateException;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.TextView;public class MyAdapter extends BaseAdapter { private Context context; private List<Student> oList; private LayoutInflater inflater; public MyAdapter(Context context,List<Student> oList) { this.context=context; this.oList=oList; this.inflater=LayoutInflater.from(context); } @Override public int getCount() { // TODO Auto-generated method stub return oList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return oList.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View v, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; if (v==null) { holder=new ViewHolder(); v=inflater.inflate(R.layout.item_layout, null); holder.tv_id=(TextView)v.findViewById(R.id.tv_id); holder.tv_name=(TextView)v.findViewById(R.id.tv_name); holder.tv_sex=(TextView)v.findViewById(R.id.tv_sex); holder.tv_age=(TextView)v.findViewById(R.id.tv_age); v.setTag(holder); }else { holder=(ViewHolder)v.getTag(); } holder.tv_id.setText( oList.get(position).getId()+""); holder.tv_name.setText( oList.get(position).getName()); holder.tv_sex.setText( oList.get(position).getSex()); holder.tv_age.setText( oList.get(position).getAge()+""); return v; } public class ViewHolder { TextView tv_id,tv_name,tv_sex,tv_age; }}
MySqliteOpenHelper:
package com.example.jhl.jhllearn;/** * Created by Administrator on 2016/11/4. */import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;public class MySqliteOpenHelper extends SQLiteOpenHelper { /** * * @param context * 上下文对象 * @param name * 数据库名称 * @param factory * 游标工厂,默认为空 * @param version */ // resulSet public MySqliteOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { // 当前第一次创建数据库的时候回调 db.execSQL("create table Student(id Integer primary key autoincrement, name varchar(10),sex varchar(4),age Integer)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 当前数据库版本更新后,回调该方法 }}
MainActivity:
package com.example.jhl.jhllearn;import java.util.ArrayList;import java.util.List;import android.os.Bundle;import android.app.Activity;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.view.View;import android.widget.EditText;import android.widget.ListView;import android.widget.Toast;public class MainActivity extends Activity { private EditText et_name, et_sex, et_age, et_search; private ListView lv_list; private List<Student> oList = new ArrayList<Student>(); private MyAdapter adapter; // 称为数据库辅助类,用于创建和更新 private MySqliteOpenHelper helper; // 操作数据库增删改查 private SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_name = (EditText) findViewById(R.id.et_name); et_sex = (EditText) findViewById(R.id.et_sex); et_age = (EditText) findViewById(R.id.et_age); et_search = (EditText) findViewById(R.id.et_search); lv_list = (ListView) findViewById(R.id.lv_list); helper = new MySqliteOpenHelper(this, "student_db", null, 1); /** * getReadableDatabase与getWritableDatabase sqlite数据库有一定的大小 * 当sqlite存取数据到达上线的时候,不能再写入数据 getReadableDatabase方法不允许读取,不允许写 * getWritableDatabase方法不允许写,可允许读 */ db = helper.getWritableDatabase(); } // 向SQLite中插入数据 public void btn_insert(View v) { // insert_sql(); insert(); } /** * 以insert()方法传参方式添加数据 */ public void insert() { String name = et_name.getText().toString(); String sex = et_sex.getText().toString(); String age = et_age.getText().toString(); // table 表名 // nullColumnHack 当我们需要插入数据时,没有明确指定字段名,默认插入数据为空 // values :ContentValues 插入的字段值 ContentValues values = new ContentValues(); values.put("name", name); values.put("sex", sex); values.put("age", Integer.parseInt(age)); // {name="",sex="",age=""} // 返回的是long类型,返回的是当前插入的数据的ID号 long index = db.insert("Student", null, values); if (index >= 0) { Show_Toase("插入成功" + index); } } /** * 以sql语句的形式添加数据 */ public void insert_sql() { String name = et_name.getText().toString(); String sex = et_sex.getText().toString(); String age = et_age.getText().toString(); db.execSQL("insert into Student(name,sex,age) values(?,?,?)", new Object[]{name, sex, Integer.parseInt(age)}); Show_Toase("添加成功"); } public void btn_search(View v) { if (oList.size() > 0) { oList.clear(); } String seach_str = et_search.getText().toString(); Cursor cursor = db.rawQuery("select * from Student where name like ?", new String[]{"%" + seach_str + "%"}); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String sex = cursor.getString(cursor.getColumnIndex("sex")); int age = cursor.getInt(cursor.getColumnIndex("age")); Student student = new Student(id, name, sex, age); oList.add(student); } dateSetChang(); } private void dateSetChang() { if (adapter == null) { adapter = new MyAdapter(this, oList); lv_list.setAdapter(adapter); } else { adapter.notifyDataSetChanged(); } } public void Show_Toase(String text) { Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } // 删除数据 public void btn_delete(View v) { delete(); // delete_sql(); } /** * 以delete()方法实现删除数据 */ public void delete() { String name = et_name.getText().toString(); String sex = et_sex.getText().toString(); String age = et_age.getText().toString(); // table 表名 // whereClause 带有占位符的条件 // whereArgs 条件所对应的值数据 // 当前整型返回的是删除记录的行数 int i = db.delete("Student", "name=? and sex=? and age=?", new String[]{name, sex, age}); if (i > 0) { Show_Toase("删除成功" + i); } } /** * 以sql语句的形式删除数据 */ public void delete_sql() { String name = et_name.getText().toString(); String sex = et_sex.getText().toString(); String age = et_age.getText().toString(); db.execSQL("delete from Student where name=? and sex=? and age=?", new Object[]{name, sex, Integer.parseInt(age)}); Show_Toase("删除成功"); boolean is = false; for (int i = 0; i < oList.size() && !is; i++) { if (oList.get(i).getName().equals(name) && oList.get(i).getSex().equals(sex) && oList.get(i).getAge() == Integer.parseInt(age)) { oList.remove(i); is = true; } } dateSetChang(); } // 查询数据 public void btn_select(View v) { query(); // query_sql(); } /* * 使用query()方法查询数据 */ public void query() { if (oList.size()>0){ oList.clear(); } // table 表名 // columns 查询的列名 // selection 带有占位符的条件 // selectionArgs 条件所对应的值 // groupBy 分组 // having 分组的条件 // orderBy 排序(分为升序ASC,降序DESC) // select * from Student order by id asc Cursor cursor = db.query("Student", null, null, null, null, null, "id asc"); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String sex = cursor.getString(cursor.getColumnIndex("sex")); int age = cursor.getInt(cursor.getColumnIndex("age")); Student student = new Student(id, name, sex, age); oList.add(student); } dateSetChang(); } /* * 使用SQL语句的形式查询数据 */ public void query_sql() { if (oList.size() > 0) { oList.clear(); } Cursor cursor = db.rawQuery("select * from Student", new String[]{}); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String sex = cursor.getString(cursor.getColumnIndex("sex")); int age = cursor.getInt(cursor.getColumnIndex("age")); Student student = new Student(id, name, sex, age); oList.add(student); } dateSetChang(); } // 更新数据 public void btn_update(View v) { // update_sql(); update(); } /** * 以update()方法实现修改数据 */ public void update() { String name = et_name.getText().toString(); String sex = et_sex.getText().toString(); String age = et_age.getText().toString(); // table 表名 // valuse ContentValues 修改后的数据 // whereClause 带占位符的条件 // whereArgs 条件的值 // update Student set name=?,age=? where sex=? ContentValues values = new ContentValues(); values.put("name", name); values.put("age", Integer.parseInt(age)); // 返回值表示执行修改语句后,别修改了的行数 int i = db.update("Student", values, "sex=?", new String[]{sex}); if (i > 0) { Show_Toase("修改成功" + i); } } /* * 以sql语句的形式修改数据 */ public void update_sql() { String name = et_name.getText().toString(); String sex = et_sex.getText().toString(); String age = et_age.getText().toString(); db.execSQL("update Student set name=?,age=? where sex=?", new Object[]{ name, Integer.parseInt(age), sex}); Show_Toase("修改成功"); for (int i = 0; i < oList.size(); i++) { if (oList.get(i).getSex().equals(sex)) { oList.get(i).setName(name); oList.get(i).setAge(Integer.parseInt(age)); } } dateSetChang(); }}
到这里,数据库存储就OVER了,其实上面是有BUG的,比如插入的时候我的条件是根据name,age,sex,如果你有一种未填写的话,是会崩掉的,因为我没判断。这篇文章我只是具体介绍怎么学习操作数据库,其他的没去做太多处理,读者自行完善
最后如果想看创建的数据库的效果话首先必须是模拟器,真机是没用的,然后下载一个操作数据库的SQLite,下载地址:http://download.csdn.net/detail/qq_33750826/9673234
然后安装打开
然后打开AndroidStudio或者Eclipse的File Explorer:
在里面找到data->data->找到自己的项目包名
0 0
- Android开发之五大存储方式之一数据库存储
- Android五大存储方式之数据库升级篇
- Android五大存储方式之File文件存储
- Android存储五大方式
- Android四大组件之一:contentprovider & 三大存储方式之一:SQLite数据库存储 应用实例
- Android中的五大数据存储方式之一——文件存储
- Android中的五大存储方式之二——SQLite数据库
- Android五大储存方式之文件存储
- Android五大存储方式之三——SharedPreferences
- Android五大存储方式之四——ContentProvider
- Android五大存储之数据库事物篇
- Android------五大存储方式详解
- android的五大存储方式
- Android 五大存储方式详解
- Android五大数据存储方式
- android五大基本存储方式
- Android------五大存储方式详解
- Android的五大存储方式
- 使用ImageIO压缩图片
- C++编译器与C的几点差异
- VHDL语言编写DS18B20温度传感器程序详解
- 透明兼容调试
- Unity如何限制3D物体的旋转角度
- Android开发之五大存储方式之一数据库存储
- 如何在没有官方API的情况下写一个第三方客户端
- 算法复杂度的计算
- 设计模式(八)外观模式
- 第十周—个人所得税
- JavaScript进阶学习——DOM对象
- K3 数据库常用表
- Android 数据库中读取图片名称加载相应的资源
- android EditTextView 设置不可输入不可点击及获取焦点