【SQLite】Android Studio SQLite Database小例

2024-03-11 07:08

本文主要是介绍【SQLite】Android Studio SQLite Database小例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


android studio SQLite Database小例

Android中SQLite应用详解


SQLiteDatabase是一个可以进行增(Create)、查(Retrieve)、改(Update)、删(Delete)数据,即CRUD操作的类。
下面教程将向你展示如何使用SQLiteDatabase在Android中实现CRUD操作。

工具使用:
Android studio 1.1.0

TODO
在这个教程中,我们将创建一个app,允许对一个student表进行增查改删的数据操作。
很容易吗?是的,如果你知道怎样做的话 :)

android Studio SQLite Database Example

表结构
这个student表将用于存储学生的详细数据,为了简单,只创建3个域,如下图:

student表.jpg
student表.jpg

id是主键,允许自增

页面布局
创建两个页面布局,第一个页面展示所有学生名字,如下图:

学生列表.jpg
学生列表.jpg

第二个页面是学生的详细信息的页面,用户点击listview的每个item时,将会进入这个页面,如下图:

详细信息或增加数据页面
详细信息或增加数据页面

布局实现
1.新建一个SQLiteDemo的project;
2.实现第一个页面布局activity_main.xml

<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"   android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Add"android:id="@+id/btnAdd"android:layout_alignParentBottom="true"android:layout_alignParentLeft="true"/><ListViewandroid:id="@android:id/list"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/btnAdd"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="List All"android:id="@+id/btnGetAll"android:layout_alignParentBottom="true"android:layout_toRightOf="@+id/btnAdd"/>
</RelativeLayout>

你需要修改ListView的id为 android:id="@+id/listView" 如果你选择继承ListActivity在你的Activity类,否则将会出错;content必须有一个ListView,它的id的属性是‘android.R.id.list’

3.创建另一个activity,StudentDetail.java,其布局为第二个页面activity_student_detail.xml

<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" android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin"tools:context="cn.cfanr.sqlitedemo.StudentDetail"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Name"android:id="@+id/tvName"android:layout_alignParentTop="true"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_marginTop="30dp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Email"android:id="@+id/tvEmail"android:layout_below="@id/tvName"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_marginTop="30dp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Age"android:id="@+id/tvAge"android:layout_below="@id/tvEmail"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_marginTop="30dp" /><EditTextandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/etName"android:inputType="textPersonName"android:ems="10"android:layout_above="@id/tvEmail"android:layout_toRightOf="@id/tvName"android:layout_alignParentRight="true"android:layout_alignParentEnd="true" /><EditTextandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/etEmail"android:layout_toRightOf="@id/tvEmail"android:inputType="textEmailAddress"android:ems="10"android:layout_above="@id/tvAge"android:layout_alignParentRight="true"android:layout_alignParentEnd="true" /><EditTextandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/etAge"android:inputType="number"android:ems="10"android:layout_alignBottom="@id/tvAge"android:layout_alignLeft="@id/etEmail"android:layout_alignStart="@id/etEmail"android:layout_alignRight="@id/etEmail"android:layout_alignEnd="@id/etEmail"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/btnClose"android:text="Close"android:layout_alignParentBottom="true"android:layout_alignParentRight="true"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/btnSave"android:text="Save"android:layout_alignParentBottom="true"android:layout_toLeftOf="@id/btnClose"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/btnDelete"android:text="Delete"android:layout_alignParentBottom="true"android:layout_toLeftOf="@id/btnSave"/>
</RelativeLayout>

4.当用户点击ListView的item时展示学生的详细信息的activity,所以我们需要一个特殊的id来检索学生的详细信息,并且这个id必须来自ListView,可以通过两个方法实现:

  • 最简单的方法,可以放id和name进listview的item中,展示给用户(不好的UI设计),当用户点击选中item时,将检索的记录传递到StudentDetail.java的activity。
  • 创建一个layout作为listview的item,通过item中包含学生的id(不过设置成隐藏)来检索学生的详细信息;

采用第二种方法,创建一个新的layout,view_student_entry.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/student_Id"android:visibility="gone"/><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:paddingLeft="6dip"android:paddingTop="6dip"android:textSize="22sp"android:textStyle="bold"/>
</LinearLayout>

编码
1.创建Student类

package cn.cfanr.sqlitedemo;/*** Created by ifanr on 2015/3/29.*/
public class Student {//表名public static final String TABLE="Student";//表的各域名public static final String KEY_ID="id";public static final String KEY_name="name";public static final String KEY_email="email";public static final String KEY_age="age";//属性public int student_ID;public String name;public String email;public int age;
}

2.为了创建表,需要使用到SQLiteDatabase类(实现CRUD操作)和SQLiteOpenHelper(用于数据库的创建和版本管理),下面先创建一个DBHelper类

package cn.cfanr.sqlitedemo;import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;/*** Created by ifanr on 2015/3/29.*/
public class DBHelper extends SQLiteOpenHelper {//数据库版本号private static final int DATABASE_VERSION=4;//数据库名称private static final String DATABASE_NAME="crud.db";public DBHelper(Context context){super(context,DATABASE_NAME,null,DATABASE_VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {//创建数据表String CREATE_TABLE_STUDENT="CREATE TABLE "+ Student.TABLE+"("+Student.KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT ,"+Student.KEY_name+" TEXT, "+Student.KEY_age+" INTEGER, "+Student.KEY_email+" TEXT)";db.execSQL(CREATE_TABLE_STUDENT);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//如果旧表存在,删除,所以数据将会消失db.execSQL("DROP TABLE IF EXISTS "+ Student.TABLE);//再次创建表onCreate(db);}
}

3.新建StudentRepo类,编写CRUD函数。

