Android 之路42

阅读: 评论:0

Android 之路42

Android 之路42

导读

1.SQLite简介
2.数据库简介
3.数据库语句操作
4.Android中操作SQL语句
5.使用相关API操作数据库
6.使用面向对象思想封装操作

SQLite简介

数据库简介

关系型数据库的分类 MySQL , Oracle, SQL Sever

数据库语句操作

对工具 SQLiteExpert的认识

创建数据库如下

在数据库中创建新的表格

也可以在Query中直接用DDL语句编写,然后点excute

创建表格实例

Structure 表示表格的结构

这里是DDL语言编写的表格
primary key 表示主键,即唯一且不为空的
autoincrement 表示可以自动增长
varchar 表示字符串

Data表示表格的真实样子

Schema可以显示表格属性的一些设置

⚠️所有操作都要先清空前边的操作

添加操作

create table info_tb(_id integer primary key autoincrement ,name varchar(30) not null,age integer notnull,gender varchar(2) not null
)insert into info_tb (name,age,gender) values ('Emilia ',30,'female')
insert into info_tb values (null,'Neymar',26,'male')--这里有三种添加方式
--第一句包含所有非空的属性
--第二句包含所有属性,id那可以写表中没有的id,也可以写null
--第三种是在Data里直接添加

删除操作

delete from info_tb
delete from info_tb where name='conan'
--语句1 将表格内容全部删除
--语句2 删除特定内容
--删除是针对行即记录而言的

修改操作

update info_tb setgender='felmale'age=25update info_tb setgender='male',age='30'where name='Emilia'
--语句1对所有行进行操作
--语句2对指定行进行操作 注意age前边的逗号容易忘记

查询操作

select * from info_tbselect name from info_tbselect * from info_tb where gender='male'--语句1会将整个表打印出来
--语句2会查询属性为name的那一列
--语句3会将性别为男的行打印出来

聚合函数的使用

聚合函数是用于统计数据的函数


count(列名) 用来统计该列有多少数据


group by 表示按照什么分组


分组计数后显示什么信息


having表示附加条件


按升序和降序排列

手机数据库文件的导入

仿真机可以用拖拽实现导入
但真机与仿真机都可以用以下方法,要先打开真机或仿真机,

选择右上方小手机图案,选择要导入的文件即可导入文件

⚠️外部存储是存在了上图的sdcard文件夹下,而内部存储则在data文件夹的相应程序文件夹下

Android中操作SQL语句

配置文件 AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""package="com.hala.view01"><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><application
        android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

主页面布局文件 l文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="10dp"><EditText
        android:id="@+id/name"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="姓名:"/><EditText
        android:id="@+id/age"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="年龄:"android:numeric="integer"/><RadioGroup
        android:id="@+id/gender"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
            android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="性别"android:layout_marginLeft="5dp"/><RadioButton
            android:id="@+id/male"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="男"android:layout_marginLeft="15dp"android:checked="true"/><RadioButton
            android:id="@+id/female"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="女"android:layout_marginLeft="15dp"/></RadioGroup><EditText
        android:id="@+id/id"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:id="@+id/insert"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="添加"android:onClick="operate"/><Button
            android:id="@+id/select"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="查询"android:onClick="operate"/><Button
            android:id="@+id/delete"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="删除"android:onClick="operate"/><Button
            android:id="@+id/update"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="修改"android:onClick="operate"/></LinearLayout><ListView
        android:id="@+id/lv"android:layout_width="match_parent"android:layout_height="match_parent"></ListView>
</LinearLayout>

ListView条目布局文件 l

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""android:orientation="horizontal" android:layout_width="match_parent"android:layout_height="match_parent"><TextView
        android:id="@+id/id_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1" /><TextView
        android:id="@+id/name_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"/><TextView
        android:id="@+id/age_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1" /><TextView
        android:id="@+id/gender_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1" /></LinearLayout>

