代码部分:
part1:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="insert"
android:text="insert" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="delete"
android:text="delete" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="update"
android:text="update" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="query"
android:text="query" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
效果图:
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ContentResolver contentResolver;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentResolver = getContentResolver();
}
/**
* 演示ContentProvider的插入操作
* @param view
*/
public void insert(View view) {
/*
* content://bzxy.day13.demo/teacher
* */
// 定义Uri
Uri uri = Uri.parse("content://bzxy.day13.demo/teacher");
// 定义ContentValues
ContentValues contentValues = new ContentValues();
contentValues.put("name", "李老师");
Uri result = contentResolver.insert(uri, contentValues);
long id = ContentUris.parseId(result);
Toast.makeText(this,"插入完成,插入数据的id是:" + id, Toast.LENGTH_SHORT).show();
}
/**
* 演示ContentProvider的删除操作
* @param view
*/
public void delete(View view) {
Uri uri = Uri.parse("content://bzxy.day13.demo/teacher");
int row = contentResolver.delete(uri, "id=?", new String[]{"1"});
Toast.makeText(this, "删除的数据条数是:" + row, Toast.LENGTH_SHORT).show();
}
/**
* 演示ContentProvider的修改操作
* @param view
*/
public void update(View view) {
Uri uri = Uri.parse("content://bzxy.day13.demo/student");
ContentValues contentValues = new ContentValues();
contentValues.put("name", "王五");
int row = contentResolver.update(uri,contentValues,"id=?", new String[]{"3"});
Toast.makeText(this, "更新的数据条数是:" + row, Toast.LENGTH_SHORT).show();
}
/**
* 演示ContentProvider的查询操作
* @param view
*/
public void query(View view) {
Uri uri = Uri.parse("content://bzxy.day13.demo/student");
Cursor cursor = contentResolver.query(uri,null,null,null,null);
while(cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
Log.i(TAG, "学生的id是:"+id+",姓名是:" + name);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.day13">
<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>
<provider
android:name=".MyContentProvider"
android:authorities="bzxy.day13.demo"
android:exported="true" />
</application>
</manifest>
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "demo";
private static final int VERSION = 2;
public DBHelper(@Nullable Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table if not exists student(id integer primary key autoincrement, name varchar not null)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) {
String sql = "create table if not exists teacher(id integer primary key autoincrement, name varchar not null)";
db.execSQL(sql);
}
}
}
MyContentProvider.java
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;
/**
* 自定义ContentProvider
*/
public class MyContentProvider extends ContentProvider {
private DBHelper dbHelper;
private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 配置UriMatcher
static {
uriMatcher.addURI("bzxy.day13.demo", "student", 1);
uriMatcher.addURI("bzxy.day13.demo", "teacher", 2);
}
@Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = null;
switch (uriMatcher.match(uri)) {
case 1:
cursor = database.query("student", projection, selection, selectionArgs, null, null, sortOrder);
break;
case 2:
cursor = database.query("teacher", projection, selection, selectionArgs, null, null, sortOrder);
break;
default:
break;
}
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
long id = 0;
switch (uriMatcher.match(uri)) {
case 1:
id = database.insert("student",null, values);
break;
case 2:
id = database.insert("teacher",null, values);
break;
default:
break;
}
Uri newUri = ContentUris.withAppendedId(uri, id);
database.close();
return newUri;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
int row = 0;
switch (uriMatcher.match(uri)){
case 1:
row = database.delete("student", selection, selectionArgs);
break;
case 2:
row = database.delete("teacher", selection, selectionArgs);
break;
default:
break;
}
database.close();
return row;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
int row = 0;
switch (uriMatcher.match(uri)) {
case 1:
row = database.update("student", values, selection, selectionArgs);
break;
case 2:
row = database.update("teacher", values, selection, selectionArgs);
break;
default:
break;
}
database.close();
return row;
}
}
part2:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="insert"
android:text="insert" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="delete"
android:text="delete" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="update"
android:text="update" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="query"
android:text="query" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
效果图:
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private ContentResolver contentResolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentResolver = getContentResolver();
}
/**
* 演示插入操作
* @param view
*/
public void insert(View view) {
}
/**
* 演示删除操作
* @param view
*/
public void delete(View view) {
}
/**
* 演示更新操作
* @param view
*/
public void update(View view) {
}
/**
* 演示查询操作
* @param view
*/
public void query(View view) {
Uri uri = Uri.parse("content://bzxy.day13.demo/teacher");
Cursor cursor = contentResolver.query(uri,null,null,null,null);
while(cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
Log.i("demo", "老师的id是:"+id+",姓名是:" + name);
}
}
}
part3:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:onClick="sendBroadcast"
android:text="发送广播"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:onClick="showLocalBroadcast"
android:text="演示本地广播"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
<Button
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:onClick="showRefresh"
android:text="通过广播进行列表刷新"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button2" />
</androidx.constraintlayout.widget.ConstraintLayout>
效果图:
MyBroadcastReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
/**
* 接收到广播的时候触发
* @param context
* @param intent
*/
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"接收到广播了", Toast.LENGTH_SHORT).show();
}
}
MyReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "广播接收到了", Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.day13_broadcast">
<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=".RefreshActivity"></activity>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <!-- 广播注册 -->
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="bzxy.day13.demo" />
</intent-filter>
</receiver>
</application>
</manifest>
效果图:
点击发送广播
part4:
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
/*
* 什么是广播:对于Activity来讲,触发只能是一对一,做不到一对多。广播可以弥补Activity的缺陷,做到消息的
* 一对多传递。
* 应用场景:非常广阔,应用于监听数据变化等等。
* 实现广播:
* 1.广播
* 2.触发:凡是可以触发事件的地方,都可以触发广播
* 3.订阅广播
* 广播订阅:
* 1.动态订阅
* 2.静态订阅
* 广播的分类
* 1.系统广播
* 2.自定义广播
* 2.1顺序广播
* 2.2正常广播
* 3.本地广播(如果只是在本app中进行广播的话,建议使用本地广播)
* */
private MyBroadcastReceiver myBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 订阅广播
// myBroadcastReceiver = new MyBroadcastReceiver();
// IntentFilter filter = new IntentFilter();
// filter.addAction("bzxy.day13.demo");
// registerReceiver(myBroadcastReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 取消订阅
// unregisterReceiver(myBroadcastReceiver);
}
/**
* 发送广播
* @param view
*/
public void sendBroadcast(View view) {
Intent intent = new Intent();
// intent.setAction("bzxy.day13.demo"); // 广播的标识 day13_broadcast
ComponentName componentName = new ComponentName("com.example.day13_broadcast",
"com.example.day13_broadcast.MyReceiver");
intent.setComponent(componentName);
sendBroadcast(intent);
}
/**
* 演示本地广播
* @param view
*/
public void showLocalBroadcast(View view) {
}
public void showRefresh(View view) {
Intent intent = new Intent(this, RefreshActivity.class);
startActivity(intent);
}
}
activity_refresh.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RefreshActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
效果图:
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "demo";
private static final int VERSION = 1;
public DBHelper(@Nullable Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table if not exists user (id integer primary key autoincrement, name varchar not null)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
User.java
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
user_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="47dp"
android:layout_marginLeft="47dp"
android:layout_marginTop="35dp"
android:text="TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="23dp"
android:layout_marginEnd="23dp"
android:layout_marginRight="23dp"
android:text="删除"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
效果图:
RefreshAdapter
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
public class RefreshAdapter extends BaseAdapter {
private List<User> data;
private Context context;
private LayoutInflater inflater;
public RefreshAdapter(List<User> data, Context context) {
this.data = data;
this.context = context;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder ;
if (convertView == null) {
convertView = inflater.inflate(R.layout.user_item, null);
viewHolder = new ViewHolder();
viewHolder.tv_id = convertView.findViewById(R.id.tv_id);
viewHolder.tv_name = convertView.findViewById(R.id.tv_name);
viewHolder.btn_delete = convertView.findViewById(R.id.btn_delete);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final User user = data.get(position);
viewHolder.tv_id.setText(user.getId()+"");
viewHolder.tv_name.setText(user.getName());
viewHolder.btn_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 删除数据
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase database = dbHelper.getWritableDatabase();
int row = database.delete("user", "id=?", new String[]{user.getId()+""});
// 发送广播
Intent intent = new Intent();
intent.setAction("user.delete");
context.sendBroadcast(intent);
}
});
return convertView;
}
class ViewHolder {
public TextView tv_id;
public TextView tv_name;
public Button btn_delete;
}
}
RefreshActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class RefreshActivity extends AppCompatActivity {
private DBHelper dbHelper;
private List<User> data;
private RefreshAdapter adapter;
private UserDeleteBroadcast userDeleteBroadcast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_refresh);
dbHelper = new DBHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
// 准备数据
for(int i=0; i<10; i++) {
ContentValues contentValues = new ContentValues();
contentValues.put("name", "张三"+i);
database.insert("user", null, contentValues);
}
getData();
// 初始化ListView
ListView listView = findViewById(R.id.listView);
adapter = new RefreshAdapter(data, this);
listView.setAdapter(adapter);
// 注册广播
userDeleteBroadcast = new UserDeleteBroadcast();
registerReceiver(userDeleteBroadcast,new IntentFilter("user.delete"));
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(userDeleteBroadcast);
}
/**
* 创建广播接收
*/
private class UserDeleteBroadcast extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// 查询数据库
getData();
// 更新列表
adapter.notifyDataSetChanged();
}
}
/**
* 获取数据
*/
private void getData() {
// 数据封装
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.query("user",null,null,null,null,null,null);
if (data != null) {
data.clear();
} else {
data = new ArrayList<>();
}
while(cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
User user = new User(id,name);
data.add(user);
}
}
}
效果图:
点击通过广播进行列表刷新