ContentProvider两个应用之间访问数据

MainActivity.java

package com.example.hd.contentprovider;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private Button mButton;
    private EditText mEditText_name;
    private EditText mEditText_addrss;
    private EditText mEditText_age;
    private Dboperator operator;
    private String name;
    private String address;
    private int age;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.Button);
        mEditText_addrss = (EditText) findViewById(R.id.EditText_address);
        mEditText_age = (EditText) findViewById(R.id.EditText_age);
        mEditText_name = (EditText) findViewById(R.id.EditText_name);
        operator = new Dboperator(MainActivity.this);
        mButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO 自动生成的方法存根
                address = mEditText_addrss.getText().toString();
                Log.i(TAG, "--------->>"+address);
                name = mEditText_name.getText().toString();
                Log.i(TAG, "--------->>"+name);
                try {
                    age = Integer.parseInt(mEditText_age.getText().toString());
                    Log.i(TAG, "--------->>"+age);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                long id = operator.insert(name, address, age);
                if (id > 0) {
                    Toast.makeText(MainActivity.this, "添加成功",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

}

DatabaseHelper.java

package com.example.hd.contentprovider;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO 自动生成的构造函数存根

    }

    public DatabaseHelper(Context context, String name, CursorFactory factory,
            int version, DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
        // TODO 自动生成的构造函数存根
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO 自动生成的方法存根
        String sql_creat = "create table person (_id integer primary key AutoIncrement,name varchar(64),address varchar(64),age integer)";
        db.execSQL(sql_creat);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO 自动生成的方法存根

    }

}

Dboperator

package com.example.hd.contentprovider;

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

public class Dboperator {
    private static final String TAG = "Dboperator";
    public static final int VERSION = 1;
    private SQLiteDatabase database;

    public Dboperator(Context context) {
        // TODO 自动生成的构造函数存根
        DatabaseHelper helper = new DatabaseHelper(context, "person_db", null, VERSION);
        database = helper.getWritableDatabase();
    }

    public long insert(String name,String address,int age){
        ContentValues value = new ContentValues();
        value.put("name", name);
        value.put("address", address);
        value.put("age", age);
        Long insert_id= database.insert("person", null, value);
        Log.i(TAG, "------>>"+insert_id);
        database.close();
        return insert_id;
    }

    public Cursor queryTest(){
        Cursor cursor = null;
        cursor = database.query(false, "person", null, null, null, null, null, null, null, null);
        return cursor;
    }

}

MyContentProvider.java

package com.example.hd.contentprovider;
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 android.util.Log;
import com.example.hd.contentprovider.Person;

public class MyContentProvider extends ContentProvider {
    private static final String TAG = "MyContentProvider";
    public DatabaseHelper helper;
    public SQLiteDatabase database;
    public static final UriMatcher sURI_MATCHER = new UriMatcher(
            UriMatcher.NO_MATCH);
    static {
        sURI_MATCHER.addURI("com.example.hd.contentprovider.MyContentProvider",
                "person", Person.PERSIONS);
        sURI_MATCHER.addURI("com.example.hd.contentprovider.MyContentProvider",
                "person/#", Person.PERSION);
    }

