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, andgetArguments()
to read that data.Then in
onCreate()
method of the fragment: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: