内容提供者

news2025/3/15 0:21:59

1.Server服务编写

 

 

 UserInfoProvider.java

package com.tiger.chapter07_server.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import com.tiger.chapter07_server.database.UserDBHelper;

public class UserInfoProvider extends ContentProvider {

    private UserDBHelper dbHelper;


    private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    private static final int USERS = 1;//多行
    private static final int USER = 2;//一条

    static {
        //往Uri 匹配器中添加指定的数据路径
        URI_MATCHER.addURI(UserInfoContent.AUTHORITIES, "/user", USERS);
        URI_MATCHER.addURI(UserInfoContent.AUTHORITIES, "/user/#", USER);
    }

    //content://com.tiger.chapter07_server.provider.UserInfoProvider/user
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        Log.d("ning", "UserInfoProvider insert");
        if (URI_MATCHER.match(uri)==USERS){
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            db.insert(UserDBHelper.TABLE_NAME, null, values);
            db.close();
        }

        return uri;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int count = 0;
        switch (URI_MATCHER.match(uri)) {
            case USERS:
                SQLiteDatabase db1 = dbHelper.getWritableDatabase();

                count = db1.delete(UserDBHelper.TABLE_NAME, selection, selectionArgs);

                db1.close();
                break;

            case USER:
                //删除单行
                String id = uri.getLastPathSegment();
                SQLiteDatabase db2 = dbHelper.getWritableDatabase();
                count = db2.delete(UserDBHelper.TABLE_NAME, "_id=?", new String[]{id});
                db2.close();
                break;
        }


        return count;

    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public boolean onCreate() {

        Log.d("ning", "UserInfoProvider onCreate");

        dbHelper = UserDBHelper.getInstance(getContext());

        //true代表成功 ,false 代表失败
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        Log.d("ning", "UserInfoProvider insert");
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        return db.query(UserDBHelper.TABLE_NAME, projection, selection, selectionArgs, null, null, null, null);


    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // TODO: Implement this to handle requests to update one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

UserInfoContent

package com.tiger.chapter07_server.provider;

import android.net.Uri;

public class UserInfoContent {

    public static final String AUTHORITIES = "com.tiger.chapter07_server.provider.UserInfoProvider";

    //访问内容提供其的URI
    public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITIES+"/user");


    // 下面是该表的各个字段名称
    public static final String _ID = "_id";
    public static final String USER_NAME = "name";
    public static final String USER_AGE = "age";
    public static final String USER_HEIGHT = "height";
    public static final String USER_WEIGHT = "weight";
    public static final String USER_MARRIED = "married";


}

DbHelpler

package com.tiger.chapter07_server.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;


import com.tiger.chapter07_server.entity.User;

import java.util.ArrayList;
import java.util.List;

public class UserDBHelper extends SQLiteOpenHelper {


    private static final String DB_NAME = "user.db";
    private static final int DB_VERSION = 1;
    public static final String TABLE_NAME = "user_info";

    private static UserDBHelper mHelper = null;



    private UserDBHelper(@Nullable Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }


    //利用单例模式获取数据库帮助其的唯一实例  没有那么大的并发量 所以不用加锁
    public static UserDBHelper getInstance(Context context) {
        if (mHelper == null) {
            mHelper = new UserDBHelper(context);
        }
        return mHelper;
    }




    //创建数据库,执行建表语句
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
                " name VARCHAR NOT NULL," +
                " age INTEGER NOT NULL," +
                " height LONG NOT NULL," +
                " weight FLOAT NOT NULL," +
                " married INTEGER NOT NULL);";

        db.execSQL(sql);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }



}

2.Client编写

ContentWriteActivity.java

package com.tiger.chapter07_client;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
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.CheckBox;
import android.widget.EditText;

import com.tiger.chapter07_client.entity.User;
import com.tiger.chapter07_client.utils.ToastUtlis;

