简体   繁体   中英

Recyclerview not updating data when filtered with searchview

So i have a searchview in my tabbed activity with 5 fragments and when i search for something in fragment 1 (Tab1) it filters my recyclerview correctly with the searched song.

But it still plays the song from the list with all my songs and not the song from filtered list.

So for example in fragment 1 i have 5 songs and i search for the 5th song, but when i try to play the 5th song it still plays my first song.

So my recyclerview is not updating my arraylist with the filtered arraylist.

Main.musicList is a global arraylist from another activity which stores all songs from device.

StorageUtil is a helper class which stores my arraylist with the songs and song index so i can play the song.

How can i do this?

Thanks,

Activity

@Override
public boolean onQueryTextSubmit(String query) {
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    PagerAdapter pagerAdapter = mViewPager.getAdapter();
    for(int i = 0; i < pagerAdapter.getCount(); i++) {

        Fragment viewPagerFragment = (Fragment) mViewPager.getAdapter().instantiateItem(mViewPager, i);
        if(viewPagerFragment != null && viewPagerFragment.isAdded()) {

            if (viewPagerFragment instanceof Tab1){
                Tab1 tab1 = (Tab1) viewPagerFragment;
                if (tab1 != null){
                    tab1.beginSearch(newText); // Calling the method beginSearch of Tab1
                    if (newText == null || newText.trim().isEmpty()) {
                        tab1.resetSearch();
                    }
                }
            }else if (viewPagerFragment instanceof Tab2){
                Tab2 tab2 = (Tab2) viewPagerFragment;
                if (tab2 != null){
                    //tab2.beginSearch(query); // Calling the method beginSearch of Tab2
                }
            }else if (viewPagerFragment instanceof Tab3){
                Tab3 tab3 = (Tab3) viewPagerFragment;
                if (tab3 != null){
                    //tab3.beginSearch(query); // Calling the method beginSearch of Tab3
                }
            }else if (viewPagerFragment instanceof Tab4){
                Tab4 tab4 = (Tab4) viewPagerFragment;
                if (tab4 != null){
                    //tab4.beginSearch(query); // Calling the method beginSearch of Tab4
                }
            }else if (viewPagerFragment instanceof Tab5){
                Tab5 tab5 = (Tab5) viewPagerFragment;
                if (tab5 != null){
                    //tab5.beginSearch(query); // Calling the method beginSearch of Tab5
                }
            }
        }
    }        
    return false;

Fragment (Tab1)

private void initRecyclerView() {
    Main.musicList = Main.songs.songs;
    // Connects the song list to an adapter
    // (thing that creates several Layouts from the song list)
    if ((Main.musicList != null) && (!Main.musicList.isEmpty())) {
        allSongsAdapter = new AllSongsAdapter(getContext(), Main.musicList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerViewSongs.setLayoutManager(linearLayoutManager);
        recyclerViewSongs.setHasFixedSize(true);
        recyclerViewSongs.setAdapter(allSongsAdapter);
        Log.i(TAG, "Songs found in list!");

        recyclerViewSongs.addOnItemTouchListener(new OnItemClickListeners(getContext(), new OnItemClickListeners.OnItemClickListener() {
            @TargetApi(Build.VERSION_CODES.O)
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(getContext(), "You Clicked position: " + position, Toast.LENGTH_SHORT).show();
                //Start playing the selected song.
                playAudio(position);

            }
        }));

    } else {
        Log.i(TAG, "No songs found in list!");
    }
}

public void beginSearch(String query) {
    Log.e("QueryFragment", query);
    allSongsAdapter.getFilter().filter(query);
}

public void resetSearch(){
    allSongsAdapter = new AllSongsAdapter(getContext(), Main.musicList);
    recyclerViewSongs.setAdapter(allSongsAdapter);
}

private void playAudio(int songIndex) {
    //MediaService is active
    //Store songList and songIndex in mSharedPreferences
    StorageUtil storageUtil = new StorageUtil(getContext());
    storageUtil.storeSong(Main.musicList);
    storageUtil.storeSongIndex(songIndex);
    //Send media with BroadcastReceiver
    Intent broadCastReceiverIntent = new Intent(Constants.ACTIONS.BROADCAST_PlAY_NEW_SONG);
    if (getActivity() != null) {
        getActivity().sendBroadcast(broadCastReceiverIntent);
    }
    //Send media with BroadcastReceiver
    Intent broadCastReceiverIntentUpdateSong = new Intent(Constants.ACTIONS.BROADCAST_UPDATE_SONG);
    if (getActivity() != null) {
        getActivity().sendBroadcast(broadCastReceiverIntentUpdateSong);
    }
}

Adapter with searchview filter

public Filter getFilter() {
    if (valueFilter == null) {
        valueFilter = new ValueFilter();
    }
    return valueFilter;
}

private class ValueFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String str = constraint.toString().toUpperCase();
        Log.e("constraint", str);
        FilterResults results = new FilterResults();

        if (constraint != null && constraint.length() > 0) {
            ArrayList<Song> filterList = new ArrayList<>();
            for (int i = 0; i < filteredMusicList.size(); i++) {
                if ((filteredMusicList.get(i).getTitle().toUpperCase())
                        .contains(constraint.toString().toUpperCase())) {
                    Song song = filteredMusicList.get(i);
                    filterList.add(song);
                }
            }
            results.count = filterList.size();
            results.values = filterList;
        } else {
            results.count = filteredMusicList.size();
            results.values = filteredMusicList;
        }
        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        musicList = (ArrayList<Song>) results.values;
        notifyDataSetChanged();
    }
}

Edit (Working but not sure if it's the right way to do it)

In my adapters i call my helper class StorageUtil that stores my music list and i store the filtered musiclist then i made a broadcastreceiver which sends a broadcast that my musiclist is updated.

   @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        musicList = (ArrayList<Song>) results.values;
        notifyDataSetChanged();
        StorageUtil storageUtil = new StorageUtil(context);
        storageUtil.storeSong(musicList);

        Intent broadCastReceiverIntent = new Intent(Constants.ACTIONS.BROADCAST_UPDATE_MUSICLIST);
        context.sendBroadcast(broadCastReceiverIntent);
    }

And in my fragment i set the musiclist to the filtered list

  //Register BroadCastReceiver UPDATE_SONG
private void registerUpdateMusicListBroadCastReceiver(){
    IntentFilter intentFilter = new IntentFilter(Constants.ACTIONS.BROADCAST_UPDATE_MUSICLIST);
    if (getActivity() != null) {
        getActivity().registerReceiver(UpdateMusicListBroadCastReceiver, intentFilter);
    }

}

private BroadcastReceiver UpdateMusicListBroadCastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        StorageUtil storageUtil = new StorageUtil(getContext());
        Main.musicList = storageUtil.getSongs();
    }
};

The problem is how to you get the music index. There is only one item in list when you filter the music list. So position of it always is 0 in the list. You should get index of selected item in the real music list (Main.musicList).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM