android - 如何让 notifyChange() 在两个 Activity 之间工作?

标签 android android-contentprovider

我有一个 Activity ActitvityA,它包含一个由 CursorLoader 填充的 ListView 。我想切换到 ActivityB 并更改一些数据,然后查看这些更改反射(reflect)在 ActivityA 的 ListView 中。

public class ActivityA implements LoaderManager.LoaderCallbacks<Cursor>
{ 
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);
        getSupportLoaderManager().initLoader(LOADER_ID, null, this);
        mCursorAdapter = new MyCursorAdapter(   
            this,
            R.layout.my_list_item,
            null,
            0 );
    }
        .
        .
        .

    /** Implementation of LoaderManager.LoaderCallbacks<Cursor> methods */
    @Override
    public Loader<Cursor> onCreateLoader(int loaderId, Bundle arg1) {
        CursorLoader result;
        switch ( loaderId ) {           
        case LOADER_ID:
            /* Rename v _id is required for adapter to work */
            /* Use of builtin ROWID http://www.sqlite.org/autoinc.html */
            String[] projection = {
                    DBHelper.COLUMN_ID + " AS _id",     //http://www.sqlite.org/autoinc.html
                    DBHelper.COLUMN_NAME    // columns in select
            }
            result = new CursorLoader(  ActivityA.this,
                                        MyContentProvider.CONTENT_URI,
                                        projection,
                                        null,
                                        new String[] {},
                                        DBHelper.COLUMN_NAME + " ASC");
            break;
        default: throw new IllegalArgumentException("Loader id has an unexpectd value.");
    }
    return result;
}


    /** Implementation of LoaderManager.LoaderCallbacks<Cursor> methods */
    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        switch (loader.getId()) {
            case LOADER_ID:
                mCursorAdapter.swapCursor(cursor);
                break;
            default: throw new IllegalArgumentException("Loader has an unexpected id.");
        }
    }
        .
        .
        .
}

我从 ActivityA 切换到 ActivityB,在其中更改基础数据。

// insert record into table TABLE_NAME
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, someValue);
context.getContentResolver().insert( MyContentProvider.CONTENT_URI, values);

MyContentProvider 的详细信息:

public class MyContentProvider extends ContentProvider {
    .
    .
    .

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int uriCode = sURIMatcher.match(uri);
        SQLiteDatabase database = DBHelper.getInstance().getWritableDatabase();
        long id = 0;
        switch (uriType) {
        case URI_CODE:
            id = database.insertWithOnConflict(DBHelper.TABLE_FAVORITE, null, values,SQLiteDatabase.CONFLICT_REPLACE);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);  // I call the notifyChange with correct uri
        return ContentUris.withAppendedId(uri, id);
    }


    @Override
    public Cursor query(Uri uri,
                        String[] projection,
                        String selection,
                        String[] selectionArgs,
                        String sortOrder) {

        // Using SQLiteQueryBuilder instead of query() method
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        int uriCode = sURIMatcher.match(uri);
        switch (uriCode) {
        case URI_CODE:
            // Set the table
            queryBuilder.setTables(DBHelper.TABLE_NAME);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        SQLiteDatabase database = DBHelper.getInstance().getWritableDatabase();
        Cursor cursor = queryBuilder.query( database, projection, selection, selectionArgs, null, null, sortOrder);
        // Make sure that potential listeners are getting notified
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }
}

据我所知,这应该足够了。但它不起作用。 返回 ActivityA 后, ListView 未更改

我用调试器跟踪了一些事情,这就是发生的事情。

首先访问ActivityA,依次调用的方法

MyContentProvider.query()    
ActivityA.onLoadFinished()

ListView 显示正确的值。 现在我切换到 activityB 并更改数据

MyContentProvider.insert()  // this one calls getContext().getContentResolver().notifyChange(uri, null);
MyContentProvider.query()
//As we can see the MyContentProvider.query is executed. I guess in response to notifyChange().
// What I found puzzling why now, when ActivityB is still active ?

返回 Activity A

!!! ActivityA.onLoadFinished() is not called    

我已经阅读了所有关于此的内容,仔细研究了很多 stackoverflow 问题,但所有这些问题/答案都围绕着我实现的 setNotificationUri() 和 notifyChangeCombo() 展开。为什么这不适用于所有 Activity ?

