Android基础学习之Provider(内容提供器)

Provider是Android四大组件之一,是一种数据共享机制(封装数据的接口规范)。是一个数据库的代理,实现跨应用间的数据共享,类似于window服务本身不负责启动和关闭,多个应用可同时访问统一provider。

主要类:
ContentProvider 类
ContentProvider 对象将程序内部数据向其他程序公开
ContentResolver 类
其他程序通过ContentResolver 对象对程序内部数据进行CRUD操作

ContentProvider 分类:
1.使用别人的provider 比如电话本,短信,媒体 这些数据系统底层使用xxx.db数据库封装为ContentProvider 接口
2.应用创建的provider 程序员自定义的,可提供给别人使用

如何定义自己的provider
步骤:
1.继承ContentProvider 定义子类
2.重写6个方法(所有方法都需要uri,每个ContentProvider 都提供对外公共uri) ContentProvider 将共享数据定义为uri

public class MenusProvider extends ContentProvider{

    @Override
    public boolean onCreate() {
        // 底层数据库初始化
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        return null;
    }

    @Override //要实现该方法必须完成
    //1.定义MIME类型
    //2.定义URI字符串
    //3.用urimather建立code和uri映射
    //4.用code来映射不同MIEM类型    
    public String getType(Uri uri) {
        // 返回MIME类型,一般用静态块来完成
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        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;
    }
}

uri代表地址,解决如何表示数据的问题.

3.声明CONTENT_URI公共的静态常量,实现UriMathcer的绑定
当自定义provider需要告诉使用ContentProvider 的人用到那些uri
UriMatcher类 将uri和MIME绑定的
ContentUris类 将uri解析/生成

4.实现provider底层封装到sqlite框架中.
4.1 onCreat() 初始化数据库 SQLiteOpenHelper辅助类
4.2 provider重写提供CRUD操作方法,如何使用uri

如:
content://myfs.pub.menusprovider/menus/2
list={“menus”,”2”}

5.注册provider,在AndroidManifest.xml文件< application>< /application>标签中(四大组件都需要注册)

<provider 
            android:name="com.robin.myprovider.MenusProvider"
            --Provider子类全名 -->
            android:authorities="myfs.pub.menusprovider" 
            
            android:exported="true"
            
 >< /provider>

6.测试provider
本地测试provider
远程测试provider

报错:
Installation error: INSTALL_FAILED_CONFLICTING_PROVIDER
表示系统中已经有同名的provider,调试时卸载重装即可。

使用->观察者模式
作用:监听ContentProvider 数据改变
ContentObserver 类
当ContentProvider 共享出来后,有时应用需要实时获得ContentProvider 共享数据的变化需要利用ContentObserver对象来实现。

实现步骤:
1.provider端的CRUD操作改变数据时调用resolver. notifyChange()方法
2.使用provider端要注册ContentObserver 对象
2.1 定义ContentObserver 子类重写onChange(boolean selfChange)方法
2.2 构造子类对象并注册给使用provider端的ContentResolver对象

如:cr.registerContentObserver(Menus.CONTENT_URI, notifyForDescendents, observer);
参数:
Menus.CONTENT_URI:监听CP的uri –> content://authority/menus
notifyForDescendents:true 表示该uri下所有的数据变化都监听
observer:false 表示只是监听uri数据变化

示例:
1.定义数据bean类
文件名Menus.java

package com.ql.providerdemo;

import android.net.Uri;

/**
 * 定义provider需要的相关数据  MIME类型
 * @author qinlang
 *
 */
public class Menus {
    // 以下定义provider的MIME类型常量
    public static final String MIME_DIR_PREFIX = "vnd.android.cursor.dir";// MIME类型 多条 
    public static final String MIME_ITEM_PREFIX = "vnd.android.cursor.item";// 单条
    //以上两条为android规定的
    public static final String MIME_ITEM = "vnd.pub.menus";// 自定义MIME类型字符串
    // 将固定前缀+自定义字符串生成两个类型
    public static final String MIME_TYPE_SINGLE = MIME_ITEM_PREFIX + "/"
            + MIME_ITEM;
    public static final String MIME_TYPE_MULTIPLE = MIME_DIR_PREFIX + "/"
            + MIME_ITEM;

