android studio SQLite Database小例
Android中SQLite应用详解
sqliteDatabase是一个可以进行增(Create)、查(RetrIEve)、改(Update)、删(Delete)数据,即CRUD *** 作的类。
下面教程将向你展示如何使用sqliteDatabase在AndroID中实现CRUD *** 作。
工具使用:
AndroID studio 1.1.0
Todo
在这个教程中,我们将创建一个app,允许对一个student表进行增查改删的数据 *** 作。
很容易吗?是的,如果你知道怎样做的话 :)
表结构
这个student表将用于存储学生的详细数据,为了简单,只创建3个域,如下图:
student表.jpg
ID是主键,允许自增
页面布局
创建两个页面布局,第一个页面展示所有学生名字,如下图:
学生列表.jpg
第二个页面是学生的详细信息的页面,用户点击ListvIEw的每个item时,将会进入这个页面,如下图:
详细信息或增加数据页面
布局实现
1.新建一个sqliteDemo的project;
2.实现第一个页面布局activity_main.xml
@H_301_72@<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"> @H_301_72@<button androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="Add" androID:ID="@+ID/btnAdd" androID:layout_alignParentBottom="true" androID:layout_alignParentleft="true" /> @H_301_72@<ListVIEw androID:ID="@androID:ID/List" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_above="@+ID/btnAdd" /> @H_301_72@<button androID: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"/>@H_301_72@</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"> <TextVIEw androID: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" /> <TextVIEw androID: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" /> <TextVIEw androID: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" /> <EditText androID: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" /> <EditText androID: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" /> <EditText androID: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" /> <button androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:ID="@+ID/btnClose" androID:text="Close" androID:layout_alignParentBottom="true" androID:layout_alignParentRight="true" /> <button androID: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"/> <button androID: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。@H_718_419@ 创建一个layout作为ListvIEw的item,通过item中包含学生的ID(不过设置成隐藏)来检索学生的详细信息;@H_718_419@采用第二种方法,创建一个新的layout,vIEw_student_entry.xml,代码如下:
<?xml version="1.0" enCoding="utf-8"?>@H_301_72@<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:orIEntation="vertical" androID:layout_wIDth="match_parent" androID:layout_height="match_parent"> @H_301_72@<TextVIEw androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:ID="@+ID/student_ID" androID:visibility="gone"/> @H_301_72@<TextVIEw androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:paddingleft="6dip" androID:paddingtop="6dip" androID:textSize="22sp" androID:textStyle="bold"/>@H_301_72@</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); } @OverrIDe public 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); } @OverrIDe public 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,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.name); db.update(Student.table,values,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; @OverrIDe protected 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); } @OverrIDe public 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; } @OverrIDe public 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 SimplifiableIfStatement if (ID == R.ID.action_settings) { return true; } return super.onoptionsItemSelected(item); } @OverrIDe public 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; @OverrIDe protected 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); } @OverrIDe public 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() { @OverrIDe public 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(); } } } @OverrIDe public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main,so long // as you specify a parent activity in AndroIDManifest.xml. int ID = item.getItemID(); //noinspection SimplifiableIfStatement if (ID == R.ID.action_settings) { return true; } return super.onoptionsItemSelected(item); }}
6.运行结果如下:
学生列表(添加数据后,原来为空)
学生详细信息页面.png
参考http://instinctcoder.com/android-studio-sqlite-database-example/
另外,sqlite的详细资料,Android中SQLite应用详解
文/cfanr(简书作者) 原文链接:http://www.jianshu.com/p/ee08f75b407c 著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。 总结
以上是内存溢出为你收集整理的【SQLite】Android Studio SQLite Database小例全部内容,希望文章能够帮你解决【SQLite】Android Studio SQLite Database小例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)