android 学习随笔二十一(内容提供者 )

一、内容提供者
* 应用的数据库是不允许其他应用访问的
* 内容提供者的作用就是让别的应用访问到你的私有数据
* 自定义内容提供者,继承ContentProvider类,重写增删改查方法,在方法中写增删改查数据库的代码,举例增方法

@Override
public Uri insert(Uri uri, ContentValues values) {
db.insert("person", null, values);
return uri;
}
* 在清单文件中定义内容提供者的标签,注意必须要有authorities属性,这是内容提供者的主机名,功能类似地址

<provider android:name="com.itheima.contentprovider.PersonProvider"
android:authorities="com.itheima.person"
android:exported="true"
></provider>

package com.itheima.mycontentprovider.db;

import java.io.Serializable;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Parcelable;

public class MyOpenHelper extends SQLiteOpenHelper {

    public MyOpenHelper(Context context) {
        super(context, "people.db", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table person(_id integer primary key autoincrement, name char(10), phone char(20), money integer(10))");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("create table handsome(_id integer primary key autoincrement, name char(10), phone char(20))");
    }

}

定义数据库

package com.itheima.mycontentprovider;

import com.itheima.mycontentprovider.db.MyOpenHelper;

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;

public class PersonProvider extends ContentProvider {

    private SQLiteDatabase db;
    //创建uri匹配器
    UriMatcher um = new UriMatcher(UriMatcher.NO_MATCH);
    {
        //添加匹配规则
        //arg0:主机名
        //arg1:路径
        //arg2:匹配码
        um.addURI("com.itheima.people", "person", 1);//content://com.itheima.people/person
        um.addURI("com.itheima.people", "handsome", 2);//content://com.itheima.people/handsome
        um.addURI("com.itheima.people", "person/#", 3);//content://com.itheima.people/person/10
    }

    //内容提供者创建时调用
    @Override
    public boolean onCreate() {
        MyOpenHelper oh = new MyOpenHelper(getContext());
        db = oh.getWritableDatabase();
        return false;
    }

    //values:其他应用要插的数据
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if(um.match(uri) == 1){
            db.insert("person", null, values);

            //数据库改变了,内容提供者发出通知
            //arg0:通知发到哪个uri上,注册在这个uri上的内容观察者都可以收到通知
            getContext().getContentResolver().notifyChange(uri, null);
        }
        else if(um.match(uri) == 2){
            db.insert("handsome", null, values);

            getContext().getContentResolver().notifyChange(uri, null);
        }
        else{
            throw new IllegalArgumentException("uri传错啦傻逼");
        }
        return uri;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int i = 0;
        if(um.match(uri) == 1){
            i = db.delete("person", selection, selectionArgs);
        }
        else if(um.match(uri) == 2){
            i = db.delete("handsome", selection, selectionArgs);
        }
        else{
            throw new IllegalArgumentException("uri又传错啦傻逼");
        }

        return i;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int i = db.update("person", values, selection, selectionArgs);
        return i;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        Cursor cursor = null;
        if(um.match(uri) == 1){
            cursor = db.query("person", projection, selection, selectionArgs, null, null, sortOrder, null);
        }
        else if(um.match(uri) == 2){
            cursor = db.query("handsome", projection, selection, selectionArgs, null, null, sortOrder, null);
        }
        else if(um.match(uri) == 3){
            //取出uri末尾携带的数字
            long id = ContentUris.parseId(uri);
            cursor = db.query("person", projection, "_id = ?", new String[]{"" + id}, null, null, sortOrder, null);
        }
        return cursor;
    }

    //返回通过指定uri获取的数据的mimetype
    @Override
    public String getType(Uri uri) {
        if(um.match(uri) == 1){
            return "vnd.android.cursor.dir/person";
        }
        else if(um.match(uri) == 2){
            return "vnd.android.cursor.dir/handsome";
        }
        else if(um.match(uri) == 3){
            return "vnd.android.cursor.item/person";
        }
        return null;
    }

}

