android通过ContentProvider实现应用间的数据共享

      此demo通过ContentProvider实现应用间的数据共享,并且定义了全局常量(当然也可以定义全局变量)。


demo:下载地址


manifest文件:




    
        
            
                

                
            
        

        

    


MyContentProvider.java文件(只实现了插入和搜索):

package fk.androiddemo_015;

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.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

import java.sql.SQLException;
import java.util.HashMap;

import fk.androiddemo_015.MyProviderMetaData.UserTableMetaDate;

//此类已在Mainfest中声明,需要时系统会自动调用它
public class MyContentProvider extends ContentProvider {
    public static final UriMatcher uriMatcher;
    public static final int INCOMING_USER_COLLECTION = 1;
    public static final int INCOMING_USER_SINGLE = 2;
    private DatabaseHelper dh;//注意

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(MyProviderMetaData.AUTHORIY, "/users", INCOMING_USER_COLLECTION);
        uriMatcher.addURI(MyProviderMetaData.AUTHORIY, "/users/#", INCOMING_USER_SINGLE);
    }

    public static HashMap userProjectionMap;

    static {
        userProjectionMap = new HashMap<>();
        userProjectionMap.put(UserTableMetaDate._ID, UserTableMetaDate._ID);
        userProjectionMap.put(UserTableMetaDate.USER_NAME, UserTableMetaDate.USER_NAME);
    }

    public MyContentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        System.out.println("getType");
        switch (uriMatcher.match(uri)) {
            case INCOMING_USER_COLLECTION:
                return UserTableMetaDate.CONTENT_TYPE;
            case INCOMING_USER_SINGLE:
                return UserTableMetaDate.CONTENT_TYPE_ITEM;
            default:
                throw new IllegalArgumentException("Unknown URI" + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO: Implement this to handle requests to insert a new row.
        System.out.println("insert");
        SQLiteDatabase db = dh.getWritableDatabase();
        long rowId = db.insert(UserTableMetaDate.TABLE_NAME, null, values);
        if (rowId > 0) {
            Uri insertedUserUri = ContentUris.withAppendedId(UserTableMetaDate.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(insertedUserUri, null);
            return insertedUserUri;
        } else {
            try {
                throw new SQLException("Failed to insert row into" + uri);
            } catch (SQLException e) {
                System.out.println("Failed to insert row into" + uri);
            }
            return uri;
        }
    }

    @Override
    public boolean onCreate() {
        // TODO: Implement this to initialize your content provider on startup.
        dh = new DatabaseHelper(getContext(), MyProviderMetaData.DATABASE_NAME);
        System.out.println("onCreat");
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // TODO: Implement this to handle query requests from clients.
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        switch (uriMatcher.match(uri)) {
            case INCOMING_USER_COLLECTION:
                qb.setTables(UserTableMetaDate.TABLE_NAME);
                qb.setProjectionMap(userProjectionMap);
                break;
            case INCOMING_USER_SINGLE:
                qb.setTables(UserTableMetaDate.TABLE_NAME);
                qb.setProjectionMap(userProjectionMap);
                qb.appendWhere(UserTableMetaDate._ID + "=" + uri.getPathSegments().get(1));
                break;
        }
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = UserTableMetaDate.DEFAULT_SORT_ORDER;
        } else orderBy = sortOrder;
        SQLiteDatabase db = dh.getWritableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // TODO: Implement this to handle requests to update one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

MyProviderMetaData.java(一些全局常量):

package fk.androiddemo_015;

import android.net.Uri;
import android.provider.BaseColumns;

/**
 * Created by Administrator on 2016/10/4.
 */
//定义一些全局常量
public class MyProviderMetaData {
    //注意和manifests中声明的保持一样
    public static final String AUTHORIY = "FK.bbs.MyContentProvider";
    public static final String DATABASE_NAME = "MyProvider.db";
    public static final String USER_TABLE_NAME = "users";
    public static final int DATABASE_VERSION = 1;

    public static final class UserTableMetaDate implements BaseColumns {
        public static final String TABLE_NAME = "users";

        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORIY + "/users");
        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.myprovider.user";
        public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.myprovider.user";

        public static final String USER_NAME = "name";
        public static final String DEFAULT_SORT_ORDER = "_id desc";
    }

}

DatabaseHelper.java(数据库工具类):

package fk.androiddemo_015;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import fk.androiddemo_015.MyProviderMetaData.UserTableMetaDate;
/**
 * Created by Administrator on 2016/10/4.
 */
//MyContentProvider中要用
public class DatabaseHelper extends SQLiteOpenHelper {
    private static final int VERSION = 1;

    public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
                          int version) {
        super(context, name, factory, version);
    }

    public DatabaseHelper(Context context, String name, int version) {
        this(context, name, null, version);
    }

    public DatabaseHelper(Context context, String name) {
        this(context, name, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println("create a database");
        db.execSQL("create table "+UserTableMetaDate.TABLE_NAME+"(" + UserTableMetaDate._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,name varchar(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.println(oldVersion + " update to " + newVersion);
    }

}

主界面:

package fk.androiddemo_015;
//1,在MyProviderMetaData定义元数据
//2,在MyContentProvider继承实现ContentProvider(在里面实现对相应数据库的操作)
//3,在Manifest中声明MyContentProvider
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import fk.androiddemo_015.MyProviderMetaData.UserTableMetaDate;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    Button but1,but2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        but1 = (Button) findViewById(R.id.but1);
        but1.setOnClickListener(this);
        but2 = (Button) findViewById(R.id.but2);
        but2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view == but1) {//向数据库中插入数据,没有会自动创建一个
            ContentValues values = new ContentValues();
            values.put(UserTableMetaDate.USER_NAME, "boboshen");
            Uri uri = getContentResolver().insert(UserTableMetaDate.CONTENT_URI, values);
            System.out.println("uri--->" + uri.toString());
        } else {//查询数据库,没有会自动创建一个
            Cursor c = getContentResolver().query(UserTableMetaDate.CONTENT_URI, null, null, null, null);
            while (c.moveToNext())
                System.out.println(c.getString(c.getColumnIndex(UserTableMetaDate.USER_NAME)));
        }
    }
}






你可能感兴趣的:(Android,学习整理)