    // 用来定义uri常量 content:////..../id
    public static final String AUTHORITY = "myfs.pub.menusprovider";// 授权者 表示用哪个provider,要跟清单文件中一致
    public static final String PATH_SINGLE = "menus/#"; // (menus:数据库表名)路径下单条记录 #代表数字id
    public static final String PATH_MULTIPLE = "menus";// 路径下多条记录 数据库将对应表名
    public static final String PATH_MULTIPLE_NAME = "menus/*"; // *代表文本 例如按名称访问等

    // 组合成所需要的uri字符串
    public static final String CONTENT_URI_STRING = "content://" + AUTHORITY
            + "/" + PATH_MULTIPLE;
    // 将uri字符串转换为uri对象
    public static final Uri CONTENT_URI = Uri.parse(CONTENT_URI_STRING);
    // 以上就完成自定义provider所需的uri和MIME类型的定义

    // 涉及sqlite底层实现的内容
    public static final String CREAT_TABLE = "create table menus(id integer primary key autoincrement ,name varchar(50),price integer)";
    public static final String DBNAME = "pub.db";//数据库名
    public static final String TABLENAME = "menus";//表名
    public static final int DB_VER = 1;//数据库版本,用于升级用

    //常量字符串,对应数据库中的字段
    public static final String KEY_ID = "id";
    public static final String KEY_NAME = "name";
    public static final String KEY_PRICE = "price";

    public static final String[] COLUNMS = { KEY_ID, KEY_NAME, KEY_PRICE };

    private int id;
    private String name;
    private int price;

    public Menus() {
    }

    public Menus(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "id:" + id + " | name:" + name + " | price:" + price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}

2.创建ContentProvider的子类,内容提供类
文件名:MenusProvider.java

package com.ql.providerdemo;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class MenusProvider extends ContentProvider {
    // 构造一个matcher对象
    private static final UriMatcher sURIMatcher = new UriMatcher(
            UriMatcher.NO_MATCH);

    // 定义code用来找对对应各种MIME类型的编码
    private static final int MULTIPLE_MENUS = 1;
    private static final int SINGLE_MENUS = 2;

    // 静态块,在类加载时执行一次,将uri和code绑定起来,以便解析
    static {
        sURIMatcher.addURI(Menus.AUTHORITY, Menus.PATH_MULTIPLE, MULTIPLE_MENUS);
        sURIMatcher.addURI(Menus.AUTHORITY, Menus.PATH_SINGLE, SINGLE_MENUS);
    }

    //数据库帮助类,用于创建表
    static class DBOpenHelper extends SQLiteOpenHelper {

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

        @Override
        // 用db对象来创建表
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(Menus.CREAT_TABLE);
        }

        @Override
        //表的更新
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("drop table if exists " + Menus.TABLENAME);
            db.execSQL(Menus.CREAT_TABLE);
        }
    }

    private SQLiteDatabase sqdb;
    private DBOpenHelper helper;

    @Override
    public boolean onCreate() {
        Context context = getContext();//得到context对象
        helper = new DBOpenHelper(context, Menus.DBNAME, null, Menus.DB_VER);//实例化数据库帮助类对象
        sqdb = helper.getWritableDatabase();//得到数据库
        if (sqdb == null) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    /**
     * 数据查询
     */
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(Menus.TABLENAME);
        switch (sURIMatcher.match(uri)) {
        case SINGLE_MENUS:
            qb.appendWhere(Menus.KEY_ID + "=" + uri.getPathSegments().get(1));
            break;
        case MULTIPLE_MENUS:
            break;
        default:
            break;
        }
        Cursor cursor = qb.query(sqdb, projection, selection, selectionArgs,
                null, null, sortOrder);
        return cursor;
    }

    @Override
    /**
     * 得到MIME类型
     */
    public String getType(Uri uri) {
        // 返回uri对应的MIME类型
        int match = sURIMatcher.match(uri);
        switch (match) {
        case MULTIPLE_MENUS:
            return Menus.MIME_TYPE_MULTIPLE;
        case SINGLE_MENUS:
            return Menus.MIME_TYPE_SINGLE;
        default:
            throw new IllegalArgumentException("Unknown uri:" + uri);
        }
    }

    @Override
    /**
     * 插入操作
     */
    public Uri insert(Uri uri, ContentValues values) {
        long id = sqdb.insert(Menus.TABLENAME, null, values);
        if (id > 0) {
            Uri newUri = ContentUris.withAppendedId(uri, id);
            return newUri;
        } else {
            throw new SQLException("fail to insert row into :" + uri);
        }
    }

    @Override
    /**
     * 删除操作
     */
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int result = -1;
        switch (sURIMatcher.match(uri)) {
        case SINGLE_MENUS:
            String id = uri.getPathSegments().get(1);
            result = sqdb.delete(Menus.TABLENAME, Menus.KEY_ID + "=" + id,
                    selectionArgs);

            break;
        case MULTIPLE_MENUS:
            result = sqdb.delete(Menus.TABLENAME, selection, selectionArgs);

        default:
            throw new IllegalArgumentException("Unknown uri:" + uri);
        }
        return result;
    }

    @Override
    /**
     * 更新操作
     */
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int count = 0;
        switch (sURIMatcher.match(uri)) {
        case SINGLE_MENUS:
            String id = uri.getPathSegments().get(1);// 从uri取出id字符串
            count = sqdb.update(Menus.TABLENAME, values, Menus.KEY_ID + "="
                    + id, selectionArgs);
            break;
        case MULTIPLE_MENUS:
            count = sqdb.update(Menus.TABLENAME, values, selection,
                    selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown uri:" + uri);
        }
        return count;
    }

}

3.在清单文件中添加权限和注册ContentProvider子类


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ql.providerdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="19" />

    
    <permission 
        android:name="com.ql.provider.READ"
        android:label="@string/app_name"
        android:protectionLevel="normal"
        >permission>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <provider
            android:name="com.ql.providerdemo.MenusProvider"
            android:authorities="myfs.pub.menusprovider"
            android:exported="true"
            android:readPermission="com.ql.provider.READ" >
            
            
        provider>

        <activity
            android:name="com.ql.providerdemo.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>

4.用于测试的Activity
4.1布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${packageName}.${activityClass}" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加" />

        <EditText
            android:id="@+id/txt_addName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="输入名称" >

            <requestFocus />
        EditText>

        <EditText
            android:id="@+id/txt_addPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="输入单价" />
    LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btn_delById"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按ID删除" />

        <EditText
            android:id="@+id/txt_delId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="输入删除的ID" />

        <Button
            android:id="@+id/btn_delAll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除全部" />
    LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btn_queryById"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按ID查询" />

        <EditText
            android:id="@+id/txt_queryId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="输入查询的ID" />

        <Button
            android:id="@+id/btn_queryAll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查询全部" />
    LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btn_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="修改" />

        <EditText
            android:id="@+id/txt_updateId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="输入要修改的ID" />

        <EditText
            android:id="@+id/txt_updataName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="名称" />

        <EditText
            android:id="@+id/txt_updataPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="单价" />
    LinearLayout>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    ListView>

LinearLayout>

4.2java代码

public class MainActivity extends Activity implements OnClickListener {
    private static final String TAG = "ql debug";
    private ContentResolver cr;

    private Button btn_add;
    private Button btn_delAll;
    private Button btn_delById;
    private Button btn_update;
    private Button btn_queryAll;
    private Button btn_queryById;
    private ListView listView;
    private EditText txt_addName;
    private EditText txt_addPrice;
    private EditText txt_delId;
    private EditText txt_queryId;
    private EditText txt_updateId;
    private EditText txt_updataName;
    private EditText txt_updataPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listView = (ListView) findViewById(R.id.listView1);

        txt_addName = (EditText) findViewById(R.id.txt_addName);
        txt_addPrice = (EditText) findViewById(R.id.txt_addPrice);
        txt_delId = (EditText) findViewById(R.id.txt_delId);
        txt_queryId = (EditText) findViewById(R.id.txt_queryId);
        txt_updateId = (EditText) findViewById(R.id.txt_updateId);
        txt_updataName = (EditText) findViewById(R.id.txt_updataName);
        txt_updataPrice = (EditText) findViewById(R.id.txt_updataPrice);

