Problemas con la actualización de un vista.

10 views
Skip to first unread message

Elias Ortiz Reyes

unread,
Jan 22, 2015, 7:37:18 AM1/22/15
to gdg-ba...@googlegroups.com

Buenas a todos!!!

Os cuento, tengo un problema con un Pagerview, la version resumida, es que no me actualiza la vista cuando le proporciona información nueva

La version extendida:

He implementado un SearchView en el ActionBar. Cada vez que intruces un nuevo caracter en search, se realiza la busqueda usando un CursorLoader. El resultado del CursorLoader es el esperado. Asi que no hay problemas en la query. 

Sin embargo, cuando el cursor, realiza el swapcursor, y pasa al adapter etc.. éste no me refresca la vista, y no estoy viendo porque....

Si me podeis hechar una manuca, seria lo suyo ^^  Gracias de antemano!

Os dejo código:

Searchview
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
    public boolean onQueryTextChange(String newText) {
        mSearchString = newText;
        doFilterAsync();
        return true;
    }

    public boolean onQueryTextSubmit(String query) {
        mSearchString = query;
       
        doFilterAsync();
        return true;
    }
};

doFilterAsync --> dofilter()
public synchronized void doFilter() {

       //lMgr =getSupportLoaderManager();

        if (mChatPagerAdapter == null) {

            mChatPagerAdapter = new ChatViewPagerAdapter(getSupportFragmentManager());

            mChatPager.setAdapter(mChatPagerAdapter);

            //mLoaderCallbacks = new MyLoaderCallbacks();
            lMgr.initLoader(CHAT_LIST_LOADER_ID, null, loaderCallbacks);
        } else {

            if (!mAwaitingUpdate) {
                mAwaitingUpdate = true;
                mHandler.postDelayed(new Runnable() {

                    public void run() {

                        lMgr.restartLoader(CHAT_LIST_LOADER_ID, null, loaderCallbacks);
                        mAwaitingUpdate = false;
                    }
                }, 1000);
            }
            mSearch = false;
        }
    }

LoaderCallback

loaderCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() {

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

                StringBuilder buf = null;

                if (mSearchString != null) {
                    buf = new StringBuilder();
                    buf.append('(');
                    buf.append("contacts.username");
                    buf.append(" LIKE ");
                    android.database.DatabaseUtils.appendValueToSql(buf, "%" + mSearchString + "%");
                    buf.append(" OR ");
                    buf.append("contacts.nickname");
                    buf.append(" LIKE ");
                    android.database.DatabaseUtils.appendValueToSql(buf, "%" + mSearchString + "%");
                    buf.append(')');
                }
                CursorLoader loader = new CursorLoader(NewChatActivity.this,
                        Imps.Contacts.CONTENT_URI_CHAT_CONTACTS, ChatView.CHAT_PROJECTION,
                        buf == null ? null : buf.toString(), null, Imps.Contacts.DEFAULT_SORT_ORDER);

                loader.setUpdateThrottle(100L);

                return loader;
            }

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

                mChatPagerAdapter.swapCursor(newCursor);

                updateChatList();

                if (getIntent() != null)
                    resolveIntent(getIntent());

                if (mRequestedChatId >= 0) {
                    if (showChat(mRequestedChatId)) {
                        mRequestedChatId = -1;
                    }
                }

            }

            @Override
            public void onLoaderReset(Loader<Cursor> loader) {
                mChatPagerAdapter.swapCursor(null);
            }
        };

