I try to simply replace one custom fragment by another one. The first custom fragment is called MenuFragment and extends ListFragment. When the activity is created (onCreate) I insert it in a layout (called layout_container) I’ve defined in XML :
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
MenuFragment menufragment = new MenuFragment();
fragmentTransaction.add(R.id.layout_container, menufragment);
fragmentTransaction.commit();
Here, I’ve got no problem.
Then I want to replace it with the second fragment called AlbumsFragment (which also extends ListFragment) when the user clicks on something. In my onClick event I put :
AlbumsFragment albumsfragment = new AlbumsFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.layout_container, albumsfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Here the new fragment is well displayed and replaces the menufragment but at the same time the app crashes and the LogCat says :
E/AndroidRuntime(25105): java.lang.ClassCastException: com.music.musicapp.AlbumsFragment cannot be cast to com.music.musicapp.MenuFragment
I’m only using and targeting Api level 15 and so I don’t use the Android Support Package.
EDIT :
Here is my Album fragment code, very simple, it is just a list with two items “Album1” and “Album2”. I can see these two items after the click is performed, but immediatly the app crashes.
package com.music.musicapp;
import java.util.ArrayList;
import android.app.ListFragment;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class AlbumsFragment extends ListFragment {
// declare the array list
ArrayList<String> array = new ArrayList<String>();
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Fill up Array
array.add("album1");
array.add("album2");
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, array));
}
}
Problem solved,
I had another method which needed the
MenuFragmentand thus, when this fragment was replaced byAlbumsFragment, this method was making the app crash because it refered to a no more existent fragment.So the problem was not in the code posted, sorry. It is important to consider the impact of replacing a fragment, and be careful when referring to it (check if it is still on the UI or if it has been already sent to the back stack, etc…).
Thanks for your answers and sorry for not having seen that my problem wasn’t there (but when the project’s getting complex, is hard to always see from where the problem comes :/).