【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中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

MySQL常用字符串函数示例和场景介绍

《MySQL常用字符串函数示例和场景介绍》MySQL提供了丰富的字符串函数帮助我们高效地对字符串进行处理、转换和分析,本文我将全面且深入地介绍MySQL常用的字符串函数,并结合具体示例和场景,帮你熟练... 目录一、字符串函数概述1.1 字符串函数的作用1.2 字符串函数分类二、字符串长度与统计函数2.1

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

MySQL 内存使用率常用分析语句

《MySQL内存使用率常用分析语句》用户整理了MySQL内存占用过高的分析方法,涵盖操作系统层确认及数据库层bufferpool、内存模块差值、线程状态、performance_schema性能数据... 目录一、 OS层二、 DB层1. 全局情况2. 内存占js用详情最近连续遇到mysql内存占用过高导致

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

Mysql中设计数据表的过程解析

《Mysql中设计数据表的过程解析》数据库约束通过NOTNULL、UNIQUE、DEFAULT、主键和外键等规则保障数据完整性,自动校验数据,减少人工错误,提升数据一致性和业务逻辑严谨性,本文介绍My... 目录1.引言2.NOT NULL——制定某列不可以存储NULL值2.UNIQUE——保证某一列的每一

解密SQL查询语句执行的过程

《解密SQL查询语句执行的过程》文章讲解了SQL语句的执行流程,涵盖解析、优化、执行三个核心阶段,并介绍执行计划查看方法EXPLAIN,同时提出性能优化技巧如合理使用索引、避免SELECT*、JOIN... 目录1. SQL语句的基本结构2. SQL语句的执行过程3. SQL语句的执行计划4. 常见的性能优

SQL Server 中的 WITH (NOLOCK) 示例详解

《SQLServer中的WITH(NOLOCK)示例详解》SQLServer中的WITH(NOLOCK)是一种表提示,等同于READUNCOMMITTED隔离级别,允许查询在不获取共享锁的情... 目录SQL Server 中的 WITH (NOLOCK) 详解一、WITH (NOLOCK) 的本质二、工作

MySQL 强制使用特定索引的操作

《MySQL强制使用特定索引的操作》MySQL可通过FORCEINDEX、USEINDEX等语法强制查询使用特定索引,但优化器可能不采纳,需结合EXPLAIN分析执行计划,避免性能下降,注意版本差异... 目录1. 使用FORCE INDEX语法2. 使用USE INDEX语法3. 使用IGNORE IND

SQL Server安装时候没有中文选项的解决方法

《SQLServer安装时候没有中文选项的解决方法》用户安装SQLServer时界面全英文,无中文选项,通过修改安装设置中的国家或地区为中文中国,重启安装程序后界面恢复中文,解决了问题,对SQLSe... 你是不是在安装SQL Server时候发现安装界面和别人不同,并且无论如何都没有中文选项?这个问题也