【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

相关文章

SQL BETWEEN 语句的基本用法详解

《SQLBETWEEN语句的基本用法详解》SQLBETWEEN语句是一个用于在SQL查询中指定查询条件的重要工具,它允许用户指定一个范围,用于筛选符合特定条件的记录,本文将详细介绍BETWEEN语... 目录概述BETWEEN 语句的基本用法BETWEEN 语句的示例示例 1:查询年龄在 20 到 30 岁

MySQL DQL从入门到精通

《MySQLDQL从入门到精通》通过DQL,我们可以从数据库中检索出所需的数据,进行各种复杂的数据分析和处理,本文将深入探讨MySQLDQL的各个方面,帮助你全面掌握这一重要技能,感兴趣的朋友跟随小... 目录一、DQL 基础:SELECT 语句入门二、数据过滤:WHERE 子句的使用三、结果排序:ORDE

MySQL MCP 服务器安装配置最佳实践

《MySQLMCP服务器安装配置最佳实践》本文介绍MySQLMCP服务器的安装配置方法,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下... 目录mysql MCP 服务器安装配置指南简介功能特点安装方法数据库配置使用MCP Inspector进行调试开发指

mysql中insert into的基本用法和一些示例

《mysql中insertinto的基本用法和一些示例》INSERTINTO用于向MySQL表插入新行,支持单行/多行及部分列插入,下面给大家介绍mysql中insertinto的基本用法和一些示例... 目录基本语法插入单行数据插入多行数据插入部分列的数据插入默认值注意事项在mysql中,INSERT I

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

SQL Server数据库死锁处理超详细攻略

《SQLServer数据库死锁处理超详细攻略》SQLServer作为主流数据库管理系统,在高并发场景下可能面临死锁问题,影响系统性能和稳定性,这篇文章主要给大家介绍了关于SQLServer数据库死... 目录一、引言二、查询 Sqlserver 中造成死锁的 SPID三、用内置函数查询执行信息1. sp_w

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

SQL中JOIN操作的条件使用总结与实践

《SQL中JOIN操作的条件使用总结与实践》在SQL查询中,JOIN操作是多表关联的核心工具,本文将从原理,场景和最佳实践三个方面总结JOIN条件的使用规则,希望可以帮助开发者精准控制查询逻辑... 目录一、ON与WHERE的本质区别二、场景化条件使用规则三、最佳实践建议1.优先使用ON条件2.WHERE用

MySQL存储过程之循环遍历查询的结果集详解

《MySQL存储过程之循环遍历查询的结果集详解》:本文主要介绍MySQL存储过程之循环遍历查询的结果集,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言1. 表结构2. 存储过程3. 关于存储过程的SQL补充总结前言近来碰到这样一个问题:在生产上导入的数据发现