public class ContentWriteActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_name;
    private EditText et_age;
    private EditText et_height;
    private EditText et_weight;
    private CheckBox ck_married;


    @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);
        ck_married = findViewById(R.id.ck_married);


        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_delete).setOnClickListener(this);
        findViewById(R.id.btn_read).setOnClickListener(this);


    }

    @SuppressLint("Range")
    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.btn_save) {
            //调用getContentResolver 方法获取

            ContentValues values = new ContentValues();

            values.put(UserInfoContent.USER_NAME, et_name.getText().toString());
            values.put(UserInfoContent.USER_AGE, Integer.parseInt(et_age.getText().toString()));
            values.put(UserInfoContent.USER_HEIGHT, Integer.parseInt(et_height.getText().toString()));
            values.put(UserInfoContent.USER_WEIGHT, Float.parseFloat(et_weight.getText().toString()));
            values.put(UserInfoContent.USER_MARRIED, ck_married.isChecked());


            //第一个参数调用Uri  第二个参数 是传入的values值
            getContentResolver().insert(UserInfoContent.CONTENT_URI, values);
            ToastUtlis.show(this, "保存成功");


        } else if (v.getId() == R.id.btn_read) {

            Cursor cursor = getContentResolver().query(UserInfoContent.CONTENT_URI, null, null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    User info = new User();
                    info.id = cursor.getInt(cursor.getColumnIndex(UserInfoContent._ID));
                    info.name = cursor.getString(cursor.getColumnIndex(UserInfoContent.USER_NAME));
                    info.age = cursor.getInt(cursor.getColumnIndex(UserInfoContent.USER_AGE));
                    info.height = cursor.getInt(cursor.getColumnIndex(UserInfoContent.USER_HEIGHT));
                    info.weight = cursor.getFloat(cursor.getColumnIndex(UserInfoContent.USER_WEIGHT));
                    info.married = cursor.getInt(cursor.getColumnIndex(UserInfoContent.USER_MARRIED)) == 1 ? true : false;
                    Log.d("ning", info.toString());
                }
                cursor.close();

            }
        } else if (v.getId() == R.id.btn_delete) {
            Uri uri = ContentUris.withAppendedId(UserInfoContent.CONTENT_URI, 2);



//            int delete = getContentResolver().delete(uri, null, null);
            int delete = getContentResolver().delete(UserInfoContent.CONTENT_URI, null, null);


            if (delete > 0) {

                ToastUtlis.show(this, "删除成功");

            }
        }
    }
}

xml

<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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <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="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_weight="1"
            android:background="@drawable/editext_selector"
            android:hint="请输入姓名"
            android:inputType="text"
            android:maxLength="12"
            android:text="Jack"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <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="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_weight="1"
            android:background="@drawable/editext_selector"
            android:hint="请输入年龄"
            android:inputType="number"
            android:maxLength="2"
            android:text="18"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <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="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_weight="1"
            android:background="@drawable/editext_selector"
            android:hint="请输入身高"
            android:inputType="number"
            android:maxLength="3"
            android:text="180"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <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="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_weight="1"
            android:background="@drawable/editext_selector"
            android:hint="请输入体重"
            android:inputType="numberDecimal"
            android:maxLength="5"
            android:text="180"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>

    <CheckBox
        android:id="@+id/ck_married"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="false"
        android:gravity="center"
        android:text="已婚"
        android:textColor="@color/black"
        android:textSize="17sp" />

    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存"
        android:textColor="@color/black"
        android:textSize="17sp" />

    <Button
        android:id="@+id/btn_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="读取"
        android:textColor="@color/black"
        android:textSize="17sp" />

    <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" />

</LinearLayout>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1496436.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于逻辑回归实现乳腺癌预测(机械学习与大数据)

基于逻辑回归实现乳腺癌预测 将乳腺癌数据集拆分成训练集和测试集&#xff0c;搭建一个逻辑回归模型&#xff0c;对训练集进行训练&#xff0c;然后分别对训练集和测试集进行预测。输出以下结果&#xff1a; 该模型在训练集上的准确率&#xff0c;在测试集上的准确率、召回率和…

深入探讨javascript的流程控制与分支结构,以及js的函数

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; 所属的专栏&#xff1a;前端泛海 景天的主页&#xff1a;景天科技苑 文章目录 1.流程控制与分支结构1.if分支结构2.switch case 分支结构3.循环结…

微信小程序python+django+uniapp公交路线查询系统

原生wxml开发对Node、预编译器、webpack支持不好&#xff0c;影响开发效率和工程构建。所以都会用uniapp框架开发 前后端分离&#xff0c;后端给接口和API文档&#xff0c;注重前端,接近原生系统 APP性能需求 &#xff08;1&#xff09;用户在安卓APP页面各种操作可及时得到反馈…

【项目】图书管理系统

目录 前言&#xff1a; 项目要求&#xff1a; 知识储备&#xff1a; 代码实现&#xff1a; Main&#xff1a; Books包&#xff1a; Book&#xff1a; BookList&#xff1a; Operate包&#xff1a; Operate: addOperate: deleteOperate: exitOperate: findOperate:…

express基础

express express介绍 官网传送门基于 Node.js 平台&#xff0c;快速、开放、极简的 Web 开发框架express特点 Web 应用 Express 是一个基于 Node.js 平台的极简、灵活的 web 应用开发框架&#xff0c;它提供一系列强大的特性&#xff0c;帮助你创建各种 Web 和移动设备应用。…

UniSA: Unified Generative Framework for Sentiment Analysis

文章目录 UniSA&#xff1a;统一的情感分析生成框架文章信息研究目的研究内容研究方法1.总体架构图2.基准数据集SAEval3.Task-Specific Prompt4.Modal Mask Training5.Pre-training Tasks5.1Mask Context Modeling5.2Sentiment Polarity Prediction5.3Coarse-grained Label Con…

Object.keys()的用法

1、语法 Object.keys(obj) 参数&#xff1a;要返回其枚举自身属性的对象 返回值&#xff1a;一个表示给定对象的所有可枚举属性的字符串数组 2、处理对象&#xff0c;返回可枚举的属性数组 let person {name:“张三”,age:25,address:“深圳”,getName:function(){}} Obj…

