首页 > 其他分享 >Android 内容提供器

Android 内容提供器

时间:2022-11-20 13:37:17浏览次数:66  
标签:String 提供 uri Uri BOOK 内容 Android null public

内容提供器(Content Provider)

简介

内容提供器(Content Provider)主要用于在不同的应用程序之间实现数据共享的功能,它提供了一套完整的机制,允许一个程序访问另一个程序中的数据,同时还能保证被访数据的安全性。
img

Android权限机制详解

在AndroidManifest.xml文件中添加权限

<uses-permission android:name=""/>

权限列表查看地址
http://developer.android.com/reference/android/Manifest.permission.html

代码中的权限申请

// 第一步判断:
ContextCompat.checkSelfPermission()
//两个参数,第一个Context,第二个权限名称
//第二步申请授权:
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CALL_PHONE},1)
//第三步验证授权:
onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults)

访问其他程序中的数据

对于应用程序来说,如果想要访问内容提供器中的共享数据,需要借助ContentResolver类
可以通过Context中的getContentResolver()方法获取到该实例。

Uri uri = Uri.parse("content://com.example.app.provider/table1");
Cursor cursor = getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);

//遍历
if(cursor.moveToFirst()){
do{
}while(cursor.moveToNext)
}

读取通讯录中的联系人和手机号码

<uses-permission android:name="android.permission.READ_CONTACTS"/>
ListView contactsView = findViewById(R.id.contacts_view);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, contactsList);
contactsView.setAdapter(adapter);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
} else {
    readContacts();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case 1:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                readContacts();
            } else {
                Toast.makeText(this, "you denied the premission", Toast.LENGTH_SHORT).show();
            }
            break;
        default:
    }
}


private void readContacts() {
    Cursor cursor = null;
    try {
        cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range")
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                @SuppressLint("Range")
                String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contactsList.add(name + "\n" + number);
            }
            adapter.notifyDataSetChanged();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

创建自己的内容提供器

创建MyProvider继承ContentProvider

public class MyProvider extends ContentProvider {


    public static final int BOOK_DIR =0;
    public static final int BOOK_ITEM = 1;
    private static UriMatcher uriMatcher;
    public static final String AUTHORITY = "com.example.providertest.provider";


    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(AUTHORITY,"book",BOOK_DIR);
        uriMatcher.addURI(AUTHORITY,"book/#",BOOK_ITEM);
    }


    @Override
    public boolean onCreate() {
        return false;
    }


    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        switch (uriMatcher.match(uri)){
            case BOOK_DIR:
                // 查询book表中的所有数据
                break;
            case BOOK_ITEM:
                // 查询book表中的单条数据
                break;
            default:
                break;
        }


        return null;
    }


    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        switch (uriMatcher.match(uri)){
            case BOOK_DIR:
                return "vnd.android.cursor.dir/vnd.com.example.providertest.provider.book";
            case BOOK_ITEM:
                return "vnd.android.cursor.item/vnd.com.example.providertest.provider.book";
            default:
                break;
        }
        return null;
    }


    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {


        return null;
    }


    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }


    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }
}

在AndroidManifest.xml中

<provider
    android:name=".DatabaseProvider"
    android:authorities="com.example.providertest.provider"
    android:enabled="true"
    android:exported="true"></provider>

新建DatabaseProvider继承ContentProvider

public class DatabaseProvider extends ContentProvider {


    public static final int BOOK_DIR = 0;
    public static final int BOOK_ITEM = 1;


    private MydbHelper mydbHelper;


    private static UriMatcher uriMatcher;


    public static final String AUTHORITY = "com.example.providertest.provider";


    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(AUTHORITY, "book", BOOK_DIR);
        uriMatcher.addURI(AUTHORITY, "book/#", BOOK_ITEM);


    }




    public DatabaseProvider() {
    }


    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mydbHelper.getReadableDatabase();
        int deleteRows = 0;
        switch (uriMatcher.match(uri)) {
            case BOOK_DIR:
                deleteRows = db.delete("Book", selection, selectionArgs);
                break;
            case BOOK_ITEM:
                String bookId = uri.getPathSegments().get(1);
                deleteRows = db.delete("Book", "id = ?", new String[]{bookId});
                break;
            default:
                break;
        }
        return deleteRows;
    }


    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)){
            case BOOK_DIR:
                return "vnd.android.cursor.dir/vnd.com.example.providertest.provider.book";
            case BOOK_ITEM:
                return "vnd.android.cursor.item/vnd.com.example.providertest.provider.book";
            default:
                break;
        }
        return null;
    }


    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = mydbHelper.getReadableDatabase();
        Uri uriReturn = null;
        switch (uriMatcher.match(uri)) {
            case BOOK_DIR:
            case BOOK_ITEM:
                long newBookId = db.insert("Book", null, values);
                uriReturn = Uri.parse("content://" + AUTHORITY + "/book/" + newBookId);
                break;
            default:
                break;
        }
        return uriReturn;
    }


    @Override
    public boolean onCreate() {
        mydbHelper = new MydbHelper(getContext(), "BookStore.db", null, 2);
        return true;
    }


    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        Cursor cursor = null;
        SQLiteDatabase db = mydbHelper.getReadableDatabase();
        switch (uriMatcher.match(uri)) {
            case BOOK_DIR:
                cursor = db.query("Book", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case BOOK_ITEM:
                String bookId = uri.getPathSegments().get(1);
                cursor = db.query("Book", projection, "id = ?", new String[]{bookId}, null, null, sortOrder);
                break;
            default:
                break;
        }




        return cursor;
    }


    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        SQLiteDatabase db = mydbHelper.getReadableDatabase();
        int updateRows = 0;
        switch (uriMatcher.match(uri)) {
            case BOOK_DIR:
                updateRows = db.update("Book", values, null, null);
                break;
            case BOOK_ITEM:
                String bookId = uri.getPathSegments().get(1);
                updateRows = db.update("Book", values, "id = ?", new String[]{bookId});
                break;
            default:
                break;
        }
        return updateRows;
    }
}

