Android开发 应用通信 ContentProvider ContentResolver

1.应用通信

Android开发 应用通信 ContentProvider ContentResolver_第1张图片

 

ContentProvider是一个Android组件,它提供了一个标准接口来在不同的应用程序之间共享数据。它充当应用程序和数据源之间的中介,数据源可以是SQLite数据库、文件,甚至是远程服务器。ContentProvider提供了一组方法来管理对数据的访问,例如查询、插入、更新和删除数据。它还支持内容URI,这些URI是表示一段数据的唯一标识符。


另一方面,ContentResolver是应用程序用来访问ContentProviders数据的另一个Android组件。ContentResolver负责查找并与保存请求数据的相应ContentProvider通信。它提供了一组方法来查询ContentProviders、插入、更新和删除数据,以及注册ContentObserver以侦听数据中的更改。

简单来说ContentProvider封装应用的数据,另一个应用想要访问该应用的数据,可以使用ContentResolver来调用ContentProvider中的增删查改方法。

2.代码

ContentProvider:

package com.example.ch07_server;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import com.example.ch07_server.database.DBHelper;

public class ServerContentProvider extends ContentProvider {
    private DBHelper dbHelper;
    private static final String authority = "com.example.ch07_server.ServerContentProvider";
    private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    private static final int USERS = 1;
    private static final int USER = 2;

    static {
        URI_MATCHER.addURI(authority,"/goods_info",USERS);
        URI_MATCHER.addURI(authority,"/goods_info/#",USER);

    }




    public ServerContentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        //throw new UnsupportedOperationException("Not yet implemented");
        Log.d("seq","ServerContentProvider  delete()");
        int count = 0;
        switch (URI_MATCHER.match(uri)){
            case USERS:
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                count = db.delete(DBHelper.TABLE_GOODS_INFO,selection,selectionArgs);
                db.close();
                //Log.d("seq","ServerContentProvider  delete()" + USERS);
                break;
            case USER:
                String  id = uri.getLastPathSegment();
                SQLiteDatabase db2 = dbHelper.getWritableDatabase();
                count = db2.delete(DBHelper.TABLE_GOODS_INFO,"_id=?",new String[]{id});
                //Log.d("seq","ServerContentProvider  delete()" + USER);
                break;
        }

        return count;
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO: Implement this to handle requests to insert a new row.
        Log.d("seq","ServerContentProvider  insert");
        SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase();
        writableDatabase.insert(DBHelper.TABLE_GOODS_INFO,null,values);
        return uri;


    }

    @Override
    public boolean onCreate() {
        // TODO: Implement this to initialize your content provider on startup.
        Log.d("seq","ServerContentProvider  onCreate()");
        dbHelper = DBHelper.getInstance(getContext());

        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // TODO: Implement this to handle query requests from clients.
        Log.d("seq","ServerContentProvider  query()");
        SQLiteDatabase readableDatabase = dbHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query(DBHelper.TABLE_GOODS_INFO, projection, selection, selectionArgs, null, null, null);
        return cursor;

    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // TODO: Implement this to handle requests to update one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

ContentResolver:

package com.example.ch07_client;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class ContentWriteActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_name;
    private EditText et_desc;
    private EditText et_price;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_write);
        et_name = findViewById(R.id.et_name);
        et_desc = findViewById(R.id.et_desc);
        et_price = findViewById(R.id.et_price);

        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_delete).setOnClickListener(this);
        findViewById(R.id.btn_query).setOnClickListener(this);
        findViewById(R.id.btn_modify).setOnClickListener(this);
    }

    @SuppressLint("Range")
    @Override
    public void onClick(View view) {
        Uri uri = Uri.parse("content://" + "com.example.ch07_server.ServerContentProvider" + "/goods_info");
        switch (view.getId()){
            case R.id.btn_save:
                ContentValues values = new ContentValues();
                values.put("name", et_name.getText().toString());
                values.put("description", et_desc.getText().toString());
                values.put("price", Float.parseFloat(et_price.getText().toString() ));
                values.put("pic_path", "null");
                getContentResolver().insert(uri, values);

                break;
            case R.id.btn_query:
                Cursor cursor = getContentResolver().query(uri,null,null,null,null);
                if(cursor!=null){
                    while(cursor.moveToNext()){
                        String output = "";
                        output += "name: " + cursor.getString(cursor.getColumnIndex("name")) + ", ";
                        output += "desc: " + cursor.getString(cursor.getColumnIndex("description")) + ", ";
                        output += "price: " + cursor.getString(cursor.getColumnIndex("price")) + "\n";
                        Log.d("query: ", output);
                    }
                }
                break;
            case R.id.btn_delete:

                Uri uri2 = ContentUris.withAppendedId(uri,3);
                Log.d("DELETE: ",uri2.toString());
                int count = getContentResolver().delete(uri2,null,null);
                //int count = getContentResolver().delete(uri,"name=?",new String[]{"linda"});
                if(count>0){
                    Log.d("DELETE: ", "delete " + count + " records");
                }
                break;
        }
    }
}

你可能感兴趣的:(APP开发,android,java)