Java Code Examples for android.content.ContentResolver#registerContentObserver()

The following examples show how to use android.content.ContentResolver#registerContentObserver() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MediaFileViewModel.java    From FilePicker with Apache License 2.0 6 votes vote down vote up
private MediaFileViewModel(ContentResolver contentResolver, Configurations configs, Long dirId) {
    this.contentResolver = contentResolver;

    MediaFileDataSource.Factory mediaFileDataSourceFactory = new MediaFileDataSource.Factory(contentResolver, configs, dirId);

    mediaFiles = new LivePagedListBuilder<>(
            mediaFileDataSourceFactory,
            new PagedList.Config.Builder()
                    .setPageSize(Configurations.PAGE_SIZE)
                    .setInitialLoadSizeHint(15)
                    .setMaxSize(Configurations.PAGE_SIZE * 3)
                    .setPrefetchDistance(Configurations.PREFETCH_DISTANCE)
                    .setEnablePlaceholders(false)
                    .build()
    ).build();

    contentResolver.registerContentObserver(mediaFileDataSourceFactory.getUri(), true, contentObserver);
}
 
Example 2
Source File: UserDictionary.java    From hackerskeyboard with Apache License 2.0 6 votes vote down vote up
public UserDictionary(Context context, String locale) {
    super(context, Suggest.DIC_USER);
    mLocale = locale;
    // Perform a managed query. The Activity will handle closing and requerying the cursor
    // when needed.
    ContentResolver cres = context.getContentResolver();
    
    cres.registerContentObserver(Words.CONTENT_URI, true, mObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean self) {
            setRequiresReload(true);
        }
    });

    loadDictionary();
}
 
Example 3
Source File: ContactsContentObserver.java    From openboard with GNU General Public License v3.0 6 votes vote down vote up
public void registerObserver(final ContactsChangedListener listener) {
    if (!PermissionsUtil.checkAllPermissionsGranted(
            mContext, Manifest.permission.READ_CONTACTS)) {
        Log.i(TAG, "No permission to read contacts. Not registering the observer.");
        // do nothing if we do not have the permission to read contacts.
        return;
    }

    if (DebugFlags.DEBUG_ENABLED) {
        Log.d(TAG, "registerObserver()");
    }
    mContactsChangedListener = listener;
    mContentObserver = new ContentObserver(null /* handler */) {
        @Override
        public void onChange(boolean self) {
            ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD)
                    .execute(ContactsContentObserver.this);
        }
    };
    final ContentResolver contentResolver = mContext.getContentResolver();
    contentResolver.registerContentObserver(Contacts.CONTENT_URI, true, mContentObserver);
}
 
Example 4
Source File: BatteryService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void onBootPhase(int phase) {
    if (phase == PHASE_ACTIVITY_MANAGER_READY) {
        // check our power situation now that it is safe to display the shutdown dialog.
        synchronized (mLock) {
            ContentObserver obs = new ContentObserver(mHandler) {
                @Override
                public void onChange(boolean selfChange) {
                    synchronized (mLock) {
                        updateBatteryWarningLevelLocked();
                    }
                }
            };
            final ContentResolver resolver = mContext.getContentResolver();
            resolver.registerContentObserver(Settings.Global.getUriFor(
                    Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
                    false, obs, UserHandle.USER_ALL);
            updateBatteryWarningLevelLocked();
        }
    }
}
 
Example 5
Source File: TextClock.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void registerObserver() {
    if (mRegistered) {
        if (mFormatChangeObserver == null) {
            mFormatChangeObserver = new FormatChangeObserver(getHandler());
        }
        final ContentResolver resolver = getContext().getContentResolver();
        Uri uri = Settings.System.getUriFor(Settings.System.TIME_12_24);
        if (mShowCurrentUserTime) {
            resolver.registerContentObserver(uri, true,
                    mFormatChangeObserver, UserHandle.USER_ALL);
        } else {
            resolver.registerContentObserver(uri, true,
                    mFormatChangeObserver);
        }
    }
}
 
Example 6
Source File: ContactsContentObserver.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 6 votes vote down vote up
public void registerObserver(final ContactsChangedListener listener) {
    if (!PermissionsUtil.checkAllPermissionsGranted(
            mContext, Manifest.permission.READ_CONTACTS)) {
        Log.i(TAG, "No permission to read contacts. Not registering the observer.");
        // do nothing if we do not have the permission to read contacts.
        return;
    }

    if (DebugFlags.DEBUG_ENABLED) {
        Log.d(TAG, "registerObserver()");
    }
    mContactsChangedListener = listener;
    mContentObserver = new ContentObserver(null /* handler */) {
        @Override
        public void onChange(boolean self) {
            ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD)
                    .execute(ContactsContentObserver.this);
        }
    };
    final ContentResolver contentResolver = mContext.getContentResolver();
    contentResolver.registerContentObserver(Contacts.CONTENT_URI, true, mContentObserver);
}
 
