Android ContentProvider

1.创建一个布局文件

2. 创建一个应用程序作为Provider

3.新建一个类继承ContentProvider重写它的五个方法

public class MyContentProvide extends ContentProvider {

    private SQLiteDatabase db;
    private UriMatcher uriMatcher;

    @Override
    public boolean onCreate() {
        DbHelper dbHelper = new DbHelper(getContext());
        db = dbHelper.getWritableDatabase();
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        //增加uri
        uriMatcher.addURI("com.zking.mycontentprovide","person",1);
        uriMatcher.addURI("com.zking.mycontentprovide","person/#",2);
        return false;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        //匹配
        int type = uriMatcher.match(uri);
        switch (type){
            case 1:
                return db.query(false,"person",projection,selection,selectionArgs,null,null,sortOrder,null);
            case 2:
                long id = ContentUris.parseId(uri);
                return db.query(false,"person",projection,"_id=?",new String[]{id + ""},null,null,sortOrder,null);
        }
        return null;
    }

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

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        db.insert("person",null,values);
        return uri;
    }

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

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return db.update("person",values,selection,selectionArgs);
    }
}
然后在清单文件配置

4.创建一个应用程序作为Resolver
 
public class MainActivity extends AppCompatActivity {

    private String contentUrl = "content://com.zking.mycontentprovide";

