Vince Vince - 2 months ago 260
Android Question

How to refresh recyclerview?

I made a mediaplayer app with fragments; Songs, Albums, Artist, Genres, Playlist

This is the code in one of my fragments, i'll show Artists as an example

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_tab3, container, false);
recyclerViewArtists = rootView.findViewById(R.id.recyclerViewArtists);

initRecyclerView();

return rootView;
}

private void initRecyclerView(){
items = Main.songs.getArtists();

if ((items != null) && (! items.isEmpty())) {
adapter = new Adapter(getContext(), items);
recyclerViewArtists.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerViewArtists.setHasFixedSize(true);
recyclerViewArtists.setAdapter(adapter);
Log.i(TAG, "Artists found in list!");

recyclerViewArtists.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 + " " + items.get(position) , Toast.LENGTH_SHORT).show();
if (! Main.songs.isInitialized()){
return;
}
String selectedArtist = items.get(position);

Main.musicList = Main.songs.getSongsByArtist(selectedArtist);
Intent intent = new Intent(getContext(), ListSongsActivity.class);
intent.putExtra("title", selectedArtist);
startActivity(intent);
}
}));

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


Inside my initRecyclerView() method i have an arraylist called 'items' which holds the songs artists.
Main.songs.getArtist -> Main is a class which holds a public static arraylist called 'songs' and the arraylists uses a model class Song which holds setters and getters ( getArtists(); )

Now when the user clicks on an artist, another activity starts ListSongsActivity.java

This is the code in the class ListSongsActivity.java

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_songs_layout);

//Holds all the songs in a scrollable list.
recyclerViewListSongs = findViewById(R.id.recyclerViewListSongs);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();

// 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(this, Main.musicList);
recyclerViewListSongs.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerViewListSongs.setHasFixedSize(true);
recyclerViewListSongs.setAdapter(allSongsAdapter);
allSongsAdapter.notifyDataSetChanged();
}

mToolbar = findViewById(R.id.mToolbar);
setSupportActionBar(mToolbar);

if ((getSupportActionBar() != null) && (bundle != null)) {
getSupportActionBar().setTitle((String) bundle.get("title"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home_up);
}

recyclerViewListSongs.addOnItemTouchListener(new OnItemClickListeners(getApplicationContext(), new OnItemClickListeners.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
playAudio(position);
Toast.makeText(getApplicationContext(), "You Clicked position: " + position + Main.musicList.get(position).getData(), Toast.LENGTH_SHORT).show();
}
}));
}

private void playAudio(int songIndex) {
//Check if service is active
if (!MediaPlayerService.musicBound) {
StorageUtil storageUtil = new StorageUtil(this);
storageUtil.storeSong(Main.musicList);
storageUtil.storeSongIndex(songIndex);

Intent playerIntent = new Intent(this, MediaPlayerService.class);
startService(playerIntent);
bindService(playerIntent, Main.musicConnection, Context.BIND_AUTO_CREATE);
} else {
//Store new songIndex in mSharedPreferences
StorageUtil storageUtil = new StorageUtil(this);
storageUtil.storeSong(Main.musicList);
storageUtil.storeSongIndex(songIndex);

//MediaService is active
//Send media with BroadcastReceiver
Intent broadCastReceiverIntent = new Intent(broadCast_PlAY_NEW_SONG);
sendBroadcast(broadCastReceiverIntent);
}
}


In this class i store songList and songIndex where songlist = the arraylists that holds song information and songindex = clicked position

public class StorageUtil {
private final String STORAGE = "com.vince_mp3player.STORAGE";
private SharedPreferences mSharedPreferences;
private Context context;
private SharedPreferences.Editor mEditor;



public StorageUtil(Context context){
this.context = context;
}

public void storeSong(List<Song> list){
mSharedPreferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
mEditor.putString("songList", json);
mEditor.apply();
}

public ArrayList<Song> getSongs(){
mSharedPreferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = mSharedPreferences.getString("songList", null);
Type type = new TypeToken<List<Song>>(){
}.getType();
return gson.fromJson(json, type);
}

public void storeSongIndex(int index) {
mSharedPreferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEditor.putInt("songIndex", index);
mEditor.apply();
}

public int loadSongIndex() {
mSharedPreferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
return mSharedPreferences.getInt("songIndex", -1);//return -1 if no data found
}

public void clearCachedAudioPlaylist() {
mSharedPreferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEditor.clear();
mEditor.apply();
}
}


Here my problem starts, so say we pick Artist A from the list --> ListSongsActivity starts --> ex. shows 3 songs by Artists A.

Then when i go back by pressing the back button, and pick Artist B and click on one of those songs, it still plays songs by Artists A.
All my recyclerviews in my app are for some reason overwritten with only songs by Artist A.

Even in my first fragment which displays all songs, when i click on a song there it only plays songs by the artist i picked in my artist tab and crashes when i pick another song when the position is over at 3.

How can i update my recyclerviews when i click on the back button?

If you don't understand my post, i'll add code to dropbox, github so you can test it yourself.

Thanks in advance,

Vince

Answer Source

It looks like when you're sending the broadcast to MediaPlayerService, the songList variable is still set to the initial song when the service was created. I was able to get it working by first updating songList in NewSongBroadcastReceiver of MediaPlayerService.java:

private BroadcastReceiver NewSongBroadCastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        songList = new StorageUtil(getApplicationContext()).getSongs();
        songIndex = new StorageUtil(getApplicationContext()).loadSongIndex();
        if (songIndex != -1 && songIndex < songList.size()){
            activeSong = songList.get(songIndex);
        }else{
            stopSelf();
        }
        stopSong();
        mediaPlayer.reset();
        initMediaPlayer();
        updateMetaData();
        NotificationBuilder(PlaybackStatus.PLAYING);
    }
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download