Android:ContentProvider的基本方法以及ContentResolver的对Provider的简单增删改查

ContentProvider使我们Android四大组件之一,ContentProvider可以实现在应用程序之间共享数据.

下面是本人自己写的一个简单dome
当然也可以参考详细的博客,点击这里

目录

代码块

首先是ContentProvider的代码:


public class MyPersonProvider   extends ContentProvider {


    private SQLiteDatabase database;

    @Override
    public boolean onCreate() {
        database = new DbWrite().openDatabase(getContext());
        return false;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        return  database.query(false,"myblacklist",new String[]{" bid as _id","bname","bnumber"},selection,selectionArgs,null,null,sortOrder,null);
    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long id=  database.insert("myblacklist","bname",values);
        //通知所有监听这个数据库的观察者,数据发生改变。
        getContext().getContentResolver().notifyChange(uri,null);
        return ContentUris.withAppendedId(uri,id);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs)
    {
        return database.delete("myblacklist",selection,selectionArgs);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

        return  database.update("myblacklist",values,selection,selectionArgs);
    }
}

Provider清单文件:

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

    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />

    <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>

        <receiver android:name=".receiver.CallInterceptReceivec">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>

        <activity android:name=".InterceptActivity"></activity>


        <provider
            android:authorities="com.example.android_22_servicesblacklist.BLACKLIST"
            android:exported="true"
            android:name=".provider.MyPersonProvider">
        </provider>


    </application>

</manifest>

下面是内容访问者的代码:

public class MainActivity extends ListActivity {

    private ContentResolver resolver;
    private EditText name;
    private EditText number;
    private ListView listView;
    private PopupWindow popupWindow;
    private View popupView;
    private SimpleCursorAdapter simpleCursorAdapter;
    private Cursor cursor;
    private Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //得到布局文件中的listview
        listView = getListView();
        //得到访问者
        resolver = getContentResolver();

        //初始化数据
        getData();

        //listView的长按监听事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, final View view, int position, long id) {
                //弹出窗口进行修改或者删除的操作
                popupWindow.showAtLocation(findViewById(R.id.activity_main), Gravity.CENTER, 0, 0);
                TextView textView= (TextView) popupView.findViewById(R.id.tv_font_1);//修改
                final TextView bid= (TextView) view.findViewById(R.id.tv_item_list_id);//得到当前选中的id
                final TextView name= (TextView) view.findViewById(R.id.tv_item_list_name);//名字
                final TextView number= (TextView) view.findViewById(R.id.tv_item_list_number);//号码
                //修改数据
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //调用这个自定义的方法,执行不同操作
                        caoData(false,new MyblackList(Integer.parseInt(bid.getText().toString()),name.getText().toString(),number.getText().toString()));
                        popupWindow.dismiss();//关闭窗口
                    }
                });

                TextView textView2= (TextView) popupView.findViewById(R.id.tv_font_2);//删除

                textView2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        resolver.delete(uri,"bid=?",new String[]{bid.getText().toString()});
                        cursor= resolver.query(uri,null,null,null,null);
                        simpleCursorAdapter.changeCursor(cursor);
                        popupWindow.dismiss();//关闭窗口
                    }
                });
                return false;
            }
        });


    }



    public void getData(){
        //解析uri字符串拿到uri
        uri = Uri.parse("content://com.example.android_22_servicesblacklist.BLACKLIST");
        //通过访问者查询数据返回给cursor
        cursor = resolver.query(uri,null,null,null,null);
        simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.item_listview, cursor,new String[]{"_id" ,"bname","bnumber"},new int[]{R.id.tv_item_list_id,R.id.tv_item_list_name,R.id.tv_item_list_number});
        listView.setAdapter(simpleCursorAdapter);//设置适配器

        //得到窗口的一个布局文件
        popupView = getLayoutInflater().inflate(R.layout.layout_popupwindow, null);
        popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(),(Bitmap)null));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
//        popupWindow.setAnimationStyle(R.style.anim_menu_bottombar);//显示的动画效果
        popupWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                        && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });
    }



    public void addData(View view){
        caoData(true,null);
    }


    /**
     *
     * @param isAdd 是否为添加,否则为修改
     * @param myblackList 待修改的对象
     */
    public void caoData(final boolean isAdd, final MyblackList myblackList){
        //添加或修改的窗口
        View view1=  getLayoutInflater().inflate(R.layout.layout_resolver,null);
        name = (EditText) view1.findViewById(R.id.et_name);
        number = (EditText) view1.findViewById(R.id.et_number);
        //判断是不是为空 ,为空就是添加操作
        if(myblackList!=null){
            name.setText(myblackList.getBname());
            number.setText(myblackList.getBnumber());
        }
        AlertDialog.Builder dialog=new AlertDialog.Builder(this);
        final AlertDialog dialog1=dialog.create();
        dialog1.setTitle("信息");
        dialog1.setView(view1);
        //显示窗口
        dialog1.show();

        //得到保存按钮
        Button btn_save= (Button) view1.findViewById(R.id.btn_save);
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(number.getText().toString())){
                    Toast.makeText(MainActivity.this, "不能为空!", Toast.LENGTH_SHORT).show();
                }else{
                    ContentValues  values=new ContentValues();
                    if(isAdd){//为添加窗口
                        values.put("bname", name.getText()+"");
                        values.put("bnumber", number.getText()+"");
                        resolver.insert(uri,values);
                    }else{//为修改窗口
                        values.put("bname",name.getText()+"");
                        values.put("bnumber",number.getText()+"");
                        int result=   resolver.update(uri,values,"bid=?",new String[]{myblackList.getBid()+""});
                    }
                    cursor= resolver.query(uri,null,null,null,null);
                    //通知适配器 cursor发生改变
                    simpleCursorAdapter.changeCursor(cursor);
                    //关闭窗口
                    dialog1.dismiss();
                }
            }
        });

        //得到修改按钮
        Button btn_no= (Button) view1.findViewById(R.id.btn_no);
        btn_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });

    }


}

layout_resolver.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/et_name"
        android:hint="名字"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/et_number"
        android:hint="号码"
        />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/btn_save"
            android:layout_height="wrap_content"
            android:text="保存"
            />
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/btn_no"
            android:layout_height="wrap_content"
            android:text="取消"
            />
    </LinearLayout>
</LinearLayout>

layout_popupwindow.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="#55cccccc"
    android:layout_height="match_parent">



    <TextView
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="15dp"
    android:layout_marginBottom="15dp"
    android:text="修改信息"
        android:id="@+id/tv_font_1"
    android:textSize="14sp"
    />
    <View
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#cccccc"
        >
    </View>


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="15dp"
        android:text="删除信息"
        android:id="@+id/tv_font_2"
        android:textSize="16sp"
        />
    <View
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#cccccc"
        >
    </View>
</LinearLayout>

ContentResolver的界面,增加, listview展示,及popupwindow修改或删除

效果图如下:
这里写图片描述


这里写图片描述

源码下载地址:http://download.csdn.net/detail/james_lang/9748487

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值