What is cursor.setNotificationUri() used for?

后端 未结 3 1874
太阳男子
太阳男子 2020-12-05 00:18

I did research on how to use ContentProviders and Loaders from this tutorial

How I see it: We have an Activity with ListView,

3条回答
  •  粉色の甜心
    2020-12-05 00:52

    I use one URI for the cursor adaptor.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        Bundle args = new Bundle();
        Uri uri = TemperatureContract.SensorEntry.buildSensorID0AddressUri(mDeviceAddress);
        args.putParcelable("URI", uri);
        getSupportLoaderManager().initLoader(0, args, this);
    
    }
    
    @Override
    public Loader onCreateLoader(int id, Bundle args) {
        if (args != null) {
            Uri mUri = args.getParcelable("URI");
            return new CursorLoader(this,
                    mUri,
                    null, // projection
                    null, // selection
                    null, // selectionArgs
                    null); // sortOrder
        } else {
            return null;
        }
    }
    

    On another class, I use a different URI to change the database contents. To have my view updated, I had to change the default implementation of the data provider's update method. The default implementation only notifies the same URI. I have to notify another URI.

    I ended up by calling the notifyChange() twice on my data provider class, on the update method:

    @Override
    public int update(
            Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        final int match = sUriMatcher.match(uri);
        int rowsUpdated;
        switch (match) {
            case ...:
                break;
            case SENSOR_BY_ID_AND_ADDRESS:
                String sensorId = TemperatureContract.SensorEntry.getSensorIdFromUri(uri);
                String sensorAddress = TemperatureContract.SensorEntry.getSensorAddressFromUri(uri);
                rowsUpdated = db.update(
                        TemperatureContract.SensorEntry.TABLE_NAME, values, "sensorid = ? AND address = ?", new String[]{sensorId, sensorAddress});
                if (rowsUpdated != 0) {
                    Uri otheruri = TemperatureContract.SensorEntry.buildSensorID0AddressUri(sensorAddress);
                    getContext().getContentResolver().notifyChange(otheruri, null);
                }
                break;
            case ...:
                break;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        if (rowsUpdated != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return rowsUpdated;
    

    I did the same for the insertand delete methods.

提交回复
热议问题