Example 7
Source File: MainActivity.java    From SyncManagerAndroid-DemoGoogleTasks with MIT License 5 votes vote down vote up
private void registerContentObservers() {
	ContentResolver cr = getContentResolver();
	handler = new Handler();		
	mTaskContentObserver = new TaskContentObserver(handler);
	cr.registerContentObserver(TaskSyncContentProvider.CONTENT_URI, true,
			mTaskContentObserver);
}
 
Example 8
Source File: Launcher.java    From TurboLauncher with Apache License 2.0 5 votes vote down vote up
/**
 * Registers various content observers. The current implementation registers
 * only a favorites observer to keep track of the favorites applications.
 */
private void registerContentObservers() {
	ContentResolver resolver = getContentResolver();
	resolver.registerContentObserver(
			LauncherProvider.CONTENT_APPWIDGET_RESET_URI, true,
			mWidgetObserver);
}
 
Example 9
Source File: AndroidWordLevelSpellCheckerSession.java    From openboard with GNU General Public License v3.0 5 votes vote down vote up
AndroidWordLevelSpellCheckerSession(final AndroidSpellCheckerService service) {
    mService = service;
    final ContentResolver cres = service.getContentResolver();

    mObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean self) {
            mSuggestionsCache.clearCache();
        }
    };
    cres.registerContentObserver(Words.CONTENT_URI, true, mObserver);
}
 
Example 10
Source File: Launcher.java    From LaunchEnr with GNU General Public License v3.0 5 votes vote down vote up
static void initContentObserver(Activity activity) {

            Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;

            ContentResolver contentResolver = activity.getContentResolver();

            contentResolver.
                    registerContentObserver(
                            contactsUri,
                            true,
                            new ContactsObserver(new Handler(), activity));
        }
 
Example 11
Source File: AndroidWordLevelSpellCheckerSession.java    From Indic-Keyboard with Apache License 2.0 5 votes vote down vote up
AndroidWordLevelSpellCheckerSession(final AndroidSpellCheckerService service) {
    mService = service;
    final ContentResolver cres = service.getContentResolver();

    mObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean self) {
            mSuggestionsCache.clearCache();
        }
    };
    cres.registerContentObserver(Words.CONTENT_URI, true, mObserver);
}
 
Example 12
Source File: MediaStoreDataLoader.java    From FastAndroid with Apache License 2.0 5 votes vote down vote up
private void registerContentObserver() {
    if (!observerRegistered) {
        ContentResolver cr = getContext().getContentResolver();
        cr.registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, false, forceLoadContentObserver);
        cr.registerContentObserver(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, false, forceLoadContentObserver);
        observerRegistered = true;
    }
}
 
Example 13
Source File: SettingsProviderTest.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
private void setSettingAndAssertSuccessfulChange(Runnable setCommand, final int type,
        final String name, final String value, final int userId) throws Exception {
    ContentResolver contentResolver = getContext().getContentResolver();

    final Uri settingUri = getBaseUriForType(type);

    final AtomicBoolean success = new AtomicBoolean();

    ContentObserver contentObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {
        public void onChange(boolean selfChange, Uri changeUri, int changeId) {
            Log.i(LOG_TAG, "onChange(" + selfChange + ", " + changeUri + ", " + changeId + ")");
            assertEquals("Wrong change Uri", changeUri, settingUri);
            assertEquals("Wrong user id", userId, changeId);
            String changeValue = getStringViaFrontEndApiSetting(type, name, userId);
            assertEquals("Wrong setting value", value, changeValue);

            success.set(true);

            synchronized (mLock) {
                mLock.notifyAll();
            }
        }
    };

    contentResolver.registerContentObserver(settingUri, false, contentObserver, userId);

    try {
        setCommand.run();

        final long startTimeMillis = SystemClock.uptimeMillis();
        synchronized (mLock) {
            if (success.get()) {
                return;
            }
            final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
            if (elapsedTimeMillis > WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS) {
                fail("Could not change setting for "
                        + WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS + " ms");
            }
            final long remainingTimeMillis = WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS
                    - elapsedTimeMillis;
            try {
                mLock.wait(remainingTimeMillis);
            } catch (InterruptedException ie) {
                /* ignore */
            }
        }
    } finally {
        contentResolver.unregisterContentObserver(contentObserver);
    }
}
 