第七十六 天WAF攻防-权限控制代码免杀异或运算变量覆盖混淆加密传参

第76天 WAF攻防-信息收集&识别&被动探针&代理池&仿指纹&白名单 知识点&#xff1a; 0、WAF介绍&模式&识别&防护等 1、信息收集被动扫描&第三方接口 2、信息收集基于爬虫&文件目录探针 3、信息收集基于用户&代理池&白名单 章…

【QT】定时器事件应用

public&#xff1a;//定时器void timerEvent(QTimerEvent *);private:int id;#include <QTimerEvent> //QWidget 默认不追踪鼠标事件 mylabel::mylabel(QWidget *parent) : QLabel(parent) {this->setMouseTracking(true);//启动定时器//参数1&#xff1a;触发定时器的…

f5——>字符串三角

暴力破解&#xff0c;双层循环&#xff0c;注意复制到新列表用append&#xff0c;这样更不容易出错 格式还是“”.join(str)

本地部署websocket服务端并结合内网穿透实现固定公网地址连接

文章目录 1. Java 服务端demo环境2. 在pom文件引入第三包封装的netty框架maven坐标3. 创建服务端,以接口模式调用,方便外部调用4. 启动服务,出现以下信息表示启动成功,暴露端口默认99995. 创建隧道映射内网端口6. 查看状态->在线隧道,复制所创建隧道的公网地址加端口号7. 以…

leetcode 3068. 最大节点价值之和【树形dp】

原题链接&#xff1a;3068. 最大节点价值之和 题目描述&#xff1a; 给你一棵 n 个节点的 无向 树&#xff0c;节点从 0 到 n - 1 编号。树以长度为 n - 1 下标从 0 开始的二维整数数组 edges 的形式给你&#xff0c;其中 edges[i] [ui, vi] 表示树中节点 ui 和 vi 之间有一…

二维码门楼牌管理系统应用场景:助力紧急服务

文章目录 前言一、紧急服务部门的传统挑战二、二维码门楼牌管理系统的优势三、实际应用案例分析四、未来展望 前言 随着城市化的快速发展&#xff0c;传统的门牌管理系统已无法满足现代社会的需求。二维码门楼牌管理系统的出现&#xff0c;为紧急服务部门&#xff08;如警察、…

鸿道Intewell-Win_V2.1.3_kyland软件版本发布说明

一、软件发布版本信息 版本号&#xff1a;V2.1.3_kyland 版本发布类型&#xff1a;trail试用版本 二、版本特点 适配 E211-1370&#xff08;J6412,8GB&#xff0c;256GB SSD&#xff09;设备 三、运行环境推荐 Intewell developer可以运行在windows7及windows10 64位 四、支…

精品中国货出海wordpress外贸独立站建站模板

旗袍唐装wordpress外贸网站模板 旗袍、唐装、华服wordpress外贸网站模板&#xff0c;适合做衣服生意的外贸公司官网使用。 https://www.jianzhanpress.com/?p3695 劳动防护wordpress外贸独立站模板 劳动防护wordpress外贸独立站模板&#xff0c;劳动保护、劳动防护用品外贸…

个人博客系列-后端项目-用户验证(5)

介绍 创建系统管理app&#xff0c;用于管理系统的用户&#xff0c;角色&#xff0c;权限&#xff0c;登录等功能&#xff0c;项目中将使用django-rest_framework进行用户认证和权限解析。这里将完成用户认证 用户验证 rest_framework.authentication模块中的认证类&#xff…

基于Python实现银行卡识别

在本文中将介绍如何使用Python和深度学习技术来实现银行卡识别功能。银行卡识别是一个在金融、安全等领域具有重要应用的问题&#xff0c;将使用深度学习模型来实现银行卡图像的识别和分类。 目录 引言数据集准备预处理和特征提取模型选择与训练模型评估与性能优化部署与应用 引…

怎么做加密文件二维码?分享文件更安全

怎么做一个加密文件二维码&#xff1f;在日常的工作和生活中&#xff0c;通过扫描二维码来查看或者下载文件的方式&#xff0c;被越来越多的人所使用&#xff0c;一方面是二维码的成本低&#xff0c;另一方面有利于提升便捷性和用户体验。 为了保证内容的隐私性和安全性&#…

Linux学习笔记——基本操作命令

目录 一、Shell 命令基础1、Shell 简介2、Shell 命令格式3、显示系统信息命令4、Shell 使用技巧 二、Linux 文件及目录管理1、Linux操作系统的目录结构2、文件及目录显示类命令3、文件及目录操作类命令4、文件内容的显示和处理5、文件查找类命令 三、vi、vim 编辑器的使用四、文…

以太网帧格式

以太网帧格式 以太网帧格式前导码&#xff08;Preamble&#xff09;帧起始界定符&#xff08;SFD&#xff0c;Start Frame Delimiter&#xff09;以太网帧头目的MAC地址源MAC地址长度/类型 数据段帧检验序列&#xff08;FCS&#xff0c;Frame Check Sequence&#xff09;帧间隙…