mohammad tofi
mohammad tofi

Reputation: 207

How I can pass data between two fragments?

I have two activity and two fragments : detialActivity and detialActivityFragment, mainActivity and mainActivityFragment. How i can pass data between detialActivityFragment and mainActivityFragment. When I try to pass data show me Exception: java.lang.NullPointerException I maked interface:

  public interface OnButtonPressListener { 
        public void onButtonPressed(String msg);
    }

Inside class mainActivityFragment:

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

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_main, container, 
        false);
        listMovie = (GridView) root.findViewById(R.id.gridview_movie);

        listMovie.setOnItemClickListener(new  AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                buttonListener.onButtonPressed("hi");
            }
        });
        return root;
    }

Inside class detialActivityFragment:

void setMessage(String msg){
   TextView txt=(TextView)root.findViewById(R.id.titleDetialMovie);
   txt.setText(msg);
}

inside class detialActivity:

 @Override
    public void onButtonPressed(String msg) {
        DetialActivityFragment Obj=(DetialActivityFragment)                   
   getSupportFragmentManager().findFragmentById(R.id.detialActivityFragment);
        Obj.setMessage(msg);
    }

Upvotes: 1

Views: 99

Answers (3)

Muhammad Ali
Muhammad Ali

Reputation: 522

You should not call method like this. Rather pass the data to constructor of Fragment and use it over there.

Upvotes: 1

silverFoxA
silverFoxA

Reputation: 4659

In order to pass data between two fragments you should use Bundle refer the google docs for more information.

Fragment-A:----
Bundle bundle= new Bundle();
bundle.putString("Key",thevalue);
fragment.setArguments(bundle);
Fragment-B:----
Bundle bundle=getArguments();
String value=bundle.getString("key");

Thats the rough example of what to do.

Upvotes: 0

Anitha Manikandan
Anitha Manikandan

Reputation: 1170

Its almost like data passing between activities. From mainActivity pass bundle with the string value and get the same in detailedActivity and sent them same to detailedFragment to display the name.

Upvotes: 0

Related Questions