java文件 MainActivity.java

package com.hala.view01;import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {private EditText name,age,id;private RadioGroup gender;private RadioButton male;private String genderStr="男";private SQLiteDatabase db;private ListView lv;protected void onCreate(Bundle savedInstanceState) {Create(savedInstanceState);setContentView(R.layout.activity_main);name=(EditText)findViewById(R.id.name);age=(EditText)findViewById(R.id.age);id=(EditText)findViewById(R.id.id);lv=(ListView)findViewById(R.id.lv);male=(RadioButton)findViewById(R.id.male);gender=(RadioGroup)findViewById(der);gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {if(checkedId==R.id.male){genderStr="男";}else{genderStr="女";}}});//第一个参数:上下文环境//第二个参数:如果写一个数据库名称,那这个数据库在私有目录中,即该app项目包下//          如果带有sd卡路径,那么数据库在指定路径下,如下path// String path= ExternalStorageDirectory()+"/Emilia";//第三个参数:游标工场//第四个参数:版本号SQLiteOpenHelper helper=new SQLiteOpenHelper(this,"Emilia",null,1) {/*** 创建数据库* @param db*/@Overridepublic void onCreate(SQLiteDatabase db) {Toast.makeText(MainActivity.this, "数据库创建", Toast.LENGTH_SHORT).show();//创建表,如果数据库不存在,会调用onCreate创建数据库String sql="create table test_db(_id integer primary key autoincrement,"+"name varchar(20),"+"age integer(3),"+"gender varchar)";db.execSQL(sql);}/*** 数据库升级* @param db* @param oldVersion* @param newVersion*/@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {Toast.makeText(MainActivity.this, "数据库升级", Toast.LENGTH_SHORT).show();}};//用于获取数据库对象//1.数据库存在,则直接打开数据库//2.数据库不存在,则调用数据库创建方法,然后打开数据库//3.数据库存在,但版本号升高了,则调用数据库升级方法db = ReadableDatabase();}public void operate(View v){String idStr&#Text().toString();String nameStr&#Text().toString();String ageStr&#Text().toString();switch (v.getId()){//添加数据操作case R.id.insert ://第一种写法 注意这里的写法很奇特String sql1="insert into test_db (name,age,gender) values ('"+nameStr+"',"+ageStr+",'"+genderStr+"')";db.execSQL(sql1);//第二种写法// String sql1="insert into test_db (name,age,gender) values (?,?,?)"//db.execSQL(sql1,new String[]{nameStr,ageStr,genderStr});Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();break;//查询数据操作case R.id.select ://第一个参数:sql语句//第二个参数:可以为null,也可以是一个数组//当sql2="select * from test_db where _id=?,?,?,?";时,第二个参数为数组 new String[]{1,2,3,4}String sql2="select * from test_db ";if(!idStr.equals("")){sql2+="where _id="+idStr;}Cursor c=db.rawQuery(sql2,null);//第一个参数:上下文//第二个参数:ListView的每一个条目的布局文件//第三个参数:上边的Cursor对象 数据源//第四个参数:数据库表的每一列表头,即属性//第五个参数:这些数据要分别填充在参数2的哪个控件上//第六个参数:通知页面根据数据库的更新而更新//注意:SimpleCursorAdapter要求表格中要有属性_id,所以在定义id是要加上下划线SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.item,c,new String[]{"_id","name","age","gender"},new int[]{R.id.id_item,R.id.name_item,R.id.age_item,der_item},CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);lv.setAdapter(adapter);break;//删除数据操作case R.id.delete :String sql3="delete from test_db where _id=?";db.execSQL(sql3,new String[]{idStr});Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();break;//修改数据操作case R.id.update :String sql4="update test_db set name=?,age=?,gender=? where _id=?";db.execSQL(sql4,new String[]{nameStr,ageStr,genderStr,idStr});Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();break;}//将界面清空初始化操作name.setText("");age.setText("");id.setText("");male.setChecked(true);}}