package cn.cfanr.sqlitedemo;import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;import java.util.ArrayList;
import java.util.HashMap;/*** Created by ifanr on 2015/3/29.*/
public class StudentRepo {private DBHelper dbHelper;public StudentRepo(Context context){dbHelper=new DBHelper(context);}public int insert(Student student){//打开连接,写入数据SQLiteDatabase db=dbHelper.getWritableDatabase();ContentValues values=new ContentValues();values.put(Student.KEY_age,student.age);values.put(Student.KEY_email,student.email);values.put(Student.KEY_name,student.name);//long student_Id=db.insert(Student.TABLE,null,values);db.close();return (int)student_Id;}public void delete(int student_Id){SQLiteDatabase db=dbHelper.getWritableDatabase();db.delete(Student.TABLE,Student.KEY_ID+"=?", new String[]{String.valueOf(student_Id)});db.close();}public void update(Student student){SQLiteDatabase db=dbHelper.getWritableDatabase();ContentValues values=new ContentValues();values.put(Student.KEY_age,student.age);values.put(Student.KEY_email,student.email);values.put(Student.KEY_name,student.name);db.update(Student.TABLE,values,Student.KEY_ID+"=?",new String[] { String.valueOf(student.student_ID) });db.close();}public ArrayList<HashMap<String, String>> getStudentList(){SQLiteDatabase db=dbHelper.getReadableDatabase();String selectQuery="SELECT "+Student.KEY_ID+","+Student.KEY_name+","+Student.KEY_email+","+Student.KEY_age+" FROM "+Student.TABLE;ArrayList<HashMap<String,String>> studentList=new ArrayList<HashMap<String, String>>();Cursor cursor=db.rawQuery(selectQuery,null);if(cursor.moveToFirst()){do{HashMap<String,String> student=new HashMap<String,String>();student.put("id",cursor.getString(cursor.getColumnIndex(Student.KEY_ID)));student.put("name",cursor.getString(cursor.getColumnIndex(Student.KEY_name)));studentList.add(student);}while(cursor.moveToNext());}cursor.close();db.close();return studentList;}public Student getStudentById(int Id){SQLiteDatabase db=dbHelper.getReadableDatabase();String selectQuery="SELECT "+Student.KEY_ID + "," +Student.KEY_name + "," +Student.KEY_email + "," +Student.KEY_age +" FROM " + Student.TABLE+ " WHERE " +Student.KEY_ID + "=?";int iCount=0;Student student=new Student();Cursor cursor=db.rawQuery(selectQuery,new String[]{String.valueOf(Id)});if(cursor.moveToFirst()){do{student.student_ID =cursor.getInt(cursor.getColumnIndex(Student.KEY_ID));student.name =cursor.getString(cursor.getColumnIndex(Student.KEY_name));student.email  =cursor.getString(cursor.getColumnIndex(Student.KEY_email));student.age =cursor.getInt(cursor.getColumnIndex(Student.KEY_age));}while(cursor.moveToNext());}cursor.close();db.close();return student;}
}

4.用户点击item,进入的详细页面StudentDetail

package cn.cfanr.sqlitedemo;import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;public class StudentDetail extends ActionBarActivity implements View.OnClickListener {private Button btnSave,btnDelete;private Button btnClose;private EditText etName;private EditText etEmail;private EditText etAge;private int _student_id=0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_student_detail);btnSave = (Button) findViewById(R.id.btnSave);btnDelete = (Button) findViewById(R.id.btnDelete);btnClose = (Button) findViewById(R.id.btnClose);etName = (EditText) findViewById(R.id.etName);etEmail = (EditText) findViewById(R.id.etEmail);etAge = (EditText) findViewById(R.id.etAge);btnSave.setOnClickListener(this);btnDelete.setOnClickListener(this);btnClose.setOnClickListener(this);_student_id =0;Intent intent = getIntent();_student_id =intent.getIntExtra("student_Id", 0);StudentRepo repo = new StudentRepo(this);Student student = new Student();student = repo.getStudentById(_student_id);etAge.setText(String.valueOf(student.age));etName.setText(student.name);etEmail.setText(student.email);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_student_detail, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}@Overridepublic void onClick(View v) {if(v==findViewById(R.id.btnSave)){StudentRepo repo=new StudentRepo(this);Student student=new Student();student.age=Integer.parseInt(etAge.getText().toString());student.email=etEmail.getText().toString();student.name=etName.getText().toString();student.student_ID=_student_id;if(_student_id==0){_student_id=repo.insert(student);Toast.makeText(this,"New Student Insert",Toast.LENGTH_SHORT).show();}else{repo.update(student);Toast.makeText(this,"Student Record updated",Toast.LENGTH_SHORT).show();}}else if (v== findViewById(R.id.btnDelete)){StudentRepo repo = new StudentRepo(this);repo.delete(_student_id);Toast.makeText(this, "Student Record Deleted", Toast.LENGTH_SHORT);finish();}else if (v== findViewById(R.id.btnClose)){finish();}}
}

5.在MainActivity实现获取学生列表和跳转到StudentDetail页面

package cn.cfanr.sqlitedemo;import android.app.ListActivity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;import java.util.ArrayList;
import java.util.HashMap;public class MainActivity extends ListActivity implements android.view.View.OnClickListener {private Button btnAdd,btnGetAll;private TextView student_Id;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnAdd = (Button) findViewById(R.id.btnAdd);btnAdd.setOnClickListener(this);btnGetAll = (Button) findViewById(R.id.btnGetAll);btnGetAll.setOnClickListener(this);}@Overridepublic void onClick(View v) {if (v== findViewById(R.id.btnAdd)){Intent intent = new Intent(this,StudentDetail.class);intent.putExtra("student_Id",0);startActivity(intent);}else {StudentRepo repo = new StudentRepo(this);ArrayList<HashMap<String, String>> studentList =  repo.getStudentList();if(studentList.size()!=0) {ListView lv = getListView();lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {student_Id = (TextView) view.findViewById(R.id.student_Id);String studentId = student_Id.getText().toString();Intent objIndent = new Intent(getApplicationContext(),StudentDetail.class);objIndent.putExtra("student_Id", Integer.parseInt( studentId));startActivity(objIndent);}});ListAdapter adapter = new SimpleAdapter( MainActivity.this,studentList, R.layout.view_student_entry, new String[] { "id","name"}, new int[] {R.id.student_Id, R.id.student_name});setListAdapter(adapter);}else{Toast.makeText(this, "No student!", Toast.LENGTH_SHORT).show();}}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}
}

