Lolik

not404

nothing
x
bilibili
github
telegram

Android-ContentProvider

ContentProvider#

ContentProvider can help applications manage access to their stored data, which can be stored by other applications, and provide methods for sharing data with other applications. They encapsulate data and provide mechanisms for defining data security. Content providers are interfaces that connect data in one process with code running in another process.

content-provider-migration

ContentProvider methods

  • onCreate: called after the ContentProvider is created
  • getType: returns the MIME type of the data represented by the current Uri
  • query: used for external applications to query data from the ContentProvider
  • insert: used for external applications to add data to the ContentProvider
  • delete: used for external applications to delete data from the ContentProvider
  • update: used for external applications to update data in the ContentProvider

First, declare in the manifest, there are two ways (after the Android 11 update, the way the current application interacts with other native applications has changed), write both for safety:

    <application>
    ...
        <provider
            android:name=".MyContentProvider"
            android:authorities="com.example.provider.MyContentProvider"
            android:enabled="true"
            android:exported="true">
        </provider>
    </application>
    <queries>
        <provider android:authorities="com.example.provider.MyContentProvider"
            android:enabled="true"
            android:exported="true" />
    </queries>

Official documentation

https://developer.android.google.cn/guide/topics/providers/content-provider-creating#ContentURI

Uri#

A content URI is a URI that identifies data in a provider. A content URI includes the symbolic name (authority) of the entire provider and a name (path) that points to a table or file. An optional id part points to a single row in the table. Each data access method takes a content URI as a parameter, allowing you to determine the table, row, or file to access.

Official recommendation
https://developer.android.google.cn/guide/topics/providers/content-provider-creating?hl=en#kotlin

Example:

  • content://com.example.app.provider/table1: The table being called is table1.
  • com.example.app: Package name.
  • provider: ContentProvider Java file name.

Similar to database CRUD operations, define the CRUD operations for the database and wrap them in a ContentProvider.
As follows:

  • Encapsulate SQL operations in mydb.
  • Call them in ContentProvider and return a cursor.
  • Finally, use them.

az3


Provider App#

Define the database and create a student table with 3 fields#

mydb.java

public class mydb extends SQLiteOpenHelper {

    public mydb(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("create table student ("+
                "id integer primary key autoincrement,name varchar,age integer)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

Database operation class (only implemented insert and query)#

mydao.java

public class mydao {
    private Context context;
    private SQLiteDatabase database;
    public mydao(Context context){
        this.context=context;
        mydb dbhelper=new mydb(context,"db",null,1);
        database=dbhelper.getWritableDatabase();
        Log.d("qwe","getWritableDatabase");
    }
    public Uri Daoinsert(ContentValues contentValues){
        long rowid=database.insert("student",null,contentValues);
        Uri uri=Uri.parse("content://com.example.provider.MyContentProvider/student");
        Uri inserturi=ContentUris.withAppendedId(uri,rowid);
        context.getContentResolver().notifyChange(inserturi,null);
        return inserturi;
    }
    public Cursor query(String[] whichone,String selection,String[] selectionArgs,String sortOrder) {
        Log.d("qwe","ok");
        Cursor cursor1 = database.query("student",whichone,selection,selectionArgs,
                null,null,sortOrder);

        return cursor1;
    }
}

MYContentProvider.java (only used query and insert operations)

public class MyContentProvider extends ContentProvider {
    private mydao mydao;
    public MyContentProvider() {

    }
    @Override
    public String getType(Uri uri) {
        return "1";
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        getContext().getContentResolver().insert(uri,values);
        return mydao.Daoinsert(values);
    }

    @Override
    public boolean onCreate() {
        mydao=new mydao(this.getContext());
        return false;
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        return mydao.query(projection,selection,selectionArgs,sortOrder);
    }
}

Resolver App#

The following code queries the content content://com.example.provider.MyContentProvider/student where age > 0.

The commented part is the insert operation.

public class MainActivity extends AppCompatActivity {
    private String d="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button_resovel);
        TextView textView=findViewById(R.id.textView_resovel);

        ContentResolver resolver = getContentResolver();
        ContentValues values= new ContentValues();
        values.put("name","sb");
        values.put("age","20");

        Uri uri = Uri.parse("content://com.example.provider.MyContentProvider/student");

//        button.setOnClickListener(v -> resolver.insert(uri,values));

        button.setOnClickListener(v -> {
            Cursor cursor = resolver.query(uri, null, null, null, null);
            while (cursor.moveToNext()) {
                    @SuppressLint("Range") String name = cursor.getString(cursor.
                            getColumnIndex("name"));
                    @SuppressLint("Range") int age = cursor.getInt(cursor.
                            getColumnIndex("age"));
                    @SuppressLint("Range") int id = cursor.getInt(cursor.
                            getColumnIndex("id"));
                    Log.d("db", "id=" + id + "|name=" + name + "|age=" + age);
                    d += ("id=" + id + "|name=" + name + "|age=" + age);
                }
            textView.setText(d);
            }
        );
    }
}

Result Screenshots#

Left: Provider App, Right: Resolver App

az2

az1

Git Repository#

https://gitee.com/qwe2412322029/contentprovider

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.