显示结果

使用相关API操作数据库

其他文件相同

java文件

package com.hala.view01;t.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {private EditText name,age,id;private RadioGroup gender;private RadioButton male;private String genderStr="男";private SQLiteDatabase db;private ListView lv;protected void onCreate(Bundle savedInstanceState) {Create(savedInstanceState);setContentView(R.layout.activity_main);name=(EditText)findViewById(R.id.name);age=(EditText)findViewById(R.id.age);id=(EditText)findViewById(R.id.id);lv=(ListView)findViewById(R.id.lv);male=(RadioButton)findViewById(R.id.male);gender=(RadioGroup)findViewById(der);gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {if(checkedId==R.id.male){genderStr="男";}else{genderStr="女";}}});//第一个参数:上下文环境//第二个参数:如果写一个数据库名称,那这个数据库在私有目录中,即该app项目包下//          如果带有sd卡路径,那么数据库在指定路径下,如下path// String path= ExternalStorageDirectory()+"/Emilia";//第三个参数:游标工场//第四个参数:版本号SQLiteOpenHelper helper=new SQLiteOpenHelper(this,"Emilia",null,1) {/*** 创建数据库* @param db*/@Overridepublic void onCreate(SQLiteDatabase db) {Toast.makeText(MainActivity.this, "数据库创建", Toast.LENGTH_SHORT).show();//创建表,如果数据库不存在,会调用onCreate创建数据库String sql="create table test_db(_id integer primary key autoincrement,"+"name varchar(20),"+"age integer(3),"+"gender varchar)";db.execSQL(sql);}/*** 数据库升级* @param db* @param oldVersion* @param newVersion*/@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {Toast.makeText(MainActivity.this, "数据库升级", Toast.LENGTH_SHORT).show();}};//用于获取数据库对象//1.数据库存在,则直接打开数据库//2.数据库不存在,则调用数据库创建方法,然后打开数据库//3.数据库存在,但版本号升高了,则调用数据库升级方法db = ReadableDatabase();}public void operate(View v){String idStr&#Text().toString();String nameStr&#Text().toString();String ageStr&#Text().toString();switch (v.getId()){//添加数据操作case R.id.insert :ContentValues values=new ContentValues();values.put("name",nameStr);values.put("age",ageStr);values.put("gender",genderStr);//参数1:要给哪个库添加信息,库名//参数2: 当第三个参数为空时,第二个参数可以使其合法化//参数3:信息源,类似于键值对的设置,如上//insert的返回值是long类型的,表示添加信息的id号db.insert("test_db",null,values);Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();break;//查询数据操作case R.id.select ://参数1:要查询哪个库的信息,库名//参数2:要查询的列 new String[]{"name","age"} 查询所有用null//参数3:条件,即sql语句where后边的内容 "age=? and gender=?" 查询所有用null//参数4:针对于参数三给出值 {"30" and "female"} 查询所有用null//参数5:分组 没有分组用null//参数6:分组后,可以设置附加条件,如按年龄分组后设置年龄大于18岁的数据  没有条件用null//参数7:排序 没有排序用nullCursor c=db.query("test_db",null,"age=? and gender=?",new String[]{ageStr,genderStr},"age","age>25","age desc");//第一个参数:上下文//第二个参数:ListView的每一个条目的布局文件//第三个参数:上边的Cursor对象 数据源//第四个参数:数据库表的每一列表头,即属性//第五个参数:这些数据要分别填充在参数2的哪个控件上//第六个参数:通知页面根据数据库的更新而更新//注意:SimpleCursorAdapter要求表格中要有属性_id,所以在定义id是要加上下划线SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.item,c,new String[]{"_id","name","age","gender"},new int[]{R.id.id_item,R.id.name_item,R.id.age_item,der_item},CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);lv.setAdapter(adapter);break;//删除数据操作case R.id.delete ://delete返回值是int型 表示删除了多少行int count=db.delete("test_db","_id=?",new String[]{idStr});if(count>0) {Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();}break;//修改数据操作case R.id.update ://修改与添加如出一辙ContentValues values2=new ContentValues();values2.put("name",nameStr);values2.put("age",ageStr);values2.put("gender",genderStr);//update返回值是int型 表示修改了多少行int count2=db.update("test_db",values2,"_id=?",new String[]{idStr});if(count2>0) {Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();}break;}//将界面清空初始化操作name.setText("");age.setText("");id.setText("");male.setChecked(true);}}

