Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: error with on fragment interaction Listener

I have been looking at stackoverflow to solve my problem and found something pretty good, but it does not work for me or I am to stupid to see it (How to implement OnFragmentInteractionListener)

I want to place a fragment inside a Frame, so I created it and so on. I have to implenet an interface and its method. I (think) I did it, but my App crashes everytime...

*Edit: My App crashes, when I call openHome or openRecommended, the onCreate method works, I get these errors, but everything is beeing displayed correctly.

This is my code:

MainActivity.java

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;


public class MainActivity extends Activity implements HomeFragment.OnFragmentInteractionListener, RecommendedFragment.OnFragmentInteractionListener
{
    FragmentTransaction fragmentTransaction;
    HomeFragment homeFragment;

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

        homeFragment = new HomeFragment();

        getFragmentManager().beginTransaction().add(R.id.mainFrame, homeFragment).commit();
    }

    protected void openHome(View view)
    {
        /*Intent homeIntent = new Intent(this, HomeFragment.class);
        startActivity(homeIntent);

        homeFragment = new HomeFragment();
        getFragmentManager().beginTransaction().replace(R.id.mainFrame, homeFragment).commit();*/

        System.out.println("Success");
    }

    public void openRecommended(View view)
    {
        Intent recommendedIntent = new Intent(this, RecommendedFragment.class);
        startActivity(recommendedIntent);

        RecommendedFragment recommendedFragment = new RecommendedFragment();
        getFragmentManager().beginTransaction().replace(R.id.mainFrame, recommendedFragment).commit();
    }

    @Override
    public void onFragmentInteractionHome(Uri uri)
    {

    }

    @Override
    public void onFragmentInteractionRecommended(Uri uri)
    {

    }
}

HomeFragment.java

import android.app.Activity;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link HomeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment
{
    private OnFragmentInteractionListener mListener;


    public static HomeFragment newInstance()
    {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    public HomeFragment()
    {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri)
    {
        if (mListener != null)
        {
            mListener.onFragmentInteractionHome(uri);
        }
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
        try
        {
            mListener = (OnFragmentInteractionListener) activity;
        }
        catch (ClassCastException e)
        {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach()
    {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener
    {
        // TODO: Update argument type and name
        public void onFragmentInteractionHome(Uri uri);
    }
}

RecommendedFragment looks the same, except some methods have a different name.

I always get this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.domain.app/com.domain.app.MainActivity}: java.lang.ClassCastException: com.domain.app.MainActivity@b1d296b0 must implement OnFragmentInteractionListener at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.ClassCastException: com.domain.app.MainActivity@b1d296b0 must implement OnFragmentInteractionListener at com.domain.app.HomeFragment.onAttach(HomeFragment.java:74) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:849) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062) at android.app.BackStackRecord.run(BackStackRecord.java:684) at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447) at android.app.Activity.performStart(Activity.java:5240) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)             at android.app.ActivityThread.access$800(ActivityThread.java:135)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)             at android.os.Handler.dispatchMessage(Handler.java:102)             at android.os.Looper.loop(Looper.java:136)             at android.app.ActivityThread.main(ActivityThread.java:5017)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:515)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)             at dalvik.system.NativeStart.main(Native Method)

I really need help here, I am stuck for hours...

John

like image 391
JRsz Avatar asked Sep 09 '14 21:09

JRsz


People also ask

How to pass Listener to fragment?

You need to call an extra method every time you want to instantiate the Fragment . You can't guarantee that mListener is set at any time. You may need to pepper your Fragment code with null checks. You need to be careful to make sure the listener remains set after lifecycle events such as screen rotation.

What is OnFragmentInteractionListener Android?

OnFragmentInteractionListener is the default implementation for handling fragment to activity communication. This can be implemented based on your needs.

How pass data from fragment to activity Kotlin?

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.


1 Answers

I’ve removed useless references and everything related with RecommendedFragment class. If you post it I will update my answer.

I’ve tested it and it works. But try to explain what is the meaning of openHome() method, because it is never used based on your code, and nevertheless you say that the app crashes when you call it.

I added this method to the interface because it seems to me the most logical thing to do.

  //MainActivity

public class MainActivity extends Activity implements HomeFragment.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getFragmentManager().beginTransaction()
                .add(R.id.mainFrame, new HomeFragment())
                .commit();
    }

    @Override
    public void openHome(View view) {
        System.out.println("Success");
    }

    @Override
    public void onFragmentInteractionHome(Uri uri) {
        Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
    }

}

//HomeFragment

public class HomeFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteractionHome(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
            mListener.onFragmentInteractionHome(Uri.parse("doWhatYouWant"));
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        public void onFragmentInteractionHome(Uri uri);
        public void openHome(View view);
    }

}
like image 59
Víctor Albertos Avatar answered Oct 19 '22 17:10

Víctor Albertos