Android Studio入门之内容共享ContentProvider讲解以及实现共享数据实战(附源码 超详细必看)

简介: Android Studio入门之内容共享ContentProvider讲解以及实现共享数据实战(附源码 超详细必看)

需要源码或运行有问题请点赞关注收藏后评论区留言~~~

一、通过ContentProvider封装数据

Android提供了四大组件。分别是活动Activity,广播Broadcast,服务Service,内容提供器ContentProvider。其中内容提供器涵盖与内部数据存取有关的一系列组件,完整的内容组件由内容提供器ContentProvider,内容解析器ContentResolver,内容观察器ContentObserver三部分组成。

ContentProvider给App存取内部数据提供了统一的外部接口,让不同的应用之间得以互相共享数据。 在实际编码中,ContentProvider只是服务端App存取数据的抽象类,开发者需要在其基础上实现一个完整的内容提供器,并重写下列数据库管理方法

onCreate方法

insert方法

delete方法

update方法

query方法

getType方法

1:编写用户信息表的数据库帮助器

2:编写内容提供器的基础字段类

3:通过右键菜单创建内容提供器

二、通过ContentResolver访问数据

如果客户端App想访问对方的内部数据,就要借助内容解析器ContentResolver,它提供的方法与ContentProvider一一对应,连参数的类型都雷同 接下来通过实例讲解 效果如下图 可以进行插入信息的操作

ContentReadActivity类

package com.example.chapter07;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.chapter07.bean.UserInfo;
import com.example.chapter07.provider.UserInfoContent;
import com.example.chapter07.util.ToastUtil;
import com.example.chapter07.util.Utils;
import java.util.ArrayList;
import java.util.List;
@SuppressLint("DefaultLocale")
public class ContentReadActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "ContentReadActivity";
    private TextView tv_desc;
    private LinearLayout ll_list; // 用户信息列表的线性布局
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_read);
        findViewById(R.id.btn_delete).setOnClickListener(this);
        tv_desc = findViewById(R.id.tv_desc);
        ll_list = findViewById(R.id.ll_list);
        showAllUser(); // 显示所有的用户记录
    }
    // 显示所有的用户记录
    private void showAllUser() {
        List<UserInfo> userList = new ArrayList<UserInfo>();
        // 通过内容解析器从指定Uri中获取用户记录的游标
        Cursor cursor = getContentResolver().query(UserInfoContent.CONTENT_URI, null, null, null, null);
        // 循环取出游标指向的每条用户记录
        while (cursor.moveToNext()) {
            UserInfo user = new UserInfo();
            user.name = cursor.getString(cursor.getColumnIndex(UserInfoContent.USER_NAME));
            user.age = cursor.getInt(cursor.getColumnIndex(UserInfoContent.USER_AGE));
            user.height = cursor.getInt(cursor.getColumnIndex(UserInfoContent.USER_HEIGHT));
            user.weight = cursor.getFloat(cursor.getColumnIndex(UserInfoContent.USER_WEIGHT));
            userList.add(user); // 添加到用户信息列表
        }
        cursor.close(); // 关闭数据库游标
        String contactCount = String.format("当前共找到%d个用户", userList.size());
        tv_desc.setText(contactCount);
        ll_list.removeAllViews(); // 移除线性布局下面的所有下级视图
        for (UserInfo user : userList) { // 遍历用户信息列表
            String contactDesc = String.format("姓名为%s,年龄为%d,身高为%d,体重为%f\n",
                    user.name, user.age, user.height, user.weight);
            TextView tv_contact = new TextView(this); // 创建一个文本视图
            tv_contact.setText(contactDesc);
            tv_contact.setTextColor(Color.BLACK);
            tv_contact.setTextSize(17);
            int pad = Utils.dip2px(this, 5);
            tv_contact.setPadding(pad, pad, pad, pad); // 设置文本视图的内部间距
            ll_list.addView(tv_contact); // 把文本视图添加至线性布局
        }
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_delete) {
            getContentResolver().delete(UserInfoContent.CONTENT_URI, "1=1", null);
            showAllUser();
            ToastUtil.show(this, "已删除所有记录");
        }
    }
}

ContentWriteActivity类

