【實驗名稱】實驗六、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
<?xml version="1.0" encoding="utf-8"?>
<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
<?xml version="1.0" encoding="utf-8"?>
<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
<?xml version="1.0" encoding="utf-8"?>
<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等的原理,識訓頗多,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/245327.html
標籤:其他