ChatViewPagerAdapter

 public class ChatViewPagerAdapter extends DynamicPagerAdapter {
        Cursor mCursor;
        boolean mDataValid;

        public ChatViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public Cursor getCursor() {
            return mCursor;
        }

        public Cursor swapCursor(Cursor newCursor) {
            if (newCursor == mCursor) {
                return null;
            }
            Cursor oldCursor = mCursor;
            mCursor = newCursor;
            
            Log.v("CHSR", android.database.DatabaseUtils.dumpCursorToString(mCursor));

            if (newCursor != null) {
                mDataValid = true;
                if(mSearch != true) {
                refreshChatViews();  
                }

            } else {
                mDataValid = false;
            }
            notifyDataSetChanged();
            return oldCursor;
        }

        @Override
        public int getCount() {
            if (mCursor != null)
                return mCursor.getCount() + 1;
            else
                return 0;
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                if (mContactList == null)
                    mContactList = new ContactListFragment();

                return mContactList;
            } else {
                int positionMod = position - 1;

                mCursor.moveToPosition(positionMod);
                long contactChatId = mCursor.getLong(ChatView.CONTACT_ID_COLUMN);
                String contactName = mCursor.getString(ChatView.USERNAME_COLUMN);
                long providerId = mCursor.getLong(ChatView.PROVIDER_COLUMN);

                return ChatViewFragment.newInstance(contactChatId, contactName, providerId);
            }
        }

        @Override
        public int getItemPosition(Object object) {

            if (object instanceof ChatViewFragment) {
                ChatViewFragment cvFrag = (ChatViewFragment) object;
                ChatView view = cvFrag.getChatView();
                long viewChatId = view.mLastChatId;
                int position = PagerAdapter.POSITION_NONE;

                // TODO: cache positions so we don't scan the cursor every time
                if (mCursor != null && mCursor.getCount() > 0) {
                    mCursor.moveToFirst();

                    int posIdx = 1;

                    do {
                        long chatId = mCursor.getLong(ChatView.CHAT_ID_COLUMN);

                        if (chatId == viewChatId) {
                            position = posIdx;
                            break;
                        }

                        posIdx++;
                    } while (mCursor.moveToNext());

                }
                return position;

            } else if (object instanceof ContactListFragment) {
                return 0;

            } else {
                throw new RuntimeException("got asked about an unknown fragment");
            }
        }

        @Override
        public CharSequence getPageTitle(int position) {

            if (position == 0 || mCursor == null) {
                if (mShowChatsOnly)
                    return getString(R.string.title_chats);
                else
                    return getString(R.string.contacts);
            } else {
                int positionMod = position - 1;

                mCursor.moveToPosition(positionMod);
                if (!mCursor.isAfterLast()) {

                    String nickname = mCursor.getString(ChatView.NICKNAME_COLUMN);
                    int presence = mCursor.getInt(ChatView.PRESENCE_STATUS_COLUMN);
                    int type = mCursor.getInt(ChatView.TYPE_COLUMN);

                    BrandingResources brandingRes = mApp.getBrandingResource(mCursor
                            .getInt(ChatView.PROVIDER_COLUMN));

                    SpannableString s = null;

                    Drawable statusIcon = null;

                    if (Imps.Contacts.TYPE_GROUP == type) {
                        s = new SpannableString(nickname);
                    } else {
                        s = new SpannableString("+ " + nickname);
                        statusIcon = brandingRes.getDrawable(PresenceUtils
                                .getStatusIconId(presence));
                        statusIcon.setBounds(0, 0, statusIcon.getIntrinsicWidth(),
                                statusIcon.getIntrinsicHeight());
                        s.setSpan(new ImageSpan(statusIcon), 0, 1,
                                SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

                    }

                    return s;

                } else
                    return "";//unknown title
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, int pos) {
            Object item = super.instantiateItem(container, pos);
            if (pos > 0) {
                ChatViewFragment frag = (ChatViewFragment) item;
            }
            return item;
        }

        @Override
        public void destroyItem(ViewGroup container, int pos, Object object) {

            super.destroyItem(container, pos, object);
        }

        public ChatView getChatViewAt(int pos) {
            if (pos > 0) {
                ChatViewFragment frag = ((ChatViewFragment) getItemAt(pos));

                if (frag != null)
                    return frag.getChatView();
            }

            return null; //this can happen if the user is quickly closing chats; just return null and swallow the event
            //throw new RuntimeException("could not get chat view at " + pos);
        }
    }

    


DEntro del swap salta a dos metodos diferentes que llevan al mismo sitio:
public void refreshChatViews() {
        mChatPagerAdapter.notifyDataSetChanged();
    }

notifyDataSetChanged();


Ambos me llevan al notifyDataSetChanged de 
DynamicPagerAdapter 

@Override
    public void notifyDataSetChanged() {
        // Fragments may have moved.  Regenerate the fragment list.
        ArrayList<Fragment> old = mFragments;
        ArrayList<Fragment.SavedState> oldState = mSavedState;
        mFragments = new ArrayList<Fragment>();
        mSavedState = new ArrayList<Fragment.SavedState>();
        for (int i = 0 ; i < old.size() ; i++) {
            Fragment frag = old.get(i);
            if (frag != null) {
                int position = getItemPosition(frag);
                if (position == POSITION_NONE)
                    continue;
                if (position == POSITION_UNCHANGED)
                    position = i;
                while (mFragments.size() <= position) {
                    mFragments.add(null);
                    mSavedState.add(null);
                }
                mFragments.set(position, frag);
                if (oldState.size() > i)
                    mSavedState.set(position, oldState.get(i));
            }
        }

        // The list must never shrink because other methods depend on it
        while (mFragments.size() < old.size()) {
            mFragments.add(null);
            mSavedState.add(null);
        }

        super.notifyDataSetChanged();
    }





Se que es todo un poco engorroso. pero llevo muchos días dándole vueltas al asunto, y no se por donde solucionarlo.
Si necesitáis mas código o cualquier cosa avisadme ^^

Gracias por todo de nuevo!!!!
Reply all
Reply to author
Forward
0 new messages