例如,如果使用

在 ActivityA.onResume() 中强制刷新
getContentResolver().notifyChange(MyContentProvider.CONTENT_URI, null, false);

然后它刷新 ListView 。但这将强制刷新每份简历,无论数据是否更改。

最佳答案

经过长达两天的挠头和 pskink 的无私参与之后,我给自己描绘了一幅错误的画面。 我的 ActivityA 实际上要复杂得多。它使用 ViewPager 和 PagerAdapter 实例化 ListView 。 起初我在 onCreate() 方法中创建了这些组件,如下所示:

@Override
public void onCreate(Bundle savedInstanceState)
{
        ...
    super.onCreate(savedInstanceState);
    // 1 .ViewPager
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    ...
    viewPager.setAdapter( new MyPagerAdapter() );
    viewPager.setOnPageChangeListener(this); */
    ...
    // 2. Loader
    getSupportLoaderManager().initLoader(LOADER_ID, null, this);
    ...
    // 3. CursorAdapter
    myCursorAdapter = new MyCursorAdapter(
                    this,
                    R.layout.list_item_favorites_history,
                    null,
      0);
}

在某处,我注意到这是错误的创建顺序。它没有产生错误的原因是因为在 onCreate() 完成后调用了 PagerAdapter.instantiateItem()。我不知道为什么或如何导致最初的问题。也许有些东西没有正确连接 ListView 、适配器和内容观察器。我没有深入研究。

我把顺序改为:

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    ...
    // 1. CursorAdapter
    myCursorAdapter = new MyCursorAdapter(
                    this,
                    R.layout.list_item_favorites_history,
                    null,
                    0);
    ...
    // 2. Loader
    getSupportLoaderManager().initLoader(LOADER_ID, null, this);
    ...
    // 3 .ViewPager
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    ...
    viewPager.setAdapter( new MyPagerAdapter() );
    viewPager.setOnPageChangeListener(this); */
    ...        
}

这神奇地使其在大约 75% 的情况下有效。当我研究 CatLog 输出时,我注意到 ActivityA().onStop() 在不同时间被调用。当它工作时,它被称为延迟,我可以在 logcat 中看到 onLoadFinished() 执行。有时 ActivityA.onStop() 会在查询后立即执行,然后根本不会调用 onLoadFinished()。这让我想起了 DeeV jas 在他关于从 ContentResolver 取消注册游标的回答中发布的内容。这可能就是这种情况。 让事情不知何故曝光的事实是,尽管它们在关键点上是相同的,但 pskink 坚持的简单演示器确实有效,而我的应用程序却没有。这让我注意到异步事物和我的 onCreate() 方法。实际上,我的 ActivityB 很复杂,因此它为 ActivityA 提供了足够的时间来停止。 我还注意到(这确实让事情更难排序)是,如果我在 Debug模式下运行我的 75% 版本(没有断点),那么成功率会下降到 0。ActivityA 在光标加载完成之前停止,所以我的 onLoadFinished () 永远不会被调用, ListView 也永远不会更新。

两个关键点:

  • ViewPager、CursorAdapter 和 CursorLoader 很重要
  • ActivityA 可能(并且已经)在之前停止 光标已加载。

但即使这样也不是。如果我看一下简化的序列,那么我会看到 ActivityA.onStop() 在内容提供者插入记录之前执行。 ActivityB 处于 Activity 状态时我看不到任何查询。但是当我返回到 ActivityA 时,将执行 laodFinished() 查询并刷新 ListView 。在我的应用程序中不是这样。它总是在 ActivityB 中执行查询,为什么???这破坏了我关于 onStop() 是罪魁祸首的理论。

(非常感谢 pskink 和 DeeV)

更新

在这个问题上浪费了很多时间后,我终于找到了问题的原因。

简短描述:

我有以下类(class):

ActivityA - contains a list view populated via cursor loader.
ActivityB - that changes data in database
ContentProvider - content provider used for data manipulation and also used by cursorloader.

问题:

在 ActivityB 中进行数据操作后,更改不会显示在 ActivityA 的 ListView 中。 ListView 未刷新。