内容提供者

package com.itheima.mycontentprovider;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

MainActivity

package com.itheima.mycontentprovider;

import com.itheima.mycontentprovider.db.MyOpenHelper;

import android.test.AndroidTestCase;

public class Test extends AndroidTestCase {

    public void test(){
        MyOpenHelper oh = new MyOpenHelper(getContext());
        oh.getWritableDatabase();
    }
}

test

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itheima.mycontentprovider"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
    android:targetPackage="com.itheima.mycontentprovider"></instrumentation>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <uses-library android:name="android.test.runner"/>
        <activity
            android:name="com.itheima.mycontentprovider.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="com.itheima.mycontentprovider.PersonProvider"
            android:authorities="com.itheima.people"

            android:exported="true"
>
        </provider>
    </application>

</manifest>

AndroidManifest

* 创建一个其他应用,访问自定义的内容提供者,实现对数据库的插入操作

public void click(View v){
//得到内容分解器对象
ContentResolver cr = getContentResolver();
ContentValues cv = new ContentValues();
cv.put("name", "小方");
cv.put("phone", 138856);
cv.put("money", 3000);
//url:内容提供者的主机名
cr.insert(Uri.parse("content://com.itheima.person"), cv);
}

package com.itheima.other;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void insert(View v){
        //通过内容提供者把数据插入01数据库
        //1.获取contentResolver
        ContentResolver resolver = getContentResolver();
        //2.访问内容提供者,插入数据
        ContentValues values = new ContentValues();
        values.put("name", "流氓润");
        values.put("phone", 138992);
        values.put("money", 14000);
        //arg0:指定内容提供者的主机名
        resolver.insert(Uri.parse("content://com.itheima.people/person"), values);

        values.clear();
        values.put("name", "侃哥");
        values.put("phone", 15999);
        //arg0:指定内容提供者的主机名
        resolver.insert(Uri.parse("content://com.itheima.people/handsome"), values);
    }

    public void delete(View v){
        ContentResolver resolver = getContentResolver();
        int i = resolver.delete(Uri.parse("content://com.itheima.people"), "name = ?", new String[]{"凤姐"});
        System.out.println(i);
    }

    public void update(View v){
        ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues();
        values.put("money", 16001);
        int i = resolver.update(Uri.parse("content://com.itheima.people"), values, "name = ?", new String[]{"春晓"});
        System.out.println(i);
    }

    public void query(View v){
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(Uri.parse("content://com.itheima.people/person"), null, null, null, null);
        while(cursor.moveToNext()){
            String name = cursor.getString(1);
            String phone = cursor.getString(2);
            String money = cursor.getString(3);
            System.out.println(name + ";" + phone + ";" + money);
        }
    }
    public void queryOne(View v){
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(Uri.parse("content://com.itheima.people/person/4"), null, null, null, null);
        if(cursor.moveToNext()){
            String name = cursor.getString(1);
            String phone = cursor.getString(2);
            String money = cursor.getString(3);
            System.out.println(name + ";" + phone + ";" + money);
        }
    }
}

------------------------------------------

时间: 2024-08-01 18:12:27

android 学习随笔二十一(内容提供者 )的相关文章

Android学习笔记二十一.使用ContentProvider实现数据共享(四).操作系统(联系人)的ContentProvider

Android系统本身提供了大量的ContentProvider,例如联系人信息.系统的多媒体信息等,我们开发的应用程序主要是通过ContentResolver来调用系统的ContentProvider提供的query().insert().update()和delete()方法来获取Android内部的数据. 一.如何使用ContentResolver操作系统ContentProvider暴露的内部数据? 1.调用Activity的getContentResolver()获取ContentRe

Android学习(二十一)OptionsMenu选项菜单

