2

I am trying to use an Activity to hold 2 Fragments at a time. One of the fragments is, let's call it the 1st fragment, being displayed holds an OnClickListener. I would like that listener to call a method within the Activity which contains the Fragments that will swap the 2nd Fragment with another one. The fragments are all added programmatically. I have the following code which seem's to give me an error.

I am new to android so the code is sloppy and mostly meant for testing so I will try to explain what is happening.

This is the code for the Activity which holds the fragments. The activity manages to add to Fragments successfully, however, upon pushing the all_jokes text view an error is received.

    package com.Ayman.jokeit;

    import android.app.Activity;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;


    public class BrowseActivity extends FragmentActivity{
        AllJokes afrag;
        OneLiners olfrag;
        selectFragment sfrag ;
        RaceJokes rfrag;
        YoMammaJokes yfrag ;
        LongJokes lfrag ;
        FragmentTransaction stransaction;
        FragmentTransaction jtransaction;
        FragmentTransaction atransaction;
        FragmentManager jmanager;
        FragmentManager smanager;
        FragmentManager amanager;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);



            afrag = new AllJokes();
            olfrag = new OneLiners();
            sfrag = new selectFragment();
            rfrag = new RaceJokes();
            yfrag = new YoMammaJokes();
            lfrag = new LongJokes();

            setContentView(R.layout.browse);

            //Creats object for fragments


            //steps for adding fragment to view
            smanager = getFragmentManager();
            jmanager = getFragmentManager();

            stransaction = smanager.beginTransaction();
            stransaction.add(R.id.browse_layout, sfrag, "selectFragment");
            stransaction.commit();


            //steps for adding fragment to view

            jtransaction = jmanager.beginTransaction();
            jtransaction.add(R.id.browse_layout, olfrag, "onelinerFragment");
            jtransaction.commit();

        }
        public void addAllJokes(){
        afrag = new AllJokes();
        atransaction = amanager.beginTransaction();
        atransaction.replace(R.id.browse_layout, afrag, "afrag");
        atransaction.commit();

        }

    }

This is the code for the Fragment from which the OnClickListener is used.

The OnClickListener calls the method all_jokes within the fragment (code below) which refers to the the addalljokes method within the activity (code above). This seems to result in an error. I have tried multiple potential solutions to no avail. Please help find a solution and if possible explain the reasoning. (None of the OnClickListeners are meant to work except for the All_Jokes one.

package com.Ayman.jokeit;

import com.Ayman.jokeit.AllJokes;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Fragment;
import android.widget.TextView;

public class selectFragment extends Fragment {
    BrowseActivity browseActivity = new BrowseActivity();
    private TextView all_jokes;
    private TextView one_liners;
    private TextView yo_mamma_jokes;
    private TextView race_jokes;
    private TextView long_jokes;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View selectFragmentView = inflater.inflate(R.layout.select_view, container, false);
        all_jokes = (TextView) selectFragmentView.findViewById(R.id.all_TextView);
        one_liners = (TextView) selectFragmentView.findViewById(R.id.one_Liners_TextView);
        yo_mamma_jokes = (TextView) selectFragmentView.findViewById(R.id.yo_Mama_Jokes_TextView);
        race_jokes = (TextView) selectFragmentView.findViewById(R.id.race_Jokes_TextView);
        long_jokes = (TextView) selectFragmentView.findViewById(R.id.long_Jokes_TextView);


        all_jokes.setOnClickListener(new View.OnClickListener() {

            @Override


            public void onClick(View v) {
                all_jokes();

            }
        });

        one_liners.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                one_liners();

            }
        });

        yo_mamma_jokes.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                yo_mamma_jokes();

            }
        });

        race_jokes.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                race_jokes();

            }
        });

        long_jokes.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                long_jokes();

            }
        });




        return selectFragmentView;

        }


    public void all_jokes(){
        BrowseActivity browseActivity = (BrowseActivity) getActivity();
        browseActivity.addAllJokes();
    }

    public void one_liners(){

    }

    public void yo_mamma_jokes(){

    }

    public void race_jokes(){

    }
    public void long_jokes(){


    }
}

Thank you in advanced.

Edit*

The following error is recieved

01-15 15:01:16.323    6393-6393/com.Ayman.jokeit E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.Ayman.jokeit, PID: 6393
    java.lang.NullPointerException
            at com.Ayman.jokeit.BrowseActivity.addAllJokes(BrowseActivity.java:61)
            at com.Ayman.jokeit.selectFragment.all_jokes(selectFragment.java:90)
            at com.Ayman.jokeit.selectFragment$1.onClick(selectFragment.java:39)
            at android.view.View.performClick(View.java:4424)
            at android.view.View$PerformClick.run(View.java:18383)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4998)
            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:777)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
            at dalvik.system.NativeStart.main(Native Method)
Ayman Elmubark
  • 959
  • 1
  • 6
  • 11

2 Answers2

2

You can use an Interface to provide communication between your fragment and the associating Activity. You should cast the Interface to the activity in the onAttach method of the first fragment. (See this link for more information)

The associating Activity should implement that interface e.g.

public interface FragmentSwitcher {
  void switchSecondFragment();
}

In the method callback of that interface (in the Activity) perform an replace fragment transaction. That replaces the secondfragment with another one.

Any questions? ask below

Tobrun
  • 18,291
  • 10
  • 66
  • 81
  • This seems to be what I was looking for. I will let you know how it works out. Also, is there any particular reason as to why an interface is required? – Ayman Elmubark Jan 20 '14 at 10:50
  • @AymanElmubark two fragments should not communicate directly with each other. also fragment is hosted by a activity. http://developer.android.com/training/basics/fragments/communicating.html. Your `browse_layout` is the container to which you add or replace fragments – Raghunandan Jan 20 '14 at 10:53
  • It is not required, but it is a better practise. It decouples the logic. You are also able to use getActivity and cast that activity to the correct one. But this could lead to occasional nullpointer and I haven't had this problem with an interface. If your problem remains after imlementing this pattern, update your code and I will try to run it myself. Kind regards – Tobrun Jan 20 '14 at 11:37
0
atransaction = amanager.beginTransaction();

amanager is not instantiated. and you are using it... null pointer might be coz of this line atransaction.replace(R.id.browse_layout, afrag, "afrag");... check this out

khubaib
  • 535
  • 4
  • 12