【实验名称】实验六、contentprovider实验+SQLite数据库的实现
【实验目的】
1、掌握如何在Android 开发中使用 SQLite 数据库
2、熟悉设计数据库表结构的方法与步骤
3、理解contentprovider的使用方法及流程,理解ContentProvider、Resolver、Uri、Urimatcher等的原理。
【实验内容】
1、实现contentprovider和contentresolver通过uri的调用;
2、实现contentprovider对数据库sqlite的功能:增、删、改、查;
3、数据库的表结构自行设计;
【实验要求】
1、配置SQLite 数据库的运行环境
2、熟悉contentprovider对数据库sqlite增、删、改、查的具体操作和流程
3、充分理解SQLite数据库的使用原理和方式
(请完成如下部分)
访问通讯录
数据库的增删改查
代码
MainActivity.java
package com.example.test05_contentprovider;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void toOne(View view){
Intent intent = new Intent(MainActivity.this, ContentActivity.class);
startActivity(intent);
}
public void toTwo(View view){
Intent intent = new Intent(MainActivity.this, SQLActivity.class);
startActivity(intent);
}
}
ContentActivity.java
package com.example.test05_contentprovider;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
import androidx.annotation.Nullable;
public class ContentActivity extends Activity {
//希望获得通讯录中的姓名
private String columns = ContactsContract.Contacts.DISPLAY_NAME;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contentlayout);
TextView textView = (TextView) findViewById(R.id.callName);
textView.setText(getQueryData());
}
private CharSequence getQueryData(){
//用于保存获取的联系人
StringBuilder stringBuilder = new StringBuilder();
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
//获得姓名记录的索引值
int displayNameIndex = cursor.getColumnIndex(columns);
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
String displayName = cursor.getString(displayNameIndex);
stringBuilder.append(displayName+"\n");
System.out.println(stringBuilder);
}
cursor.close();
return stringBuilder.toString();
}
}
PersonDBOpenHelper.java
package com.example.test05_contentprovider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class PersonDBOpenHelper extends SQLiteOpenHelper {
//构造方法
public PersonDBOpenHelper(Context context) {
super(context,"person.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table info(_id integer primary key autoincrement,name varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
PersonProvider.java
package com.example.test05_contentprovider;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class PersonProvider extends ContentProvider {
//定义一个URI路径的匹配器 匹配失败返回-1
private static UriMatcher mUriMatcher = new UriMatcher(-1);
//匹配成功
private static final int SUCCESS = 1;
//数据库操作类的对象
private PersonDBOpenHelper helper;
//添加路径匹配器的规则
static {
mUriMatcher.addURI("cn.itcast.contentobserverdb","info",SUCCESS);
}
@Override
public boolean onCreate() {
helper = new PersonDBOpenHelper(getContext());
return false;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
int code = mUriMatcher.match(uri);
if(code == SUCCESS){
SQLiteDatabase db = helper.getReadableDatabase();
return db.query("info",strings,s,strings1,null,null,s1);
}else{
try {
throw new IllegalAccessException("路径不正确,不会给你提供数据");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
int code = mUriMatcher.match(uri);
if(code == SUCCESS){
SQLiteDatabase db = helper.getReadableDatabase();
long rowId = db.insert("info",null,values);
if(rowId>0){
Uri insertedUri = ContentUris.withAppendedId(uri, rowId);
//提示数据库的内容变化了
getContext().getContentResolver().notifyChange(insertedUri,null);
return insertedUri;
}
db.close();
return uri;
}else{
try {
throw new IllegalAccessException("路径不正确,不会插入数据");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
int code = mUriMatcher.match(uri);
if(code == SUCCESS){
SQLiteDatabase db = helper.getReadableDatabase();
int count = db.delete("info",s,strings);
if(count>0){
getContext().getContentResolver().notifyChange(uri,null);
}
db.close();
return count;
}else{
try {
throw new IllegalAccessException("路径不正确,不会删除数据");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return code;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
int code = mUriMatcher.match(uri);
if(code == SUCCESS){
SQLiteDatabase db = helper.getReadableDatabase();
int count = db.update("info",contentValues,s,strings);
if(count>0){
getContext().getContentResolver().notifyChange(uri,null);
}
db.close();
return count;
}else{
try {
throw new IllegalAccessException("路径不正确,不能更新数据");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}return 0;
}
}
SQLActivity.java
package com.example.test05_contentprovider;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class SQLActivity extends Activity {
private ContentResolver resolver;
private Uri uri;
private ContentValues values;
private Button btnInsert;
private Button btnUpdate;
private Button btnDelete;
private Button btnSelect;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllayout);
createDB();
createDB();
}
private void createDB(){
//创建数据库
PersonDBOpenHelper helper = new PersonDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
for (int i = 0; i< 3;i++){
ContentValues values = new ContentValues();
values.put("name","peach"+i);
db.insert("info",null,values);
}
System.out.println("创建成功");
db.close();
}
public void btnAdd(View view){
System.out.println("????????????????????");
resolver = getContentResolver();
uri = Uri.parse("content://cn.itcast.contentobserverdb/info");
values = new ContentValues();
Random random = new Random();
values.put("name","add_itcast"+random.nextInt(10));
Uri newUri = resolver.insert(uri,values);
Toast.makeText(this,"成功添加",Toast.LENGTH_SHORT).show();
Log.i("数据库","add");
}
public void btnQuery(View view){
System.out.println("????????????????????");
resolver = getContentResolver();
uri = Uri.parse("content://cn.itcast.contentobserverdb/info");
values = new ContentValues();
List<Map<String,String>> data = new ArrayList<Map<String ,String >>();
Cursor cursor = resolver.query(uri, new String[]{
"_id","name"},null,null,null);
while(cursor.moveToNext()){
Map<String,String> map = new HashMap<String,String>();
map.put("_id",cursor.getString(0));
map.put("name",cursor.getString(1));
data.add(map);
}
cursor.close();
Log.i("ahadhsahf","safk"+data.toString());
}
public void btnUpdate(View view){
System.out.println("--------更新!!!");
resolver = getContentResolver();
uri = Uri.parse("content://cn.itcast.contentobserverdb/info");
values = new ContentValues();
values.put("name","hhhhhhh");
int updateCount = resolver.update(uri,values,"name=?",new String[]{
"peach0"});
Toast.makeText(this,"成功更新了"+updateCount+"行",Toast.LENGTH_SHORT).show();
}
public void btnDelete(View view){
System.out.println("????????????????????");
resolver = getContentResolver();
uri = Uri.parse("content://cn.itcast.contentobserverdb/info");
values = new ContentValues();
int deleteCount = resolver.delete(uri,"name=?",new String[]{
"peach0"});
resolver.delete(uri,"name=?",new String[]{
"peach1"});
resolver.delete(uri,"name=?",new String[]{
"hhhhhhh"});
Toast.makeText(this,"成功删除了"+deleteCount+"行",Toast.LENGTH_SHORT).show();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/toOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="访问通讯录"
android:onClick="toOne"
/>
<Button
android:id="@+id/toTwo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="数据库"
android:onClick="toTwo"
/>
LinearLayout>
contentlayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ContentActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="读取到的联系人姓名:"
android:textSize="30dp"/>
<TextView
android:id="@+id/callName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
/>
LinearLayout>
sqllayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SQLActivity">
<Button
android:id="@+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnAdd"
android:text="增加"/>
<Button
android:id="@+id/update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnUpdate"
android:text="更新"/>
<Button
android:id="@+id/delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnDelete"
android:text="删除"/>
<Button
android:id="@+id/query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnQuery"
android:text="查询"/>
LinearLayout>
【实验分析或心得】
掌握如何在Android 开发中使用 SQLite 数据库,熟悉设计数据库表结构的方法与步骤并且理解contentprovider的使用方法及流程,理解ContentProvider、Resolver、Uri、Urimatcher等的原理。收获颇多。