ContentProvider作为服务端接口

activity_content_provider.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="10dp" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp" >

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            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="5dp"
            android:layout_marginTop="5dp"
            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:textColorHint="@color/grey"
            android:textCursorDrawable="@drawable/text_cursor"
            android:textSize="17sp" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp" >

        <TextView
            android:id="@+id/tv_age"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            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="5dp"
            android:layout_marginTop="5dp"
            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:textColorHint="@color/grey"
            android:textCursorDrawable="@drawable/text_cursor"
            android:textSize="17sp" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp" >

        <TextView
            android:id="@+id/tv_height"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            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="5dp"
            android:layout_marginTop="5dp"
            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:textColorHint="@color/grey"
            android:textCursorDrawable="@drawable/text_cursor"
            android:textSize="17sp" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp" >

        <TextView
            android:id="@+id/tv_weight"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            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="5dp"
            android:layout_marginTop="5dp"
            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:textColorHint="@color/grey"
            android:textCursorDrawable="@drawable/text_cursor"
            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" />

    <TextView
        android:id="@+id/tv_read_user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:textColor="@color/black"
        android:textSize="17sp" />

</LinearLayout>

AndroidManifest.xml 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.forth">
    <application android:name=".MainApplication"
        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"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name=".UserInfoProvider"
            android:authorities="com.example.storage.provider.UserInfoProvider"
            android:enabled="true"
            android:exported="true" />
    </application>

</manifest>

 MainActivity.java

package com.example.forth;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "ContentProviderActivity";
    private EditText et_name;
    private EditText et_age;
    private EditText et_height;
    private EditText et_weight;
    private TextView tv_read_user;
    private String mUserCount = "";
    private String mUserResult = "";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_provider);
        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);
        tv_read_user = findViewById(R.id.tv_read_user);
        findViewById(R.id.btn_add_user).setOnClickListener(this);
        tv_read_user.setOnClickListener(this);
        showUserInfo();
    }
    // 显示所有用户信息
    private void showUserInfo() {
        mUserResult = readAllUser(getContentResolver());
        String[] split = mUserResult.split("\n");
        int count = (!mUserResult.contains("\n")) ? 0 : split.length;
        mUserCount = String.format("当前共找到%d位用户信息", count);
        tv_read_user.setText(mUserCount);
    }

    // 添加一条用户记录
    private void addUser(ContentResolver resolver, 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("married", false);
        name.put("update_time", DateUtil.getNowDateTime(""));
        // 通过内容解析器往指定Uri中添加用户信息
        resolver.insert(UserInfoContent.CONTENT_URI, name);
    }
    // 读取所有的用户记录
    private String readAllUser(ContentResolver resolver) {
        ArrayList<UserInfo> userArray = new ArrayList<UserInfo>();
        // 通过内容解析器从指定Uri中获取用户记录的游标
        Cursor cursor = resolver.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));
            userArray.add(user); // 添加到用户信息队列
        }
        cursor.close(); // 关闭数据库游标

        String result = "";
        for (UserInfo user : userArray) {
            // 遍历用户信息队列,逐个拼接到结果字符串
            result = String.format("%s%s	年龄%d	身高%d	体重%f\n", result,
                    user.name, user.age, user.height, user.weight);
        }
        Log.d(TAG, "result=" + result);
        return result;
    }
    private void showToast(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_add_user) {
            UserInfo user = new UserInfo();
            user.name = et_name.getText().toString().trim();
            user.age = Integer.parseInt(et_age.getText().toString().trim());
            user.height = Integer.parseInt(et_height.getText().toString().trim());
            user.weight = Float.parseFloat(et_weight.getText().toString().trim());
            addUser(getContentResolver(), user);
            showUserInfo();
        } else if (v.getId() == R.id.tv_read_user) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(mUserCount);
            builder.setMessage(mUserResult);
            builder.setPositiveButton("确定", null);
            builder.create().show();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值