    private ContentResolver cr;
    private ListView lv_main_list;
    private List<Person> persons = new ArrayList<>();
    private MyAdapter myAdapter;
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cr = getContentResolver();
        initViews();
    }

    private void initViews() {
        lv_main_list = (ListView) findViewById(R.id.lv_main_list);
        persons = getPersons(null);
        myAdapter = new MyAdapter();
        lv_main_list.setAdapter(myAdapter);
        lv_main_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, final long id) {
                LinearLayout ll = new LinearLayout(MainActivity.this);
                ll.setOrientation(LinearLayout.VERTICAL);
                ll.setBackgroundColor(Color.argb(255,255,255,255));
                TextView tv_edit = new TextViewUtil(MainActivity.this).setText("编辑").toTextView();
                TextView tv_delete = new TextViewUtil(MainActivity.this).setText("删除").toTextView();
                ll.addView(tv_edit);
                tv_edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final Person person = persons.get(position);
                        LinearLayout linearLayout = new LinearLayout(MainActivity.this);
                        linearLayout.setOrientation(LinearLayout.VERTICAL);
                        final EditText et_id = new EditTextUtil(MainActivity.this,LinearLayout.LayoutParams.class,EditTextUtil.WIDTH_MATH_AND_HEGTI_WRAP).setText(person.getId()+ "").setHint("用户id").toEditText();
                        et_id.setEnabled(false);
                        final EditText et_name = new EditTextUtil(MainActivity.this,LinearLayout.LayoutParams.class,EditTextUtil.WIDTH_MATH_AND_HEGTI_WRAP).setText(person.getName()+ "").setHint("用户姓名").toEditText();
                        final EditText et_age = new EditTextUtil(MainActivity.this,LinearLayout.LayoutParams.class,EditTextUtil.WIDTH_MATH_AND_HEGTI_WRAP).setText(person.getAge()+ "").setHint("用户年龄").toEditText();
                        linearLayout.addView(et_id);
                        linearLayout.addView(et_name);
                        linearLayout.addView(et_age);
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setMessage("修改");
                        builder.setView(linearLayout);
                        builder.setNeutralButton("修改", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ContentValues contentValues = new ContentValues();
                                contentValues.put("name",et_name.getText().toString());
                                contentValues.put("age",et_age.getText().toString());
                                cr.update(Uri.parse(contentUrl),contentValues,"_id=?",new String[]{et_id.getText().toString()});
                                persons = getPersons(null);
                                myAdapter.notifyDataSetChanged();
                            }
                        });
                        builder.setPositiveButton("取消",null);
                        builder.show();
                        popupWindow.dismiss();
                    }
                });
                ll.addView(tv_delete);
                tv_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("删除");
                        builder.setMessage("你确定删除吗");
                        builder.setNegativeButton("", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                cr.delete(Uri.parse(contentUrl),"_id=?",new String[]{persons.get(position).getId() + ""});
                                persons = getPersons(null);
                                myAdapter.notifyDataSetChanged();
                            }
                        });
                        builder.setPositiveButton("",null);
                        builder.show();
                        popupWindow.dismiss();
                    }
                });
                popupWindow = new PopupWindow(ll,300,300);
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(0,255,255,255)));
                popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
                popupWindow.setOutsideTouchable(false);
                popupWindow.setFocusable(true);
                popupWindow.showAsDropDown(view);
                return false;
            }
        });
    }

    public List<Person> getPersons(String id){
        List<Person> persons = new ArrayList<>();
        Uri uri = null;
        if (id != null){
            uri =  Uri.parse(contentUrl + "/person/" + id);
        }else {
            uri =  Uri.parse(contentUrl + "/person");

        }
        Cursor cursor =  cr.query(uri,null,null,null,null);
        while (cursor.moveToNext()){
            Person p = new Person();
            p.setId(cursor.getInt(0));
            p.setName(cursor.getString(1));
            p.setAge(cursor.getInt(2));
            persons.add(p);
        }
        return persons;
    }

    private class MyAdapter extends BaseAdapter{

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

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LinearLayout linearLayout = new LinearLayout(MainActivity.this);
            Person person = persons.get(position);
            TextView textView = getTextView();
            textView.setText(person.getId() + "");
            TextView textView1 = getTextView();
            textView1.setText(person.getName() + "");
            TextView textView2 = getTextView();
            textView2.setText(person.getAge() + "");
            linearLayout.addView(textView);
            linearLayout.addView(textView1);
            linearLayout.addView(textView2);
            return linearLayout;
        }

        private TextView getTextView(){
            TextView textView = new TextView(MainActivity.this);
            LinearLayout.LayoutParams l = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.WRAP_CONTENT);
            l.weight = 1;
            textView.setLayoutParams(l);
            return textView;
        }
    }

    public void query(View view){
        LinearLayout linearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        final EditText editText = new EditText(this);
        editText.setLayoutParams(lp);
        editText.setHint("请输入id");
        linearLayout.addView(editText);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("查询");
        builder.setView(linearLayout);
        builder.setNeutralButton("查询", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (!TextUtils.isEmpty(editText.getText().toString())){
                    persons = getPersons(editText.getText().toString());
                }else {
                    persons = getPersons(null);
                }
                myAdapter.notifyDataSetChanged();
            }
        });
        builder.setPositiveButton("取消",null);
        builder.show();
    }

    public void insert(View view){
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        final EditText et_name = new EditTextUtil(this,LinearLayout.LayoutParams.class,EditTextUtil.WIDTH_MATH_AND_HEGTI_WRAP).setHint("请输入用户名").toEditText();
        final EditText et_age = new EditTextUtil(this,LinearLayout.LayoutParams.class,EditTextUtil.WIDTH_MATH_AND_HEGTI_WRAP).setHint("请输入年龄").toEditText();
        et_age.setInputType(InputType.TYPE_CLASS_NUMBER);
        linearLayout.addView(et_name);
        linearLayout.addView(et_age);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("增加");
        builder.setView(linearLayout);
        builder.setNeutralButton("添加", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ContentValues contentValues = new ContentValues();
                contentValues.put("name",et_name.getText().toString());
                contentValues.put("age",et_age.getText().toString());
                cr.insert(Uri.parse(contentUrl),contentValues);
                persons = getPersons(null);
                myAdapter.notifyDataSetChanged();
            }
        });
        builder.setPositiveButton("取消",null);
        builder.show();
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值