Example 14
Source File: TestWeatherProvider.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it prior to this method being run.
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
Example 15
Source File: TestWeatherProvider.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it prior to this method being run.
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
Example 16
Source File: TestTaskContentProvider.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * Tests deleting a single row of data via a ContentResolver
 */
@Test
public void testDelete() {
    /* Access writable database */
    TaskDbHelper helper = new TaskDbHelper(InstrumentationRegistry.getTargetContext());
    SQLiteDatabase database = helper.getWritableDatabase();

    /* Create a new row of task data */
    ContentValues testTaskValues = new ContentValues();
    testTaskValues.put(TaskContract.TaskEntry.COLUMN_DESCRIPTION, "Test description");
    testTaskValues.put(TaskContract.TaskEntry.COLUMN_PRIORITY, 1);

    /* Insert ContentValues into database and get a row ID back */
    long taskRowId = database.insert(
            /* Table to insert values into */
            TaskContract.TaskEntry.TABLE_NAME,
            null,
            /* Values to insert into table */
            testTaskValues);

    /* Always close the database when you're through with it */
    database.close();

    String insertFailed = "Unable to insert into the database";
    assertTrue(insertFailed, taskRowId != -1);


    /* TestContentObserver allows us to test if notifyChange was called appropriately */
    TestUtilities.TestContentObserver taskObserver = TestUtilities.getTestContentObserver();

    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (tasks) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            TaskContract.TaskEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            taskObserver);



    /* The delete method deletes the previously inserted row with id = 1 */
    Uri uriToDelete = TaskContract.TaskEntry.CONTENT_URI.buildUpon().appendPath("1").build();
    int tasksDeleted = contentResolver.delete(uriToDelete, null, null);

    String deleteFailed = "Unable to delete item in the database";
    assertTrue(deleteFailed, tasksDeleted != 0);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    taskObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(taskObserver);
}
 
Example 17
Source File: TestWeatherProvider.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it prior to this method being run.
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
Example 18
Source File: TestWeatherProvider.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it when this method is run
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
Example 19
Source File: MobileContactSingleton.java    From customview-samples with Apache License 2.0 4 votes vote down vote up
private MobileContactSingleton() {
    Log.d("hyh", "MobileContactSingleton: MobileContactSingleton: 实例化");
    mMobileContactObserver = new MobileContactObserver(null);
    ContentResolver contentResolver = MyApplication.getApplication().getContentResolver();
    contentResolver.registerContentObserver(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,false,mMobileContactObserver);
}
 
Example 20
Source File: TestTaskContentProvider.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * Tests inserting a single row of data via a ContentResolver
 */
@Test
public void testInsert() {

    /* Create values to insert */
    ContentValues testTaskValues = new ContentValues();
    testTaskValues.put(TaskContract.TaskEntry.COLUMN_DESCRIPTION, "Test description");
    testTaskValues.put(TaskContract.TaskEntry.COLUMN_PRIORITY, 1);

    /* TestContentObserver allows us to test if notifyChange was called appropriately */
    TestUtilities.TestContentObserver taskObserver = TestUtilities.getTestContentObserver();

    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (tasks) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            TaskContract.TaskEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            taskObserver);


    Uri uri = contentResolver.insert(TaskContract.TaskEntry.CONTENT_URI, testTaskValues);


    Uri expectedUri = ContentUris.withAppendedId(TaskContract.TaskEntry.CONTENT_URI, 1);

    String insertProviderFailed = "Unable to insert item through Provider";
    assertEquals(insertProviderFailed, uri, expectedUri);

    /*
     * If this fails, it's likely you didn't call notifyChange in your insert method from
     * your ContentProvider.
     */
    taskObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(taskObserver);
}