Android应用使用ContentProvider共享数据

1.

在当前应用新建一个MyContentProvider:Flie–>new–>other–>Content Provider,Class Name写MyContentProvider,URI Authority随便填个,我填的是com.jerehedu.ch08.mycontentprovider,点击确定即可。

2.

MyContentProvider.java里面代码如下:

package com.example.ygd.jreduch08;

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;

import com.example.ygd.jreduch08.dbhelper.MyDbHelper;

public class MyContentProvider extends ContentProvider {
    private MyDbHelper openHelper;
    private static final UriMatcher MATCHER=new UriMatcher(UriMatcher.NO_MATCH);    //声明一个urimatcher
    static{//注册两个URL
        MATCHER.addURI("com.jerehedu.ch08.mycontentprovider","info",1);   //访问info表所有信息    主机名在清单文件中有,路径填数据库名
        MATCHER.addURI("com.jerehedu.ch08.mycontentprovider","info/#",2);//根据id来访问
    }

    @Override
    public String getType(Uri uri) {
        switch (MATCHER.match(uri)){
            case 1:
                return "vnd.android.cursor.dir/info";
            case 2:
                return "vnd.android.cursor.item/info";
        }
        return null;
    }

    public MyContentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db=openHelper.getWritableDatabase();
        switch (MATCHER.match(uri)){
            case 1:
                return db.delete("info",selection,selectionArgs);
            case 2:
                long rowid=ContentUris.parseId(uri);   //从uri中拿到id
                String where="_id="+rowid;
                if(selection!=null&&!selection.equals("")){
                    where=selection+" and "+where;
                    return db.delete("info",where,selectionArgs);
                }
        }
        return 0;
    }



    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db=openHelper.getWritableDatabase();
        switch (MATCHER.match(uri)){
            case 1:
                long rowid=db.insert("info",null,values);
                return ContentUris.withAppendedId(uri,rowid);
            default:
                break;
        }
        return null;
    }

    @Override
    public boolean onCreate() {
        openHelper=new MyDbHelper(this.getContext(),1);
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db=openHelper.getReadableDatabase();
        switch (MATCHER.match(uri)){
            case 1:
                return db.query("info",projection,selection,selectionArgs,null,null,sortOrder);
            case 2:
                long rowid=ContentUris.parseId(uri);
                String where="_id="+rowid;
                if(selection!=null&&!selection.equals("")){
                    where=selection+" and "+where;
                }
                return db.query("info",projection,where,selectionArgs,null,null,sortOrder);
        }
        return null;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        SQLiteDatabase db=openHelper.getWritableDatabase();
        switch (MATCHER.match(uri)){
            case 1:
                return db.update("info",values,selection,selectionArgs);
            case 2:
                long rowid=ContentUris.parseId(uri);
                String where="_id="+rowid;
                if(selection!=null&&!selection.equals("")){
                    where=selection+" and "+where;
                }
                return db.update("info",values,where,selectionArgs);
        }
        return 0;
    }
}

3

新建一个项目,就叫MyContentProviderTest,添加两个Button:查询和添加;再添加一个TextView,用来展示数据,主函数如下:

package com.example.ygd.mycontentprovidertest;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button bt1,bt2;
    private TextView show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt1= (Button) findViewById(R.id.getUser);
        bt2= (Button) findViewById(R.id.insert);
        show= (TextView) findViewById(R.id.show);
        bt1.setOnClickListener(new View.OnClickListener() {     //bt1用来查询数据
            @Override
            public void onClick(View v) {
                Uri uri=Uri.parse("content://com.jerehedu.ch08.mycontentprovider/info");
                ContentResolver resolver=getContentResolver();
                Cursor cs=resolver.query(uri,null,null,null,null);
                StringBuffer sbff=new StringBuffer();
                while(cs.moveToNext()){
                    sbff.append(cs.getString(0));
                    sbff.append(cs.getString(1));
                    sbff.append(cs.getString(2));
                    sbff.append(cs.getString(3));
                    sbff.append(cs.getString(4));
                }
                show.setText(sbff.toString());
            }
        });

        bt2.setOnClickListener(new View.OnClickListener() {     //bt2用来插入数据
            @Override
            public void onClick(View v) {
                addUser();
                Toast.makeText(MainActivity.this, "插入成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void addUser(){
        Uri uri=Uri.parse("content://com.jerehedu.ch08.mycontentprovider/info");
        ContentResolver resolver=getContentResolver();
        ContentValues values=new ContentValues();
        values.put("name","外星人");
        values.put("pwd","123");
        values.put("age","0");
        values.put("imgUrl","http://adfjak.com");
        resolver.insert(uri,values);
    }
}

这样就实现了不同应用的数据共享。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值