Android开发之ContentProvider结合LoaderManager加载数据

ContentProvider作为Android的四大存储方式之一,有着广泛的应用性,它暴露了数据地址,可以让其他应用访问数据,可以用于存储图片、通讯录等信息,这篇博文将详细介绍ContentProvider、URIMatcher,LoaderManager,cursorAdapter的方法使用与介绍。使用ContentProvider的时候一定要注意在manifest清单文件中像Acticity文件一样,声明其属性。如图所示

        <provider android:name="com.example.loadermanagertest2.PersonContentProvider" android:authorities="com.example.loadermanagertest2.PersonContentProvider" android:exported="false">
            <!-- true表示可以被外部程序访问,此处不需要 -->
        </provider>

此外因为我们是用loadermanager来加载数据,MainAcitivity类要实现LoaderCallback接口。按照惯例我们还是看下谷歌官方文档对contentprovider的解释,ContentProvider管理一个结构化的数据集。它封装了数据,并提供定义数据安全机制。ContentProvider的标准接口实现多线程机制来连接数据,一般是用loaderManager异步加载数据。
MainActivity的代码:

package com.example.loadermanagertest2;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity implements LoaderCallbacks<Cursor>{
    private ListView listView;
    private Button button;
    private MyAdapter adapter;
    private LoaderManager loaderManager;

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

        listView = (ListView)findViewById(R.id.listView1);
        button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                ContentResolver resolver = getContentResolver();
                Uri uri = Uri.parse("content://com.example.loadermanagertest2." +
                        "PersonContentProvider/person");
                ContentValues values = new ContentValues();
                values.put("name", "tick");
                resolver.insert(uri, values);
                //通过内容提供者contentProvider插入数据后还需要调用loadermanager的restart方法更新一次UI
                loaderManager.restartLoader(0, null, MainActivity.this);
            }
        });
        //初始化loaderManager
        loaderManager = getLoaderManager();
        loaderManager.initLoader(0, null, this);
        //如果没有button及其响应事件,那么必须调用loaderManager.getLoader(0).onContentChanged();因为刚实例化的listview是没有数据的。作用类似于restartLoader
    }
    //下面是继承LoaderCallbacks必须调用的三个函数

    //是一个工厂方法,用来返回一个新的Loader
    //LoaderManager将会在它第一次创建Loader的时候调用该方法。
    //只会调用一次
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        CursorLoader loader = new CursorLoader(this);
        Uri uri = Uri.parse("content://com.example.loadermanagertest2." +
                "PersonContentProvider/person");
        loader.setUri(uri);
        loader.setProjection(new String[] { "name" });
        return loader;
    }

    //在Loader创建完毕的时候自动调用
    //每次数据源都有更新的时候,就会回调这个方法,然后update我们的ui了。
    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        List<String> list = new ArrayList<String>();
        while (data.moveToNext()) {
            String name = data.getString(data.getColumnIndex("name"));
            list.add(name);
        }
        adapter = new MyAdapter(this, list);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    //移除不再有用的数据
    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }
}

接下来就是MyAdapter和PersonContentProvider
MyAdapter.java

package com.example.loadermanagertest2;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {
    private List<String> list;
    private Context context;

    public MyAdapter(Context context, List<String> list){
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = null;
        if(convertView == null){
            textView = new TextView(context);
        }else {
            textView = (TextView) convertView;
        }
        textView.setTextSize(20);
        textView.setText(list.get(position));
        return textView;
    }
}

PersonContentProvider.java

package com.example.loadermanagertest2;

import android.content.ContentProvider;
import android.content.ContentResolver;
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;

//要在manifest文件中注册provider
public class PersonContentProvider extends ContentProvider {
    private MyOpenHelper helper;
    private static final UriMatcher matcher = new UriMatcher(
            UriMatcher.NO_MATCH);// 专门用来匹配URI的类
    private static final int PERSONS = 1;
    private static final int PERSON = 2;
    private ContentResolver resolver;
    static {
        //Add a URI to match, and the code to return when this URI is matched
        matcher.addURI("com.example.loadermanagertest2.PersonContentProvider",
                "person", PERSONS);
        matcher.addURI("com.example.loadermanagertest2.PersonContentProvider",
                "person/#", PERSON);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    // 当您需要匹配一个URI,调用匹配(URI),用来来建立一个查询,返回类型,插入或删除一行。
    @Override
    public String getType(Uri arg0) {
        int match = matcher.match(arg0);
        switch (match) {
        case PERSONS:
            return "vnd.android.cursor.dir/person";
        case PERSON:
            return "vnd.android.cursor.item/person";
        default:
            return null;
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase database = helper.getWritableDatabase();
        long id = database.insert("person", null, values);
        Uri rUri = ContentUris.withAppendedId(uri, id);
        resolver.notifyChange(rUri, null);//通知Loader已更新
        return rUri;
    }

    @Override
    public boolean onCreate() {
        helper = new MyOpenHelper(getContext());
        resolver = getContext().getContentResolver();
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        Cursor cursor = null;
        int flag = matcher.match(uri);
        SQLiteDatabase database = helper.getReadableDatabase();
        switch (flag) {
        case PERSONS:
            cursor=database.query("person", null, null, null,null, null, null);
            break;
        case PERSON:
            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;

        default:
            break;
        }
        cursor.setNotificationUri(resolver, uri);
        //Register to watch a content URI for changes.
        return cursor;
    }

    @Override
    public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
        return 0;
    }
}

最后就是MyOpenHelper和布局文件

package com.example.loadermanagertest2;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class MyOpenHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String PERSON_TABLE_NAME = "person";

    public MyOpenHelper(Context context) {
        super(context, PERSON_TABLE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("create table "
                + PERSON_TABLE_NAME
                + "(_id integer primary key autoincrement," +
                "name varchar(64))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

main.xml就比较简单

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/RelativeLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.loadermanagertest2.MainActivity" >

    <ListView  android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="200sp" >
    </ListView>

    <Button  android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/listView1" android:text="添加" />

</RelativeLayout>

文章转载自http://www.it165.net/pro/html/201403/11228.html

你可能感兴趣的:(Android开发之ContentProvider结合LoaderManager加载数据)