显示结果

使用面向对象思想封装操作

⚠️对于数据库的操作类一般命名xxxxDao, 即data access object,这是一种习惯

配置文件 l

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""package="com.hala.view01"><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><application
        android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

主页面布局文件 l

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="10dp"><EditText
        android:id="@+id/name"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="姓名:"/><EditText
        android:id="@+id/age"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="年龄:"android:numeric="integer"/><RadioGroup
        android:id="@+id/gender"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
            android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="性别"android:layout_marginLeft="5dp"/><RadioButton
            android:id="@+id/male"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="男"android:layout_marginLeft="15dp"android:checked="true"/><RadioButton
            android:id="@+id/female"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="女"android:layout_marginLeft="15dp"/></RadioGroup><EditText
        android:id="@+id/id"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:id="@+id/insert"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="添加"android:onClick="operate"/><Button
            android:id="@+id/select"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="查询"android:onClick="operate"/><Button
            android:id="@+id/delete"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="删除"android:onClick="operate"/><Button
            android:id="@+id/update"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="修改"android:onClick="operate"/></LinearLayout><ListView
        android:id="@+id/lv"android:layout_width="match_parent"android:layout_height="match_parent"></ListView>
</LinearLayout>

ListView条目布局文件 l

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""android:orientation="horizontal" android:layout_width="match_parent"android:layout_height="match_parent"><TextView
        android:id="@+id/id_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1" /><TextView
        android:id="@+id/name_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"/><TextView
        android:id="@+id/age_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1" /><TextView
        android:id="@+id/gender_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1" /></LinearLayout>

Student类 Student.java