        btn_add = (Button) findViewById(R.id.btn_add);
        btn_delAll = (Button) findViewById(R.id.btn_delAll);
        btn_delById = (Button) findViewById(R.id.btn_delById);
        btn_update = (Button) findViewById(R.id.btn_update);
        btn_queryAll = (Button) findViewById(R.id.btn_queryAll);
        btn_queryById = (Button) findViewById(R.id.btn_queryById);
        btn_add.setOnClickListener(this);
        btn_delAll.setOnClickListener(this);
        btn_delById.setOnClickListener(this);
        btn_queryAll.setOnClickListener(this);
        btn_queryById.setOnClickListener(this);
        btn_update.setOnClickListener(this);

        cr = getContentResolver(); //实例化ContentResolver 对象
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_add:
            String name = txt_addName.getText().toString().trim();
            String s_price = txt_addPrice.getText().toString().trim();
            if ("".equals(name) || "".equals(s_price)) {
                Toast.makeText(this, "输入不可为空!", Toast.LENGTH_SHORT).show();
            }else {
                int price = Integer.valueOf(s_price);
                addData(name, price);
            }
            break;
        case R.id.btn_delAll:
            delAllData();
            break;
        case R.id.btn_delById:
            String s_del_id = txt_delId.getText().toString().trim();
            if (!"".equals(s_del_id)) {
                int del_id = Integer.valueOf(s_del_id);
                delById(del_id);
            }
            break;
        case R.id.btn_update:
            String s_updata_id = txt_updateId.getText().toString().trim();
            String updata_name = txt_updataName.getText().toString().trim();
            String s_updata_price = txt_updataPrice.getText().toString().trim();
            if (!"".equals(s_updata_id)) {
                int updata_id = Integer.valueOf(s_updata_id);
                if ("".equals(updata_name) && "".equals(s_updata_price)) {
                    Toast.makeText(this, "没有项进行修改!", Toast.LENGTH_SHORT).show();
                }else {
                    updateData(updata_id, updata_name, s_updata_price);
                }
            }
            break;
        case R.id.btn_queryAll:
            queryAll();
            break;
        case R.id.btn_queryById:
            String s_query_id = txt_queryId.getText().toString().trim();
            if (!"".equals(s_query_id)) {
                int query_id = Integer.valueOf(s_query_id);
                queryById(query_id);
            }
            break;

        default:
            break;
        }
    }

    private void updateData(int id, String name, String price) {
        Menus mm = new Menus();
        if (!"".equals(name)) {
            mm.setName(name);
        }
        if (!"".equals(price)) {
            int i_price = Integer.valueOf(price);
            mm.setPrice(i_price);
        }
        Uri uri = Uri.parse(Menus.CONTENT_URI + "/" + id);// 定义要操作的uri
        ContentValues values = new ContentValues();
        values.put(Menus.KEY_NAME, mm.getName());
        values.put(Menus.KEY_PRICE, mm.getPrice());
        int result = cr.update(uri, values, null, null);
    }

    private void queryById(int id) {
        Uri uri = Uri.parse(Menus.CONTENT_URI + "/" + id);
        Cursor cursor = cr.query(uri, Menus.COLUNMS, null, null, null);
        ArrayList arr = new ArrayList();
        arr.add("ID\tNAME\tPRICE");
//      Log.e(TAG, "==单条查询==");
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                String s = cursor.getString(0) + "\t\t" + cursor.getString(1)
                        + "\t\t" + cursor.getString(2);
//              Log.e(TAG, s);
                arr.add(s);
            }
        }
        listView.setAdapter(new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, arr));
    }

    private void queryAll() {
        Cursor cursor = cr.query(Menus.CONTENT_URI, Menus.COLUNMS, null, null,
                null);
        ArrayList arr = new ArrayList();
        arr.add("ID\tNAME\tPRICE");
//      Log.e(TAG, "==查询所有==");
        Log.d(TAG, "Is null:" + String.valueOf(cursor == null ? true : false));
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    String s = cursor.getString(0) + "\t\t" + cursor.getString(1)
                            + "\t\t" + cursor.getString(2);
                    arr.add(s);
//                  Log.e(TAG, s);
                } while (cursor.moveToNext());
            }
        }
        listView.setAdapter(new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, arr));
    }

    private void delById(int id) {
        Uri uri = Uri.parse(Menus.CONTENT_URI + "/" + id);// 定义要操作的uri
        int result = cr.delete(uri, null, null);
        Toast.makeText(this, result + "项删除完成!", Toast.LENGTH_SHORT).show();
    }

    private void delAllData() {
        int result = cr.delete(Menus.CONTENT_URI, null, null);
        Toast.makeText(this, result + "项删除完成!", Toast.LENGTH_SHORT).show();
    }

    private void addData(String name, int price) {

        Menus[] mms = { new Menus(name, price)};

        for (Menus m : mms) {
            ContentValues cv = new ContentValues();
            cv.put(Menus.KEY_NAME, m.getName());
            cv.put(Menus.KEY_PRICE, m.getPrice());
            Uri uri = cr.insert(Menus.CONTENT_URI, cv); // 最终
                                                        // cp.insert(url,values)
            Log.d(TAG, "add data:" + uri.toString());
        }
    }
}

