Android – Transfer data from Fragment Activity to Fragment

androidandroid-fragmentactivitybundlefragment

I'm working with a bluetooth service in my application which ables me to get received message from another device. In my FragmentActivity, i'm using a handler to get this message:

FragmentActivity:

  public final Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                  //my code

                  case MESSAGE_READ:
                         byte[] readBuf = (byte[]) msg.obj;
                         byte[] alpha = null;
                         alpha=readBuf;

                         if(alpha!=null){
                          //my code..
              }
        }
  }

From this Handler I would like to get a data and transfer it to a Fragment.
I tried to use bundle but it doesn't work..

The code I tried:

In FragmentActivity:

    Intent intent = new Intent();
intent.setClass(getApplicationContext(), General.class);
Bundle bundle=new Bundle();
bundle.putInt("battery", bat);
intent.putExtra("android.intent.extra.INTENT", bundle);

In Fragment:

Bundle bundle = getActivity().getIntent().getExtras();
if (bundle != null) {
int mLabel = bundle.getInt("battery", 0);
Toast.makeText(getActivity(), "tottiti: "+mLabel, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "prout", Toast.LENGTH_SHORT).show();
}

The application is returning "prout" which means that it can't get my data from my FragmentActivity.

Is there any other way to get a data frome a fragmentActivity and transfer it to a fragment?

Thank you for your help

Best Answer

Assuming that you need pass the data to the fragment at creation time, you could use setArguments() to pass data to the fragment, and getArguments() to read that data.

Bundle bundle = new Bundle();
bundle.putInt("battery", bat);
MyFragment fragment=new MyFragment();
fragment.setArguments(bundle);

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment_container,fragment);
ft.commit();

Then in onCreate() method of the fragment:

Bundle bundle=getArguments(); 
int mLabel = bundle.getInt("battery", 0);

But if the fragment is already created, then you could create a method inside the fragment that you'll use to pass data, something like this:

fragment.setBattery(bat);