一.OptionsMenu选项菜单 在应用程序中点击功能按钮会弹出选项菜单,点击可以实现具体功能. 二.实现思路: 1.创建选项菜单: onCreateOptionsMenu(); 2.设置菜单项可用代码动态设置menu.add();还可以通过xml设置Menuinflater.infalte(R.menu.menu); 3.设置菜单的点击事件:onOptionsItemSelect(); 三.示例代码: 自定义菜单XML: <menu xmlns:android="http://sche

android 学习随笔二十八(应用小结 )

去掉标题栏的方法 第一种:也一般入门的时候经常使用的一种方法requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏注意这句一定要写在setContentView()方法的前面,不然会报错的 第二种:在AndroidManifest.xml文件中定义<application android:icon="@drawable/icon" android:label="@string/app_name" androi

android 学习随笔二十七(JNI:Java Native Interface,JAVA原生接口 )

JNI(Java Native Interface,JAVA原生接口) 使用JNI可以使Java代码和其他语言写的代码(如C/C++代码)进行交互. 问:为什么要进行交互? 首先,Java语言提供的类库无法满足要求,且在数学运算,实时渲染的游戏上,音视频处理等方面上与C/C++相比效率稍低. 然后,Java语言无法直接操作硬件,C/C++代码不仅能操作硬件而且还能发挥硬件最佳性能. 接着,使用Java调用本地的C/C++代码所写的库,省去了重复开发的麻烦,并且可以利用很多开源的库提高程序效率.

Android学习笔记二十九之SwipeRefreshLayout、RecyclerView和CardView

Android学习笔记二十九之SwipeRefreshLayout.RecyclerView和CardView 前面我们介绍了AlertDialog和几个常用的Dialog,ProgressDialog进度条提示框.DatePickerDialog日期选择对话框和TimePickerDialog时间选择对话框.这一节我们介绍几个新的API控件SwipeRefreshLayout.RecyclerView和CardView,这几个API控件都是google在Android5.0推出的.下面我们来学

Android学习笔记二

17. 在ContentProvider中定义的getType()方法是定义URI的内容类型. 18. SQLiteDatabase类中的insert/delete/update/query方法其实也挺好用的,我在EquipmentProvider类中做了实现 19. Android专门有个单元测试项目(Android Test Project),在这个项目中,可以新建一个继承AndroidTestCase类的具体测试类来单元测试某个功能.我新建了一个AndroidTestProject项目,在

Android学习路线(十一)管理Activity的生命周期

当一个用户进入,退出,再次进入你的应用时,你的应用中的Activity 会在它的生命周期的各个状态下切换.例如,当你的activity第一次启动,它出现在系统的前方接受用户的焦点.在这个过程中,Android系统调用了一系列的生命周期方法来设置UI和其他组件.如果用户执行了一个操作,启动了另一个activity或者切换到其它应用中,你的activity会移动到后台(这时activity已经不可见,但是它的实力和状态都保持不变),系统会调用另外的一些生命周期方法. 通过这些生命周期方法,你可以声明

Android学习笔记二十之Toast吐司、Notification通知、PopupWindow弹出窗

Android学习笔记二十之Toast吐司.Notification通知.PopupWindow弹出窗 Toast吐司 Toast吐司是我们经常用到的一个控件,Toast是AndroidOS用来显示消息的一种机制,它与Dialog不同,Toast不会获取到焦点,通常显示一段时间之后就会自动消失,下面我们来介绍Toast的几种常用方式: 第一种,默认显示方式,也是最常用的方式: Toast.makeText(MainActivity.this, "这是默认的显示方式", Toast.LE

Android学习笔记二十五之ListView多布局实现

Android学习笔记二十五之ListView多布局实现 这一节是介绍ListView这个控件的最后一节,实现一个Item的多布局.像我们经常在用的各种即时通讯工具,QQ.微信等,假设他们的会话界面是ListView实现的,那么ListView就有多种Item布局,这一节,我们就来实现一个ListView的多种Item. 要实现ListView里面有多种Item,就要重写适配器的两个方法getViewTypeCount()和getItemViewType(int position),第一个方法是