androidandroid-activityfragment

Passing Data Between Fragments to Activity


I need to pass data between from 5 fragments to one Activity, those fragments send data one after another when i reach 5'th fragment then i need to store all 5 fragments data how can we do this. any idea is Great.enter image description here


Solution

  • Pass data from each fragment to activity, when activity gets all data then process it. You can pass data using interfaces.

    Fragment:

    public class Fragment2 extends Fragment {
    
      public interface onSomeEventListener {
        public void someEvent(String s);
      }
    
      onSomeEventListener someEventListener;
    
      @Override
      public void onAttach(Activity activity) {
        super.onAttach(activity);
            try {
              someEventListener = (onSomeEventListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
            }
      }
    
      final String LOG_TAG = "myLogs";
    
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment2, null);
    
        Button button = (Button) v.findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
            someEventListener.someEvent("Test text to Fragment1");
          }
        });
    
        return v;
      }
    }
    

    Activity:

    public class MainActivity extends Activity implements onSomeEventListener{
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            Fragment frag2 = new Fragment2();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.add(R.id.fragment2, frag2);
            ft.commit();
        }
    
      @Override
      public void someEvent(String s) {
          Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1);
          ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
      }
    }