-1

I know that data can be transferred from an Activity to another Fragment using Bundle. I have done some research and I found out that Bundle works only when the Activity commits a Fragment transaction to the Fragment where the data has to be send.

My question is: Is there any way by which I can send data from the activity to another fragment without committing fragment transaction?

I have attached an image which explains the scenario:
Problem Scenario

Here is the Main Activity (User.java):

  protected void onCreate(Bundle savedInstanceState)
{
    ActionBar ab = getSupportActionBar();
    ab.hide();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);

    TextView txt = (TextView) findViewById(R.id.textView5);
    Intent intent = getIntent();
    String Name  = intent.getStringExtra("UserName");
    txt.setText("Logged in as "+Name);

    Bundle bundle = new Bundle();
    bundle.putString("message", Name );
    user_profile up = new user_profile(); //This is the Fragment where I want to send data(which is "Name")
    up.setArguments(bundle); 

    user_home uh = new user_home(); //This is the Fragment that is added
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.fragment_container,uh);
    ft.commit();
}   

Here is the Second Activity where I want to send data(Known as "user_profile.java")

Bundle bundle2 = this.getArguments();
    String N = bundle2.getString("message");
    Toast.makeText(getContext(), N , Toast.LENGTH_SHORT).show();    

Is there any way by which I can send between activity and fragment other than using bundle?

Tony Mathew
  • 191
  • 2
  • 12

2 Answers2

1

I'm not sure what kind of data you want to pass exactly.. but this could help you https://github.com/greenrobot/EventBus

Moulesh
  • 2,762
  • 1
  • 22
  • 32
  • Its a string type data – Tony Mathew Aug 09 '16 at 11:00
  • Using event bus you can send any kind of data... if it is just single string value or static values then you can go for options like shared preferences, sqlite etc but you have a server call and should pass too many strings or whole object i think you can try eventbus – Moulesh Aug 09 '16 at 11:09
0

What I do in such situation is

  1. Create a interface in Activity

  2. Implement that interface in the Fragment

  3. Pass that data, it will be received in the interface method inside fragment, and you'll also know when it is received.

Google has demonstrated fragment to activity communication, just check that code and follow my instructions here for activity to fragment communication.

https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

Kashif Anwaar
  • 728
  • 7
  • 14