package com.hala.view01;/*** Created by air on 2018/2/25.*/public class Student {private int id;private String name;private int age;private String gender;//无参构造方法public Student(){}//带3參构造方法public Student(String name, int age, String gender) {this.name = name;this.age = der = gender;}//带4參构造方法public Student(int id, String name, int age, String gender) {this.id = id;this.name = name;this.age = der = gender;}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 int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {der = gender;}}

StuDao类 StuDao.java

package com.hala.view01;t.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;/*** Created by air on 2018/2/24.*/public class StuDao {private SQLiteDatabase db;public StuDao(final Context context){//第一个参数:上下文环境//第二个参数:如果写一个数据库名称,那这个数据库在私有目录中,即该app项目包下//          如果带有sd卡路径,那么数据库在指定路径下,如下path// String path= ExternalStorageDirectory()+"/Emilia";//第三个参数:游标工场//第四个参数:版本号SQLiteOpenHelper helper=new SQLiteOpenHelper(context,"Emilia",null,1) {/*** 创建数据库* @param db*/@Overridepublic void onCreate(SQLiteDatabase db) {//创建表,如果数据库不存在,会调用onCreate创建数据库String sql="create table test_db(_id integer primary key autoincrement,"+"name varchar(20),"+"age integer(3),"+"gender varchar)";db.execSQL(sql);}/*** 数据库升级* @param db* @param oldVersion* @param newVersion*/@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}};//用于获取数据库对象//1.数据库存在,则直接打开数据库//2.数据库不存在,则调用数据库创建方法,然后打开数据库//3.数据库存在,但版本号升高了,则调用数据库升级方法db = ReadableDatabase();}//添加public void addStu(Student stu){String sql="insert into test_db (name,age,gender) values(?,?,?)";db.execSQL(sql,new String[]{Name(),Age()+"",Gender()});}//查询public Cursor  strings){//查询所有(无参)String sql="select * from test_db";//含条件查询(name/age/id)(第一个参数指明条件 第二个参数指明条件值)if(strings.length!=0){sql+=" where "+strings[0]+"='"+strings[1]+"'";}Cursor c=db.rawQuery(sql,null);return c;}//删除public void  strings){String sql="delete from test_db where "+strings[0]+"='"+strings[1]+"'";db.execSQL(sql);}
//这里注意where前后要加空格//修改public void updateStu(Student stu){String sql="update test_db set name=?,age=?,gender=? where _id=?";db.execSQL(sql,new Object[]{Name(),Age(),Gender(),Id()});}
}

主页面java文件 MainActivity.java

package com.hala.view01;import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {private EditText name,age,id;private RadioGroup gender;private RadioButton male;private String genderStr="男";private SQLiteDatabase db;private ListView lv;private StuDao stuDao;protected void onCreate(Bundle savedInstanceState) {Create(savedInstanceState);setContentView(R.layout.activity_main);stuDao=new StuDao(this);name=(EditText)findViewById(R.id.name);age=(EditText)findViewById(R.id.age);id=(EditText)findViewById(R.id.id);lv=(ListView)findViewById(R.id.lv);male=(RadioButton)findViewById(R.id.male);gender=(RadioGroup)findViewById(der);gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {if(checkedId==R.id.male){genderStr="男";}else{genderStr="女";}}});}public void operate(View v){String idStr&#Text().toString();String nameStr&#Text().toString();String ageStr&#Text().toString();switch (v.getId()){//添加数据操作case R.id.insert :int ageInt;ageInt=strToInt(ageStr);Student student=new Student(nameStr,ageInt,genderStr);stuDao.addStu(student);Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();break;//查询数据操作case R.id.select :String[] params=getParams(nameStr,ageStr,idStr);Cursor c;if(params[0].equals("")){c&#Stu();}else{c&#Stu(params[0],params[1]);}//第一个参数:上下文//第二个参数:ListView的每一个条目的布局文件//第三个参数:上边的Cursor对象 数据源//第四个参数:数据库表的每一列表头,即属性//第五个参数:这些数据要分别填充在参数2的哪个控件上//第六个参数:通知页面根据数据库的更新而更新//注意:SimpleCursorAdapter要求表格中要有属性_id,所以在定义id是要加上下划线SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.item,c,new String[]{"_id","name","age","gender"},new int[]{R.id.id_item,R.id.name_item,R.id.age_item,der_item},CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);lv.setAdapter(adapter);break;//删除数据操作case R.id.delete :String[] params1=getParams(nameStr,ageStr,idStr);stuDao.deleteStu(params1[0],params1[1]);Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();break;//修改数据操作case R.id.update :int ageInt1,idInt;idInt=strToInt(idStr);ageInt1=strToInt(ageStr);Student student1=new Student(idInt,nameStr,ageInt1,genderStr);stuDao.updateStu(student1);Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();break;}//将界面清空初始化操作name.setText("");age.setText("");id.setText("");male.setChecked(true);}//公有代码,提出来变为公有方法//当涉及有多个返回值时,可以用数组做返回值public String[] getParams(String nameStr,String ageStr,String idStr){String[] params=new String[2];if(!nameStr.equals("")){params[0]="name";params[1]=nameStr;}else if(!ageStr.equals("")){params[0]="age";params[1]=ageStr;}else if(!idStr.equals("")){params[0]="_id";params[1]=idStr;}else{params[0]="";params[1]="";}return params;}//将字符串变为int型的操作public int strToInt(String str){int result=0;if(!str.equals("")){result=Integer.parseInt(str);}return result;}
}

本文发布于:2024-02-08 20:22:37,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170739528968884.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:之路   Android
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23