package com.example.chapter07;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import com.example.chapter07.bean.UserInfo;
import com.example.chapter07.provider.UserInfoContent;
import com.example.chapter07.util.DateUtil;
import com.example.chapter07.util.ToastUtil;
@SuppressLint("DefaultLocale")
public class ContentWriteActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "ContentWriteActivity";
    private EditText et_name;
    private EditText et_age;
    private EditText et_height;
    private EditText et_weight;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_write);
        et_name = findViewById(R.id.et_name);
        et_age = findViewById(R.id.et_age);
        et_height = findViewById(R.id.et_height);
        et_weight = findViewById(R.id.et_weight);
        findViewById(R.id.btn_add_user).setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_add_user) {
            UserInfo user = new UserInfo();
            user.name = et_name.getText().toString();
            user.age = Integer.parseInt(et_age.getText().toString());
            user.height = Integer.parseInt(et_height.getText().toString());
            user.weight = Float.parseFloat(et_weight.getText().toString());
            addUser(user); // 添加一条用户记录
        }
    }
    // 添加一条用户记录
    private void addUser(UserInfo user) {
        ContentValues name = new ContentValues();
        name.put("name", user.name);
        name.put("age", user.age);
        name.put("height", user.height);
        name.put("weight", user.weight);
        name.put("update_time", DateUtil.getNowDateTime(""));
        // 通过内容解析器往指定Uri添加用户信息
        getContentResolver().insert(UserInfoContent.CONTENT_URI, name);
        ToastUtil.show(this, "成功添加用户信息");
    }
}

activity_content_readXML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/btn_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除所有记录"
        android:textColor="@color/black"
        android:textSize="17sp" />
    <TextView
        android:id="@+id/tv_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:textColor="@color/black"
        android:textSize="17sp" />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/ll_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>
</LinearLayout>

activity_content_writeXML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp" >
        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="姓名:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/et_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="3dp"
            android:layout_marginTop="3dp"
            android:layout_toRightOf="@+id/tv_name"
            android:background="@drawable/editext_selector"
            android:gravity="left|center"
            android:hint="请输入姓名"
            android:inputType="text"
            android:maxLength="12"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp" >
        <TextView
            android:id="@+id/tv_age"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="年龄:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/et_age"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="3dp"
            android:layout_marginTop="3dp"
            android:layout_toRightOf="@+id/tv_age"
            android:background="@drawable/editext_selector"
            android:gravity="left|center"
            android:hint="请输入年龄"
            android:inputType="number"
            android:maxLength="2"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp" >
        <TextView
            android:id="@+id/tv_height"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="身高:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/et_height"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="3dp"
            android:layout_marginTop="3dp"
            android:layout_toRightOf="@+id/tv_height"
            android:background="@drawable/editext_selector"
            android:gravity="left|center"
            android:hint="请输入身高"
            android:inputType="number"
            android:maxLength="3"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp" >
        <TextView
            android:id="@+id/tv_weight"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="体重:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/et_weight"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="3dp"
            android:layout_marginTop="3dp"
            android:layout_toRightOf="@+id/tv_weight"
            android:background="@drawable/editext_selector"
            android:gravity="left|center"
            android:hint="请输入体重"
            android:inputType="numberDecimal"
            android:maxLength="5"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </RelativeLayout>
    <Button
        android:id="@+id/btn_add_user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="添加用户信息"
        android:textColor="@color/black"
        android:textSize="17sp" />
</LinearLayout>

创作不易 觉得有帮助请点赞关注收藏~~~

相关文章
|
开发工具 Android开发 iOS开发
如何在Android Studio中配置Flutter环境?
如何在Android Studio中配置Flutter环境?
3078 160
|
Android开发 Windows
Android studio 报错Connect to 127.0.0.1:8888 [/127.0.0.1] failed: Connection refused: connect(已解决)
这是一篇关于解决Android Studio报错“Connect to 127.0.0.1:8888 failed: Connection refused”的文章。问题通常因系统代理设置被Android Studio自动保存导致。解决方法是找到系统中Android Studio使用的gradle.properties文件(位于Windows的C:\Users\你的电脑用户名\.gradle或Mac的/Users/.{你的用户目录}/.gradle),删除或注释掉多余的代理配置后保存并重新Sync项目。希望此经验能帮助快速解决同类问题!
2612 36
|
Java Android开发
Android studio中build.gradle文件简单介绍
本文解析了Android项目中build.gradle文件的作用,包括jcenter仓库配置、模块类型定义、包名设置及依赖管理,涵盖本地、库和远程依赖的区别。
1078 19
|
XML 搜索推荐 Android开发
Android改变进度条控件progressbar的样式(根据源码修改)
本文介绍了如何基于Android源码自定义ProgressBar样式。首先分析了系统源码中ProgressBar样式的定义,发现其依赖一张旋转图片实现动画效果。接着分两步指导开发者实现自定义:1) 模仿源码创建一个旋转动画XML文件(放置在drawable文件夹),修改图片为自定义样式;2) 在UI控件中通过`indeterminateDrawable`属性应用该动画。最终实现简单且个性化的ProgressBar效果,附带效果图展示。
716 2
|
前端开发 程序员 开发工具
|
9月前
|
移动开发 前端开发 Android开发
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
1682 12
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
9月前
|
移动开发 JavaScript 应用服务中间件
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
1101 5
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
9月前
|
移动开发 Rust JavaScript
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
1188 4
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
10月前
|
开发工具 Android开发
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
919 11
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
|
9月前
|
移动开发 Android开发
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
419 0

热门文章

最新文章