    @Override
    public boolean onCreate() {
        // TODO 自动生成的方法存根
        helper = new DatabaseHelper(getContext(), Person.DBNAME, null,
                Person.VERSION);
        Log.i(TAG, "---------->>onCreate");
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        // TODO 自动生成的方法存根
        database = helper.getWritableDatabase();
        Log.i(TAG, "------>>" + String.valueOf(uri));
        Cursor cursor = null;

        int flag = sURI_MATCHER.match(uri);

        switch (flag) {
        case Person.PERSION:
            long _id = ContentUris.parseId(uri);
            String where_value = "_id = " + _id;
            if (selection != null && !selection.equals("")) {
                where_value += selection;
            }
            cursor = database.query("person", projection, where_value,
                    selectionArgs, null, null, sortOrder);
            break;
        case Person.PERSIONS:
            cursor = database.query("person", projection, selection,
                    selectionArgs, null, null, sortOrder);
            break;

        default:
            Log.i(TAG, "------>>!!!!Unknown URI" + uri);
            throw new IllegalAccessError("Unknown URI" + uri);
        }
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        // TODO 自动生成的方法存根
        switch (sURI_MATCHER.match(uri)) {
        case Person.PERSION:
            return Person.CONTENT_ITEM_TYPE;
        case Person.PERSIONS:
            return Person.CONTENT_TYPE;
        default:
            Log.i(TAG, "------>>Unknown URI");
            throw new IllegalAccessError("Unknown URI" + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO 自动生成的方法存根
        int flag = sURI_MATCHER.match(uri);
        Long id = null;
        switch (flag) {
        case Person.PERSIONS:
            database = helper.getWritableDatabase();
            id = database.insert("person", null, values);
            break;
        default:
            Log.i(TAG, "------>>Unknown URI");
            throw new IllegalAccessError("Unknown URI" + uri);
        }
        if (id > 0) {
            Uri noteuri = ContentUris.withAppendedId(Person.CONTENT_URI, id);
            getContext().getContentResolver().notifyChange(noteuri, null);
            return noteuri;
        }
        throw new IllegalAccessError("Unknown URI" + uri);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO 自动生成的方法存根
        database = helper.getWritableDatabase();
        Long _id = ContentUris.parseId(uri);
        int num = 0;
        String where_value = "_id = " + _id;
        switch (sURI_MATCHER.match(uri)) {
        case Person.PERSION:
            if (selection != null && !selection.equals("")) {
                where_value += selection;
                Log.i(TAG, "----->>where_value" + where_value);
            }
            num = database.delete(Person.TNAME, where_value, selectionArgs);
            break;
        case Person.PERSIONS:
            num = database.delete(Person.TNAME, selection, selectionArgs);
            break;

        default:
            Log.i(TAG, "------>>Unknown URI");
            throw new IllegalAccessError("Unknown URI" + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return num;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO 自动生成的方法存根
        database = helper.getWritableDatabase();
        long _id = 0;
        int num = 0;
        switch (sURI_MATCHER.match(uri)) {
        case Person.PERSION:
            _id = ContentUris.parseId(uri);
            String where_value = "_id" +_id;
            if(selection!= null&&!selection.equals("")){
                where_value += selection;
                Log.i(TAG, "----->>>where_value"+where_value);
            }
            num = database.update(Person.TNAME, values, where_value, selectionArgs);
            break;
        case Person.PERSIONS:
            num = database.update(Person.TNAME, values, selection, selectionArgs);
            break;

        default:
            Log.i(TAG, "------>>Unknown URI");
            throw new IllegalAccessError("Unknown URI" + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return num;
    }

}

MyTest.java

package com.example.hd.contentprovider;

import android.database.Cursor;
import android.test.AndroidTestCase;
import android.util.Log;

public class MyTest extends AndroidTestCase {
    private static final String TAG = "MyTest";

    public MyTest() {
        // TODO 自动生成的构造函数存根
    }

    public void query(){
        Dboperator operator = new Dboperator(getContext());
        Cursor cursor = operator.queryTest();
        while (cursor.moveToNext()) {
            String age = cursor.getString(cursor.getColumnIndex("age"));
            Log.i(TAG, "------>>" + age);
            String address = cursor.getString(cursor.getColumnIndex("address"));
            Log.i(TAG, "------>>" + address);
        }
    }


}

Person.java

package com.example.hd.contentprovider;

import android.net.Uri;

public class Person {
    public static final String DBNAME = "person_db";
    public static final String TNAME = "person";
    public static final int VERSION = 1;
    public static final String AUTHORITY = "com.example.hd.contentprovider.MyContentProvider";
    public static final int PERSION = 1;
    public static final int PERSIONS = 2;
    public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.hd.person";
    public static final String CONTENT_ITEM_TYPE ="vnd.android.cursor.item/vnd.hd.person";
    public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/person");


}

layout_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText android:id="@+id/EditText_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入名字"/>
    <EditText 
        android:id="@+id/EditText_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入地址"/>
    <EditText 
        android:id="@+id/EditText_age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入年龄"/>
    <Button 
        android:id="@+id/Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加数据"/>

</LinearLayout>

AndroidMainfest.xml

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

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="21" />

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.example.hd.contentprovider" >
    </instrumentation>

    <permission
        android:name="com.example.hd.contentprovider.MyContentProvider"
        android:label="provider pomission"
        android:protectionLevel="normal" >
    </permission>

    <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=".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=".MyContentProvider"
            android:authorities="com.example.hd.contentprovider.MyContentProvider"
            android:exported="true"
            android:permission="com.example.hd.contentprovider.MyContentProvider" />
    </application>

</manifest>

创建另一个应用访问ContentProvider
MainActivity.java

package com.example.hd.content_pro_test;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class MainActivity extends Activity {
    private ListView mListView;
    private TextView mTextView_name;
    private TextView mTextView_address;
    private TextView mtextView_age;
    private SimpleCursorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.listview);
        mTextView_name = (TextView) findViewById(R.id.TextView_name);
        mTextView_address = (TextView) findViewById(R.id.TextView_address);
        mtextView_age = (TextView) findViewById(R.id.TextView_age);
        ContentResolver reslover = getContentResolver();
        Uri uri = Uri
                .parse("content://com.example.hd.contentprovider.MyContentProvider/person");
        Cursor cursor = reslover.query(uri, null, null, null, null);
        adapter = new SimpleCursorAdapter(MainActivity.this,
                R.layout.activity_main, cursor, new String[] { "name",
                        "address", "age" }, new int[] { R.id.TextView_name,
                        R.id.TextView_address, R.id.TextView_age });
        mListView.setAdapter(adapter);
    }

}

layout_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.hd.content_pro_test.MainActivity" >

    <ListView 
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>
   <LinearLayout 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal">
       <TextView 
           android:id="@+id/TextView_name"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_weight="1"/>
        <TextView 
           android:id="@+id/TextView_address"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_weight="1"/>
         <TextView 
           android:id="@+id/TextView_age"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_weight="1"/>
   </LinearLayout>

</RelativeLayout>

AndroidMainfest.xml

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

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="21" />
    <uses-permission android:name="com.example.hd.contentprovider.MyContentProvider"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
    </application>

</manifest>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值