主活动中使用getContentResolver()增删改查处理

//增
findViewById(R.id.button1).setOnClickListener(v -> {
ContentValues values = new ContentValues();
values.put("name", "yyyyyyyypppppppp");
values.put("author", "tt111tt");
values.put("pages", 900);
values.put("price", 10.99);
Uri uri = Uri.parse("content://com.example.providertest.provider/book");
Uri insert = getContentResolver().insert(uri, values);
newId = insert.getPathSegments().get(1);
});

//删
findViewById(R.id.button3).setOnClickListener(v -> {
Uri uri = Uri.parse("content://com.example.providertest.provider/book/" + newId);
    getContentResolver().delete(uri,null,null);
});

//改
findViewById(R.id.button2).setOnClickListener(v -> {
ContentValues values = new ContentValues();
values.put("name", "zybao");
Uri uri = Uri.parse("content://com.example.providertest.provider/book/" + newId);
getContentResolver().update(uri,values,null,null);

});

//查
findViewById(R.id.button4).setOnClickListener(v -> {
Uri uri = Uri.parse("content://com.example.providertest.provider/book");
    Cursor cursor2 =getContentResolver().query(uri,null,null,null,null);
    if (cursor2.moveToFirst()) {
        do {
            String name = cursor2.getString(cursor2.getColumnIndexOrThrow("name"));
            Log.d("cursor2", "book name is " + name);
        } while (cursor2.moveToNext());
    }
});

标签:String,提供,uri,Uri,BOOK,内容,Android,null,public
From: https://www.cnblogs.com/zybao/p/16908298.html

相关文章

  • Android 数据存储方案
    Android数据存储方案利用文件进行存取数据写入文件数据openFileOutput是Context中提供的一个方法,用于将数据存储到指定的文件中,第一个参数是文件名,第二个参数是文件......
  • Build failed due to use of deprecated Android v1 embedding.
    原文:https://blog.51cto.com/u_15639793/5340424 问题:Warning────────────────────────────────────────────────......
  • Android 使用网络技术
    Android使用网络技术使用<!--在布局文件中增加--><WebViewandroid:id="@+id/web_view"android:layout_width="match_parent"android:layout_height="......
  • 性能测试报告的内容和性能测试方案【杭州多测师】【杭州多测师_王sir】
    一、性能测试报告的内容1、基本概况2、测试背景目标==》测试目的、术语及缩写词3、测试准则==》启动准则、结束准则4、测试工具及环境配置==》性能测试环境配置 、测试工具......
  • 2022-11-19学习内容-Server端代码编写-Client端代码编写
    1.Server端代码编写1.1UserDBHelper.javapackagecom.example.chapter07_server.database;importandroid.content.Context;importandroid.database.sqlite.SQLiteD......
  • Android 利用和风天气API显示实时天气
    最近开发遇到了这样的需求,需要在APP中显示出实时天气等信息,可以利用和风天气提供的API,免费订阅可以使用一定数量的查询额度,不过也差不多够用了。进入和风天气官网,注册。......
  • eclipse android快速搭建开发环境
    1.下载eclipse3.5以及以上ide和javaee工具​​​http://java.sun.com/javase/downloads/index.jsp​​​2下载AndroidSDK3.在eclipse下......
  • 遥控pc android应用程序
    遥控pcandroid应用程序 通过手机来控制您的电脑,在家里比如床上看电影,手机控制不用去直接操作电脑,多方便呀,呵呵。 分pc服务端程序,以及移动app应用程序。  1首先下载j......
  • android 一键锁屏
    android一键锁屏从操作上看,如果我们想锁屏休眠需要按手机上固定的按钮,现在通过桌面应用,只要将此应用图标放到桌面上点击一下即可锁屏休眠。从体......
  • css应用内容总结
     css作为前端三大重要组成之一也是尤为重要得,而且在日常生活中可能关于javascript的相关问题可以组织语言去百度,而对于一些css样式有时候可能却不好组织语言去表述这个问......