1

Всем привет. Не могу накапать как правильно обновлять ListFragment. Вроде при заполнение с помощью LoaderManager курсор при изменении базы данных должен обновляться сам, судя из инфы с http://developer.android.com/reference/android/app/LoaderManager.LoaderCallbacks.html :

public abstract void onLoadFinished (Loader<D> loader, D data)

Added in API level 11 Called when a previously created loader has finished its load. Note that normally an application is not allowed to commit fragment transactions while in this call, since it can happen after an activity's state is saved. See FragmentManager.openTransaction() for further discussion on this.

This function is guaranteed to be called prior to the release of the last data that was supplied for this Loader. At this point you should remove all use of the old data (since it will be released soon), but should not do your own release of the data since its Loader owns it and will take care of that. The Loader will take care of management of its data so you don't have to. In particular:

The Loader will monitor for changes to the data, and report them to you through new calls here. You should not monitor the data yourself. For example, if the data is a Cursor and you place it in a CursorAdapter, use the CursorAdapter(android.content.Context, android.database.Cursor, int) constructor without passing in either FLAG_AUTO_REQUERY or FLAG_REGISTER_CONTENT_OBSERVER (that is, use 0 for the flags argument). This prevents the CursorAdapter from doing its own observing of the Cursor, which is not needed since when a change happens you will get a new Cursor throw another call here.

The Loader will release the data once it knows the application is no longer using it. For example, if the data is a Cursor from a CursorLoader, you should not call close() on it yourself. If the Cursor is being placed in a CursorAdapter, you should use the swapCursor(android.database.Cursor) method so that the old Cursor is not closed.

Но он не обновляется, он считывает данные из базы только один раз и при изменении базы данных курсор не обновляется. Максимум, что у меня получилось добиться, это запустить обновление при переключении между вкладками(фрагмент служит содержим одной из вкладок FragmetActivity). Для этого я инициализировал LoaderManager каждый раз разными ид, через рандомное число. Из более менее осмысленного - пытался перевызывать LoaderManager в AsynkTask .Еще пробовал adapter.notifyDataSetChanged(). Но это как и метод тыка и гугл не помогли.

public class ChatList extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {

    final Uri CONTACT_URI = Uri.parse("content://ivied.p001astreamchat/chats");
    String chatName;
    ChatCursorAdapter adapter;
     private LoaderManager.LoaderCallbacks<Cursor> mCallbacks;
     private static final int LOADER_ID = 1;

     @Override
      public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(LOG_TAG, this.toString());

        String[] from = new String[] { MyContentProvider.MESSAGES_CHANEL, MyContentProvider.MESSAGES_MESSAGE };
        int[] to = new int[] { R.id.ivImg, R.id.tvText };
     // Initialize the adapter.
        adapter = new ChatCursorAdapter(getActivity(), 
                R.layout.message, null, from, to, 0);
     // Associate the (now empty) adapter with the ListView.
        setListAdapter(adapter);

        mCallbacks = this;
        LoaderManager lm = getLoaderManager();
        lm.initLoader(1, null, mCallbacks);

     }

     @Override
     public Loader<Cursor> onCreateLoader(int id, Bundle args) {

         String [] selectionArgs = new String[] { "67822" };

           Loader<Cursor> mLoader = new CursorLoader(getActivity(), CONTACT_URI, null, "channel = ?",
                    selectionArgs, null);
            return mLoader;

     }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

            // Swap the new cursor in. (The framework will take care of closing the
            // old cursor once we return.)

            adapter.swapCursor(data);
            setListAdapter(adapter); 
            // The list should now be shown.
            if (isResumed()) {
                setListShown(true);
            } else {
                setListShownNoAnimation(true);
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

            // This is called when the last Cursor provided to onLoadFinished()
            // above is about to be closed. We need to make sure we are no
            // longer using it.
            adapter.swapCursor(null);
        }

}

`

1 ответ 1

1

нашёл 2 решения если есть свой ContenetProvider добавляем строку в метод public Cursor query:

cursor.setNotificationUri(getContext().getContentResolver(),
                MESSAGES_CONTENT_URI);

если нет тогда используем BroadcastReceiver :

....

public void onActivityCreated(Bundle savedInstanceState) {

.....

newMessage = new BroadcastReceiver() {

public void onReceive(Context context, Intent intent) {

                                 LoaderManager lm = getLoaderManager();

                                 lm.restartLoader(LOADER_ID, null, mCallbacks);   }};

....

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.