测试示例:
用于测试以上程序的内容提供者。
布局和bean一样,清单文件只添加了数据提供者给的读取权限


<uses-permission android:name="com.ql.provider.READ" />

活动添加了内容观察者对象

public class MainActivity extends Activity implements OnClickListener {
    private static final String TAG = "ql debug";
    private ContentResolver cr;

    private Button btn_add;
    private Button btn_delAll;
    private Button btn_delById;
    private Button btn_update;
    private Button btn_queryAll;
    private Button btn_queryById;
    private ListView listView;
    private EditText txt_addName;
    private EditText txt_addPrice;
    private EditText txt_delId;
    private EditText txt_queryId;
    private EditText txt_updateId;
    private EditText txt_updataName;
    private EditText txt_updataPrice;

    /**
     * 内容提供器观察者对象
     * @author qinlang
     *
     */
    class MyContentObserver extends ContentObserver{

        public MyContentObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
//          Log.e(TAG, "remote observer find content provider data change!!!");
            queryAll();
        }
    }

    MyContentObserver observer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listView = (ListView) findViewById(R.id.listView1);

        txt_addName = (EditText) findViewById(R.id.txt_addName);
        txt_addPrice = (EditText) findViewById(R.id.txt_addPrice);
        txt_delId = (EditText) findViewById(R.id.txt_delId);
        txt_queryId = (EditText) findViewById(R.id.txt_queryId);
        txt_updateId = (EditText) findViewById(R.id.txt_updateId);
        txt_updataName = (EditText) findViewById(R.id.txt_updataName);
        txt_updataPrice = (EditText) findViewById(R.id.txt_updataPrice);

        btn_add = (Button) findViewById(R.id.btn_add);
        btn_delAll = (Button) findViewById(R.id.btn_delAll);
        btn_delById = (Button) findViewById(R.id.btn_delById);
        btn_update = (Button) findViewById(R.id.btn_update);
        btn_queryAll = (Button) findViewById(R.id.btn_queryAll);
        btn_queryById = (Button) findViewById(R.id.btn_queryById);
        btn_add.setOnClickListener(this);
        btn_delAll.setOnClickListener(this);
        btn_delById.setOnClickListener(this);
        btn_queryAll.setOnClickListener(this);
        btn_queryById.setOnClickListener(this);
        btn_update.setOnClickListener(this);

        observer=new MyContentObserver(new Handler());
        cr = getContentResolver();
        //注册内容提供器观察者对象
        cr.registerContentObserver(Menus.CONTENT_URI, true, observer);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_add:
            String name = txt_addName.getText().toString().trim();
            String s_price = txt_addPrice.getText().toString().trim();
            if ("".equals(name) || "".equals(s_price)) {
                Toast.makeText(this, "输入不可为空!", Toast.LENGTH_SHORT).show();
            }else {
                int price = Integer.valueOf(s_price);
                addData(name, price);
            }
            break;
        case R.id.btn_delAll:
            delAllData();
            break;
        case R.id.btn_delById:
            String s_del_id = txt_delId.getText().toString().trim();
            if (!"".equals(s_del_id)) {
                int del_id = Integer.valueOf(s_del_id);
                delById(del_id);
            }
            break;
        case R.id.btn_update:
            String s_updata_id = txt_updateId.getText().toString().trim();
            String updata_name = txt_updataName.getText().toString().trim();
            String s_updata_price = txt_updataPrice.getText().toString().trim();
            if (!"".equals(s_updata_id)) {
                int updata_id = Integer.valueOf(s_updata_id);
                if ("".equals(updata_name) && "".equals(s_updata_price)) {
                    Toast.makeText(this, "没有项进行修改!", Toast.LENGTH_SHORT).show();
                }else {
                    updateData(updata_id, updata_name, s_updata_price);
                }
            }
            break;
        case R.id.btn_queryAll:
            queryAll();
            break;
        case R.id.btn_queryById:
            String s_query_id = txt_queryId.getText().toString().trim();
            if (!"".equals(s_query_id)) {
                int query_id = Integer.valueOf(s_query_id);
                queryById(query_id);
            }
            break;

        default:
            break;
        }
    }

    private void updateData(int id, String name, String price) {
        Menus mm = new Menus();
        ContentValues values = new ContentValues();
        if (!"".equals(name)) {
            mm.setName(name);
            values.put(Menus.KEY_NAME, mm.getName());
        }
        if (!"".equals(price)) {
            int i_price = Integer.valueOf(price);
            mm.setPrice(i_price);
            values.put(Menus.KEY_PRICE, mm.getPrice());
        }
        Uri uri = Uri.parse(Menus.CONTENT_URI + "/" + id);// 定义要操作的uri

        int result = cr.update(uri, values, null, null);
    }

    private void queryById(int id) {
        Uri uri = Uri.parse(Menus.CONTENT_URI + "/" + id);
        Cursor cursor = cr.query(uri, Menus.COLUNMS, null, null, null);
        ArrayList arr = new ArrayList();
        arr.add("ID\tNAME\tPRICE");
        Log.e(TAG, "==单条查询==");
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                String s = cursor.getString(0) + "\t\t" + cursor.getString(1)
                        + "\t\t" + cursor.getString(2);
//              Log.e(TAG, s);
                arr.add(s);
            }
        }
        listView.setAdapter(new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, arr));
    }

    private void queryAll() {
        Cursor cursor = cr.query(Menus.CONTENT_URI, Menus.COLUNMS, null, null,
                null);
        ArrayList arr = new ArrayList();
        arr.add("ID\tNAME\tPRICE");
        Log.e(TAG, "==查询所有==");
        Log.d(TAG, "Is null:" + String.valueOf(cursor == null ? true : false));
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    String s = cursor.getString(0) + "\t\t" + cursor.getString(1)
                            + "\t\t" + cursor.getString(2);
                    arr.add(s);
//                  Log.e(TAG, s);
                } while (cursor.moveToNext());
            }
        }
        listView.setAdapter(new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, arr));
    }

    private void delById(int id) {
        Uri uri = Uri.parse(Menus.CONTENT_URI + "/" + id);// 定义要操作的uri
        int result = cr.delete(uri, null, null);
        Toast.makeText(this, result + "项删除完成!", Toast.LENGTH_SHORT).show();
    }

    private void delAllData() {
        int result = cr.delete(Menus.CONTENT_URI, null, null);
        Toast.makeText(this, result + "项删除完成!", Toast.LENGTH_SHORT).show();
    }

    private void addData(String name, int price) {

        Menus[] mms = { new Menus(name, price)};

        for (Menus m : mms) {
            ContentValues cv = new ContentValues();
            cv.put(Menus.KEY_NAME, m.getName());
            cv.put(Menus.KEY_PRICE, m.getPrice());
            Uri uri = cr.insert(Menus.CONTENT_URI, cv); // 最终
                                                        // cp.insert(url,values)
            Log.d(TAG, "add data:" + uri.toString());
        }
    }
}

你可能感兴趣的:(Android基础)