6.运行结果如下:

学生列表(添加数据后,原来为空)
学生列表(添加数据后,原来为空)
学生详细信息页面.png
学生详细信息页面.png

参考http://instinctcoder.com/android-studio-sqlite-database-example/

另外,SQLite的详细资料,Android中SQLite应用详解



文/cfanr(简书作者)
原文链接:http://www.jianshu.com/p/ee08f75b407c
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。


这篇关于【SQLite】Android Studio SQLite Database小例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/797036

相关文章

Mysql数据库聚簇索引与非聚簇索引举例详解

《Mysql数据库聚簇索引与非聚簇索引举例详解》在MySQL中聚簇索引和非聚簇索引是两种常见的索引结构,它们的主要区别在于数据的存储方式和索引的组织方式,:本文主要介绍Mysql数据库聚簇索引与非... 目录前言一、核心概念与本质区别二、聚簇索引(Clustered Index)1. 实现原理(以 Inno

sqlserver、mysql、oracle、pgsql、sqlite五大关系数据库的对象名称和转义字符

《sqlserver、mysql、oracle、pgsql、sqlite五大关系数据库的对象名称和转义字符》:本文主要介绍sqlserver、mysql、oracle、pgsql、sqlite五大... 目录一、转义符1.1 oracle1.2 sqlserver1.3 PostgreSQL1.4 SQLi

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

深入理解Mysql OnlineDDL的算法

《深入理解MysqlOnlineDDL的算法》本文主要介绍了讲解MysqlOnlineDDL的算法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小... 目录一、Online DDL 是什么?二、Online DDL 的三种主要算法2.1COPY(复制法)

mysql8.0.43使用InnoDB Cluster配置主从复制

《mysql8.0.43使用InnoDBCluster配置主从复制》本文主要介绍了mysql8.0.43使用InnoDBCluster配置主从复制,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录1、配置Hosts解析(所有服务器都要执行)2、安装mysql shell(所有服务器都要执行)3、

k8s中实现mysql主备过程详解

《k8s中实现mysql主备过程详解》文章讲解了在K8s中使用StatefulSet部署MySQL主备架构,包含NFS安装、storageClass配置、MySQL部署及同步检查步骤,确保主备数据一致... 目录一、k8s中实现mysql主备1.1 环境信息1.2 部署nfs-provisioner1.2.

MySQL中VARCHAR和TEXT的区别小结

《MySQL中VARCHAR和TEXT的区别小结》MySQL中VARCHAR和TEXT用于存储字符串,VARCHAR可变长度存储在行内,适合短文本;TEXT存储在溢出页,适合大文本,下面就来具体的了解... 目录一、VARCHAR 和 TEXT 基本介绍1. VARCHAR2. TEXT二、VARCHAR

MySQL中C接口的实现

《MySQL中C接口的实现》本节内容介绍使用C/C++访问数据库,包括对数据库的增删查改操作,主要是学习一些接口的调用,具有一定的参考价值,感兴趣的可以了解一下... 目录准备mysql库使用mysql库编译文件官方API文档对象的创建和关闭链接数据库下达sql指令select语句前言:本节内容介绍使用C/

mybatis直接执行完整sql及踩坑解决

《mybatis直接执行完整sql及踩坑解决》MyBatis可通过select标签执行动态SQL,DQL用ListLinkedHashMap接收结果,DML用int处理,注意防御SQL注入,优先使用#... 目录myBATiFBNZQs直接执行完整sql及踩坑select语句采用count、insert、u

MySQL之搜索引擎使用解读

《MySQL之搜索引擎使用解读》MySQL存储引擎是数据存储和管理的核心组件,不同引擎(如InnoDB、MyISAM)采用不同机制,InnoDB支持事务与行锁,适合高并发场景;MyISAM不支持事务,... 目录mysql的存储引擎是什么MySQL存储引擎的功能MySQL的存储引擎的分类查看存储引擎1.命令