Search code examples
androidandroid-listfragment

How to pass intent from ListFragment1 to ListFragment2


I have a Class1 extending ListFragment1.
I have a Class2 extending ListFragment2.

I'm currently passing an Intent like this inside OnItemClickListener.

            Intent intent = new Intent(getActivity().getApplicationContext(), ListFragment2.class);
            intent.putExtra("id", "1");
            getActivity().startActivity(intent);

        }

However, i get this exception:

java.lang.ClassCastException: com.abc.xyz.Class2 cannot be cast to android.app.Activity

Please help ! :(


Solution

  • First you should know:

    • You are calling startActivity(intent) and your Intent is pointing to a Fragment.
    • You cannot pass intents to your Fragment like that since Fragments are not App Components.
    • Communcation between Fragments should be between the Activity holding them.

    Best Solution:

    Pass your data from Class1 to your Activity and then send it to Class2, this link provides you exactly this, no more or less code: http://developer.android.com/training/basics/fragments/communicating.html
    It's a must read when you want to communicate between fragments.