在我仔细观察和研究 logcat 跟踪后,我发现事情按以下顺序进行:

ActivityA is started

    ActivityA.onCreate()
        -> getSupportLoaderManager().initLoader(LOADER_ID, null, this);

    ContentProvider.query(uri)  // query is executes as it should

    ActivityA.onLoadFinished()  // in this event handler we change cursor in list view adapter and listview is populated


ActivityA starts ActivityB

    ActivityA.startActivity(intent)

    ActivityB.onCreate()
        -> ContentProvider.insert(uri)      // data is changed in the onCreate() method. Retrieved over internet and written into DB.
            -> getContext().getContentResolver().notifyChange(uri, null);   // notify observers

    ContentProvider.query(uri)
    /*  We can see that a query in content provider is executed.
        This is WRONG in my case. The only cursor for this uri is cursor in cursor loader of ActivityA.
        But ActivityA is not visible any more, so there is no need for it's observer to observe. */

    ActivityA.onStop()
    /*  !!! Only now is this event executed. That means that ActivityA was stopped only now.
        This also means (I guess) that all the loader/loading of ActivityA in progress were stopped.
        We can also see that ActivityA.onLoadFinished() was not called, so the listview was never updated.
        Note that ActivityA was not destroyed. What is causing Activity to be stopped so late I do not know.*/


ActivityB finishes and we return to ActivityA

    ActivityA.onResume()

    /*  No ContentProvider.query() is executed because we have cursor has already consumed
        notification while ActivityB was visible and ActivityA was not yet stopped.
        Because there is no query() there is no onLoadFinished() execution and no data is updated in listview */

所以问题不在于 ActivityA 停止得太快,而是它停止得太晚了。数据更新并通知 在创建 ActivityB 和停止 ActivityA 之间的某处发送。 解决方案是强制 ActivityA 中的加载器在 ActivityB 启动之前停止加载。

ActivityA.getSupportLoaderManager().getLoader(LOADER_ID).stopLoading(); // <- THIS IS THE KEY
ActivityA.startActivity(intent)

这会停止加载程序并且(我再次猜测)防止光标在 Activity 处于上述边缘状态时使用通知。 现在的事件顺序是:

ActivityA is started

    ActivityA.onCreate()
        -> getSupportLoaderManager().initLoader(LOADER_ID, null, this);

    ContentProvider.query(uri)  // query is executes as it should

    ActivityA.onLoadFinished()  // in this event handler we change cursor in list view adapter and listview is populated


ActivityA starts ActivityB

    ActivityA.getSupportLoaderManager().getLoader(LOADER_ID).stopLoading();
    ActivityA.startActivity(intent)

    ActivityB.onCreate()
    -> ContentProvider.insert(uri)
        -> getContext().getContentResolver().notifyChange(uri, null);   // notify observers

    /*  No ContentProvider.query(uri) is executed, because we have stopped the loader in ActivityA. */

    ActivityA.onStop()
    /*  This event is still executed late. But we have stopped the loader so it didn't consume notification. */


ActivityB finishes and we return to ActivityA

    ActivityA.onResume()

    ContentProvider.query(uri)  // query is executes as it should

    ActivityA.onLoadFinished()  // in this event handler we change cursor in list view adapter and listview is populated

/* The listview is now populated with up to date data */

这是我能找到的最优雅的解决方案。无需重新启动装载机等。 但我仍然想听听有更深刻见解的人对该主题的评论。

关于android - 如何让 notifyChange() 在两个 Activity 之间工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32741634/

相关文章:

Android Studio 在运行 Flutter App 时抛出异常

Android 下载管理器不适合我

java - 获得速度后需要帮助设置条件

android - 无法选择电话号码与 IN 子句匹配的所有联系人

android - 如何更好地控制 Android SAF UI(例如 ACTION_OPEN_DOCUMENT)?

java - 一个 Activity 上的第二个按钮关闭 android 应用程序

android - 适用于 Android 的 ADAL - 处理错误的正确方法是什么?

android - queryBuilder.appendWhere() 的意义何在?安卓

android - 在 Android 中将联系人数据加入我的表格

android - 将图像添加到 android 联系人时的一些问题