首页 > 学院 > 开发设计 > 正文

ContentProvider内容提供者的使用

2019-11-09 18:26:38
字体:
来源:转载
供稿:网友

ContentPRovider内容提供者

           ContentProvider是安卓四大组件之一,用来共享程序内的数据。当你需要把你的应用程序数据共享给其它的应用程序时,才需要用它,该组件对外提供了其他应用可以直接访问的增删查改的方法。并且 ContentProvider暴露了自己的数据,不管应用程序是否启动,都能访问到。      以下是我自己运用ContentProvider写的一个测试其中涉及到了:ContentProvider内容提供者 ;ContentResolver内容访问者。ContentProvider主要是提供数据资源,ContentResolver可以访问到ContentProvider的资源,并可以对其增删查改。两个运用程序可以直接访问第一步写一个提供数据的应用程序,这个程序中也可以开始提供添加数据  activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.g150825_16class.MainActivity">    <EditText    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:hint="Id:"    android:id="@+id/et_main_id"    />    <EditText        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:hint="Name:"        android:id="@+id/et_main_name"        />    <EditText        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:hint="Age:"        android:id="@+id/et_main_age"        />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        >   <Button       android:layout_width="0dp"       android:layout_height="wrap_content"       android:text="保存"       android:layout_weight="1"       android:onClick="save"       />        <Button            android:layout_width="0dp"            android:layout_height="wrap_content"            android:text="查询"            android:layout_weight="1"            android:onClick="query"            />    </LinearLayout>    <ListView    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@android:id/list"    ></ListView></LinearLayout>2.
MainActivity.java
package com.example.g150825_16class;import android.app.ListActivity;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.support.v7.app.AlertDialog;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.AdapterView;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.SimpleCursorAdapter;import android.widget.TextView;import android.widget.Toast;import com.example.g150825_16class.com.zking.db.DbHelper;public class MainActivity extends ListActivity {    private EditText et_main_id;    private EditText et_main_name;    private EditText et_main_age;    private SQLiteDatabase db;    private SimpleCursorAdapter simpleCursorAdapter;    private Cursor cursor;    private ListView listview;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //实例化DbHelper        DbHelper dbHelper=new DbHelper(this,"person.db",null,2);        //获取SQLiteDataBase对象(类似Hibernate中session        db = dbHelper.getReadableDatabase();        //获取ListView        listview = getListView();        initViews();        //查询所有        cursor = db.query(false,"person",null,null,null,null,null,null,null);        //循环游标        //把值放入list        //设置适配器        //SimpleCursorAdapter      simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.itm_list_view,                cursor,new String[]{"_id","name","age"},new int[]{R.id.tv_item_list_id,R.id.tv_item_list_name,R.id.tv_item_list_age});        listview.setAdapter(simpleCursorAdapter);        initEvents();//初始化事件    }    private void initEvents() {        //给ListView添加长按事件        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {            @Override            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {                //获取点击的每一行的值                LinearLayout root= (LinearLayout) view;                String id=((TextView)root.findViewById(R.id.tv_item_list_id)).getText().toString();                String name=((TextView)root.findViewById(R.id.tv_item_list_name)).getText().toString();                String age=((TextView)root.findViewById(R.id.tv_item_list_age)).getText().toString();                //弹出对话框(自定义)                final AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);                final AlertDialog dialog=builder.create();                //设置点击空白,不取消对话框                dialog.setCancelable(false);                //解析布局文件                View v=getLayoutInflater().inflate(R.layout.dialog_listview,null);                ((TextView)v.findViewById(R.id.tv_dialog_listview_id)).setText("修改:"+id);                ((EditText)v.findViewById(R.id.et_dialog_listview_name)).setText(name);                ((EditText)v.findViewById(R.id.et_dialog_listview_age)).setText(age);                ((Button)v.findViewById(R.id.btn_dialog_listview_sure)).setOnClickListener(new View.OnClickListener() {                    @Override                    public void onClick(View view) {                        Toast.makeText(MainActivity.this, "执行修改操作", Toast.LENGTH_SHORT).show();                        dialog.dismiss();//关闭当前的对话框                    }                });                ((Button)v.findViewById(R.id.btn_dialog_listview_cancel)).setOnClickListener(new View.OnClickListener() {                    @Override                    public void onClick(View view) {                        dialog.dismiss();//关闭当前的对话框                    }                });                dialog.setView(v);                dialog.show();                return true;            }        });    }    private void initViews() {        et_main_id = (EditText) findViewById(R.id.et_main_id);        et_main_name = (EditText) findViewById(R.id.et_main_name);        et_main_age = (EditText) findViewById(R.id.et_main_age);    }    public void save(View view){        String name=et_main_name.getText().toString();        int age=Integer.parseInt(et_main_age.getText().toString());        //保存到数据库        ContentValues values=new ContentValues();//Map        values.put("name",name);        values.put("age",age);        values.putNull("_id");        db.insert("person","name",values);        Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();        cursor=queryAllPerson(null);        //通知适配器发生改变        simpleCursorAdapter.changeCursor(cursor);    }    public Cursor queryAllPerson(String name){        //Cursor cursor=db.query(false,"person",null,null,null,null,null,null,null);        Cursor cursor;        if(!"".equals(name)){            Log.i("test","name="+name);            cursor=db.rawQuery("select * from person where name like ? limit ?,?",new String[]{"%"+name+"%",2+"",2+""});        }else{            Log.i("test","查询所有");            cursor = db.rawQuery("select * from person",null);        }        return cursor;    }    public void query(View view){//        if(!TextUtils.isEmpty(et_main_name.getText())){        String name=et_main_name.getText().toString();        cursor=queryAllPerson(name);        //通知适配器发生改变        simpleCursorAdapter.changeCursor(cursor);    }}
3.MyPersonProvider.Javapublic class MyPersonProvider extends ContentProvider{    private DbHelper dbHelper;    private SQLiteDatabase sqLiteDatabase;    @Override    public boolean onCreate() {        Log.i("test","onCreate");        //初始化DB        dbHelper = new DbHelper(getContext(),"person.db",null,2);        sqLiteDatabase = dbHelper.getReadableDatabase();        return false;    }    @Override    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {        Log.i("test","query");        //查询数据库中的所有数据        return sqLiteDatabase.query(false,"person",projection,selection,selectionArgs,null,null,sortOrder,null);    }    @Nullable    @Override    public String getType(Uri uri) {        Log.i("test","getType");        return null;    }    @Nullable    @Override    public Uri insert(Uri uri, ContentValues values) {        Log.i("test","insert");        sqLiteDatabase.insert("person",null,values);        return null;    }    @Nullable    @Override    public int delete(Uri uri, String selection, String[] selectionArgs) {        Log.i("test","delete");        sqLiteDatabase.delete("person",selection,selectionArgs);        return 0;    }    @Nullable    @Override    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {        Log.i("test","update");        sqLiteDatabase.update("person",values,selection,selectionArgs);        return 0;    }}
在清单文件中
<!--配置内容提供者--><provider    android:authorities="com.example.g150825_16class.PERSONS"    android:name=".com.zking.provider.MyPersonProvider"    android:exported="true"    ></provider>以上是contentProvider提供数据资源
那么ContentResolver内容访问者可以对上一个应用程序进行直接的访问
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"    android:layout_width="match_parent" android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.g150825_24contentresole.MainActivity">  <Button      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:onClick="getData"      android:text="获取数据"      />  <EditText      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:hint="Id:"      android:id="@+id/et_main_id"      />  <EditText      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:hint="Name:"      android:id="@+id/et_main_name"      />  <EditText      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:hint="Age:"      android:id="@+id/et_main_age"      />  <LinearLayout      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:orientation="horizontal"      >    <Button        android:layout_width="0dp"        android:layout_height="wrap_content"        android:text="保存"        android:layout_weight="1"        android:onClick="save"        /></LinearLayout><!--修改-->  <EditText      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:hint="修改Id:"      android:id="@+id/et_main_id_update"      />  <EditText      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:hint="修改Name:"      android:id="@+id/et_main_name_update"      />  <EditText      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:hint="修改Age:"      android:id="@+id/et_main_age_update"      />  <LinearLayout      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:orientation="horizontal"      >    <Button        android:layout_width="0dp"        android:layout_height="wrap_content"        android:text="修改保存"        android:layout_weight="1"        android:onClick="update"        />  </LinearLayout>  <!--删除-->  <EditText      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:hint="根据name删除:"      android:id="@+id/et_main_id_delete"      />  <LinearLayout      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:orientation="horizontal"      >    <Button        android:layout_width="0dp"        android:layout_height="wrap_content"        android:text="删除保存"        android:layout_weight="1"        android:onClick="delete"        />  </LinearLayout></LinearLayout>
MainActivity.java  这个文件中的URL是十分重要的,它是让两个程序进行访问的重要桥梁
package com.example.g150825_24contentresole;import android.content.ContentProvider;import android.content.ContentResolver;import android.content.ContentValues;import android.database.Cursor;import android.net.Uri;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.EditText;import android.widget.ListView;import android.widget.Toast;public class MainActivity extends AppCompatActivity {    private ContentResolver cr;    private ListView listview;    private Cursor cursor;    private EditText et_main_id;    private EditText et_main_name;    private EditText et_main_age;    private Uri uri;    private EditText et_main_id_update;    private EditText et_main_name_update;    private EditText et_main_age_update;    private EditText et_main_id_delete;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取内容访问者        initViews();        cr = getContentResolver();    }    private void initViews() {        et_main_id = (EditText) findViewById(R.id.et_main_id);        et_main_name = (EditText) findViewById(R.id.et_main_name);        et_main_age = (EditText) findViewById(R.id.et_main_age);       //修改        et_main_id_update = (EditText) findViewById(R.id.et_main_id_update);        et_main_name_update = (EditText) findViewById(R.id.et_main_name_update);        et_main_age_update = (EditText) findViewById(R.id.et_main_age_update);        //删除        et_main_id_delete = (EditText) findViewById(R.id.et_main_id_delete);    }    //查    public void getData(View view){        //访问数据        uri = Uri.parse("content://com.example.g150825_16class.PERSONS");        cursor = cr.query(uri,null,null,null,null);//拿取数据        while (cursor.moveToNext()){            int pid= cursor.getInt(cursor.getColumnIndex("_id"));            String name= cursor.getString(cursor.getColumnIndex("name            int age= cursor.getInt(cursor.getColumnIndex("age"));            Log.i("test",pid+"aa"+name+"bb"+age+"cc");        }    }    //增加    public void save(View view){        String name=et_main_name.getText().toString();        int age=Integer.parseInt(et_main_age.getText().toString());        uri = Uri.parse("content://com.example.g150825_16class.PERSONS");        //保存到数据库中        ContentValues values=new ContentValues();//Map        values.put("name",name);        values.put("age",age);        values.putNull("_id");        cr.insert(uri,values);        Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();    }    //修改    public  void update(View view){        Log.i("test","dddd");        String name=et_main_name_update.getText().toString();        int age=Integer.parseInt(et_main_age_update.getText().toString());        int pid=Integer.parseInt(et_main_age_update.getText().toString());        //url        uri = Uri.parse("content://com.example.g150825_16class.PERSONS");        ContentValues values=new ContentValues();//Map        values.put("name",name);        values.put("age",age);        String aa="_id=?";        String[] bb=new String[]{String.valueOf(pid)};        cr.update(uri,values,aa,bb);        Toast.makeText(MainActivity.this, "修改成功", Toast.LENGTH_SHORT).show();    }    //删除    public void delete(View view){        String name=et_main_id_delete.getText().toString();        uri = Uri.parse("content://com.example.g150825_16class.PERSONS");        cr.delete(uri,"name=?",new String[]{name});        Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();    }
1、ContentProvider内容提供者的应用程序
}
2、ContentResolver内容访问者

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表