Android review 09 [content provider, music player]

Posted by jack_indigo on Sun, 31 May 2020 06:46:28 +0200

catalog

PersonCp

PersonCp.java

insert()

ContentObserver

music player

1. Add read-write permission

1.1. Dynamic permission granting (calling encapsulated methods)

2. Get music files( MainActivity.java )

2, Music.java (entity class)

Apply for access to SD card

Set adapter

Drop down refresh

PersonCp

PersonCp.java

package cn.wangzg.personcp;

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

import java.util.Objects;

/**
 * Time: 2020/4/13
 * Author: wangzhiguo
 * Description: Function description
 */
public class PersonCp extends ContentProvider { //As a data source, the database saves the data to the database.
    private MyHelper mHelper;
    private final static String AUTHORITY = "cn.wangzg.personprovider";
    private static UriMatcher mUriMatcher;
    private static final int PERSON_DIR = 0;
    private static final int PERSON = 1;

    /**
     * Initializing the UriMatcher with static code blocks
     * Multiple URIs are included in the UriMatcher, each representing an operation
     * When called UriMatcher.match(Uri uri) method will return the code corresponding to the uri;
     * For example, PERSONS and PERSONS here
     */
    static {
        mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        // The URI indicates that all PERSONS are returned, where PERSONS is the ID code of the specific URI
        mUriMatcher.addURI(AUTHORITY, "person", PERSON_DIR);
        // The URI indicates that a PERSON is returned, where PERSON is the ID code of the specific URI
        mUriMatcher.addURI(AUTHORITY, "person/#", PERSON);
    }


    /**
     * getType(Uri uri) method must be overridden in custom ContentProvider
     * This method is used to get the MIME type corresponding to the Uri object
     * <p>
     * The MIME string corresponding to a Uri follows three points:
     * 1 Must start with vnd
     * 2 If the data corresponding to the Uri may contain multiple records, the return string should be“ vnd.android.cursor.dir / "start
     * 3 If the data corresponding to the Uri contains only one record, the return string should be“ vnd.android.cursor.item / "start
     */
    @Override
    public String getType(Uri uri) {
        switch (mUriMatcher.match(uri)) {
            case PERSON_DIR:
                return "vnd.android.cursor.dir/" + AUTHORITY + ".persons";
            case PERSON:
                return "vnd.android.cursor.item/" + AUTHORITY + ".person";
            default:
                throw new IllegalArgumentException("unknown uri" + uri.toString());
        }
    }


    @Override
    public boolean onCreate() {
        mHelper = new MyHelper(getContext());
        return true;
    }


    /**
     * Insert operation:
     * There is only one possible insert operation: insert into a table
     * The return result is the Uri corresponding to the new record
     * method db.insert() the return result is the primary key value corresponding to the new record
     */
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        switch (mUriMatcher.match(uri)) {
            case PERSON_DIR:
                long newId = db.insert("person", "name,phone,salary", values);
                //Inform the outside world that the data in the ContentProvider has changed, so that ContentObserver can make corresponding
                getContext().getContentResolver().notifyChange(uri, null);
                return ContentUris.withAppendedId(uri, newId);
            default:
                throw new IllegalArgumentException("unknown uri" + uri.toString());
        }
    }

    /**
     * Update operation:
     * There are two possibilities for an update operation: updating a table or updating a piece of data
     * When updating a piece of data, the principle is similar to querying a piece of data, as shown below
     */
    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        int updatedNum = 0;
        switch (mUriMatcher.match(uri)) {
            // Update table
            case PERSON_DIR:
                updatedNum = db.update("person", values, selection, selectionArgs);
                break;
            // Update a piece of data by id
            case PERSON:
                long id = ContentUris.parseId(uri);
                String where = "id=" + id;
                if (selection != null && !"".equals(selection.trim())) {
                    where = selection + " and " + where;
                }
                updatedNum = db.update("person", values, where, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("unknown uri" + uri.toString());
        }
        //Inform the outside world that the data in the ContentProvider has changed, so that ContentObserver can make corresponding
        Objects.requireNonNull(getContext()).getContentResolver().notifyChange(uri, null);
        return updatedNum;
    }

    /**
     * Delete operation:
     * There are two possibilities for deleting: deleting a table or deleting a piece of data
     * When deleting a piece of data, the principle is similar to querying a piece of data, as shown below
     */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        int deletedNum = 0;
        switch (mUriMatcher.match(uri)) {
            // Delete table
            case PERSON_DIR:
                deletedNum = db.delete("person", selection, selectionArgs);
                break;
            // Delete a piece of data by id
            case PERSON:
                long id = ContentUris.parseId(uri);
                String where = "id=" + id;
                if (selection != null && !"".equals(selection.trim())) {
                    where = selection + " and " + where;
                }
                deletedNum = db.delete("person", where, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("unknown uri" + uri.toString());
        }
        //Inform the outside world that the data in the ContentProvider has changed, so that ContentObserver can make corresponding
        Objects.requireNonNull(getContext()).getContentResolver().notifyChange(uri, null);
        return deletedNum;
    }

    /**
     * Query operation:
     * There are two possibilities for querying: querying a table or querying a piece of data
     * <p>
     * matters needing attention:
     * When querying a piece of data, you should pay attention to it -- because here is the query by id
     * A piece of data, but there may be other restrictions at the same time. For example:
     * Requires id 2 and name xiaoming1
     * So the query is divided into two steps:
     * Step 1:
     * Parse out the id and put it into the where query condition
     * Step 2:
     * Determine whether there are other restrictions (such as name). If so, group them into where query criteria
     * <p>
     * See below for detailed code
     */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        Cursor cursor = null;
        switch (mUriMatcher.match(uri)) {
            // Query table
            case PERSON_DIR:
                cursor = db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            // Query a piece of data by id
            case PERSON:
                // Step 1:
                long id = ContentUris.parseId(uri);
                String where = "id=" + id;
                // Step 2:
                if (selection != null && !"".equals(selection.trim())) {
                    where = selection + " and " + where;
                }
                cursor = db.query("person", projection, where, selectionArgs, null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("unknown uri" + uri.toString());
        }
        return cursor;
    }
}

insert()

ContentObserver

Rookie tutorial [4.4.1 content provider exploration]

https://www.runoob.com/w3cnote/android-tutorial-contentprovider.html

music player

1. Add read-write permission

1.1. Dynamic permission granting (calling encapsulated methods)

2. Get music files( MainActivity.java )

2, Music.java (entity class)

Apply for access to SD card

Set adapter

Drop down refresh

Let's have a goo d time 👍

Please~

Small business, not easy~

Topics: Android Java Database SQLite