• ContentProvider和数据库的创建和使用


    contentprovider的创建主要是分享应用的数据库的数据,创建主要可分为4步:

    1、创建数据库(注意即使创建了数据库类,只有在调用了sqLiteOpenHelper.getWritableDatabase(),数据库才会创建,而在清单文件里配置了provider,一开始就会加载,因此在provider的onCreate()方法里调用这个函数创建数据库。

    2、创建类继承contentProvider,在里面定义数据库的authority与后面mainfest里面的一致,代表content的主机名,相当于数据库地址,并且定义表的信息和uri的适配器,并添加uri到适配器中,当然这些静态常量也可以另外定义一个MetaData类来存储。

    3、在mainfest 注册provider,主要包括contentProvder的name和authority属性,demo中都是定义为包名+contentprovider类。

    4、在activity中利用getContentReceiver来得到contentReceiver对象操作数据库。

    下面根据以上步骤展示下代码:

    1、数据库构建

    package com.example.user.mcontentproviderdemo;
    
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    /**
     * Created by user on 2016/10/17.
     */
    public class MyDatabace extends SQLiteOpenHelper {
        final static String DATABACE_NAME ="MyFriends";
        final static int DATABACE_VISION =1;
    
        private String CREATE_FRIEND = "create table friends( _id integer primary key autoincrement, " +
                "name text not null, mobile text not null)";//
    
        public MyDatabace(Context context) {
    
            super(context, DATABACE_NAME, null, DATABACE_VISION);
    
        }
    
        @Override
        public void onCreate(SQLiteDatabase db)
        {
    
            db.execSQL(CREATE_FRIEND);
    
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
    
        }
    }
    

     2 contentprovider类的构建:

    package com.example.user.mcontentproviderdemo;
    
    import android.content.ContentProvider;
    import android.content.ContentValues;
    import android.content.UriMatcher;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.net.Uri;
    import android.provider.ContactsContract;
    import android.support.annotation.Nullable;
    
    import java.io.File;
    
    /**
     * Created by user on 2016/10/18.
     */
    public class MyContentProvider extends ContentProvider{
        //要共享的数据库
        private  static SQLiteOpenHelper sqLiteOpenHelper;
    
        public final  static  String AUTHORITY = "com.example.user.mcontentproviderdemo.MyContentProvider";
    
        //**********************为每个表定义变量信息,例子中就一个friend表***********************
        //*****************friends表**************************************//
        public final  static  String FRIENDS_TABLE ="friends";//表名
        //friends表的列明
        public final  static String FRIENDS_ID = "_id";
        public final  static String FRIENDS_NAME = "name";
        public final  static String FRIENDS_MOBILE = "mobile";
        public final static int  ALL_FRIENDS = 100; //当uri匹配是整个表格时候得返回值
        public  final  static  int ONE_FRIENDS = 1 ;//当uri匹配是整个表格的某一条目时候返回值
        public final static  String DEFAULT_SORT_ORDER = FRIENDS_ID+" desc";//定义默认排序
    
        //getType会用到的返回的类型
        private final  static  String ITEM_FRIENDS_TABLE_MIME = "vnd.android.cursor.item/vnd.com.example.user.mcontentproviderdemo.friends";
        private final  static  String ALL_FRIENDS_TABLE_MIME = "vnd.android.cursor.dir/vnd.com.example.user.mcontentproviderdemo.friends";
    
    
    
        private static final UriMatcher sUriMatcher;
        static {
    
            //初始化匹配器
            sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
            //  为friends表添加匹配的uri,当匹配时返回后面的整数值
            sUriMatcher.addURI(AUTHORITY , File.separator+FRIENDS_TABLE , ALL_FRIENDS);
            sUriMatcher.addURI(AUTHORITY , File.separator+FRIENDS_TABLE+"/*",ONE_FRIENDS);
    
        }
    
    
        @Override
        public boolean onCreate() {
            sqLiteOpenHelper = new MyDatabace(getContext());
            SQLiteDatabase db = sqLiteOpenHelper.getWritableDatabase();
            db.close();
            return false;
        }
    
        @Nullable
        @Override
        public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    
            Cursor cursor = null;
            SQLiteDatabase db=sqLiteOpenHelper.getWritableDatabase();
            cursor=db.query("friends", projection, selection, selectionArgs, null, null ,null );//DEFAULT_SORT_ORDER
            return cursor;
        }
    
        @Nullable
        @Override
        public String getType(Uri uri) {
            switch (sUriMatcher.match(uri))
            {
                case ALL_FRIENDS:
                    return ALL_FRIENDS_TABLE_MIME;
                case ONE_FRIENDS:
                    return ITEM_FRIENDS_TABLE_MIME;
                default:
                    return "error";
            }
    
        }
    
        @Nullable
        @Override
        public Uri insert(Uri uri, ContentValues values) {
            switch (sUriMatcher.match(uri))
            {
                case ALL_FRIENDS:
                    System.out.println("匹配成功");
                    SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getWritableDatabase();
                    sqLiteDatabase.insert("friends" , null ,values);
                    sqLiteDatabase.close();
    
                default:
                   break;
    
            }
            return null;
        }
    
        @Override
        public int delete(Uri uri, String selection, String[] selectionArgs) {
            return 0;
        }
    
        @Override
        public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
            return 0;
        }
    }
    

      3、配置文件中注册:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.user.mcontentproviderdemo">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <provider android:name="com.example.user.mcontentproviderdemo.MyContentProvider"
                android:authorities="com.example.user.mcontentproviderdemo.MyContentProvider"
                >
            </provider>
    
        </application>
    
    </manifest>
    

      4 在activity中使用:

    package com.example.user.mcontentproviderdemo;
    
    import android.content.ContentProvider;
    import android.content.ContentResolver;
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.net.Uri;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import java.net.URI;
    
    public class MainActivity extends AppCompatActivity {
    
        Uri uri = Uri.parse("content://"+ MyContentProvider.AUTHORITY+"/"+MyContentProvider.FRIENDS_TABLE);
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    //        ******************************插入*********************************
            ContentValues contentValues = new ContentValues();
            //id 在数据库是主键且自增长,所有可以不添加,当添加时候若数据库内是唯一的就会添加进数据库,若不是就不会插入此条
    //        contentValues.put(MyContentProvider.FRIENDS_ID,111);
            contentValues.put(MyContentProvider.FRIENDS_NAME , "db");
            contentValues.put(MyContentProvider.FRIENDS_MOBILE , "1356076");
            Uri uri2 =getContentResolver().insert(uri,contentValues);
    //        System.out.println(uri2.toString());
    
    //        ******************************查询*********************************
            Cursor cursor = getContentResolver().query(uri , null , null , null ,null);//new String[]{"name"}
            //遍历cursor
            while(cursor.moveToNext())
            {
                Bundle bundle = cursor.getExtras();
                String name =  cursor.getString(cursor.getColumnIndex(MyContentProvider.FRIENDS_NAME));
                String mobile =  cursor.getString(cursor.getColumnIndex(MyContentProvider.FRIENDS_MOBILE));
                int id =  cursor.getInt(cursor.getColumnIndex(MyContentProvider.FRIENDS_ID ));
                System.out.println("id:"+id+"   name:" + name + "   mobile:"+mobile);
            }
    
    
        }
    }
    

      

  • 相关阅读:
    如何快速发现网站恶意镜像与网页劫持?
    最牛「CSRF防护」,带你进入大虾们的圈子!
    安全无小事:如何给企业用户数据上把锁?
    PHP 7 探针的安装与测试
    如何使用 Docker、ECS、Terraform 重建基础架构?
    应用安全技术趋势之 Top 5
    第77节:Java中的事务和数据库连接池和DBUtiles
    第76节:Java中的基础知识
    第76节:Java中的基础知识
    第75节:Java的中的JSP,EL和JSTL
  • 原文地址:https://www.cnblogs.com/bokeofzp/p/5975564.html
Copyright © 2020-2023  润新知