In my application I have two fragments in an activity. In one of the fragments I have data, such as :
String name = "Transporter";
I want send this name to container activity. How can I do it? Please help me.
In my application I have two fragments in an activity. In one of the fragments I have data, such as :
String name = "Transporter";
I want send this name to container activity. How can I do it? Please help me.
The fragment will be attached to the activity which you launch from.
Thus, you can create a callback method in your activity which can be called from fragment using the activity context object.
Please see the below code snippet :
public class YourFragment extends Fragment{
OnCallbackReceived mCallback;
// Implement this interface in your Activity.
public interface OnCallbackReceived {
public void Update();
}
In your fragment :
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnCallbackReceived) activity;
} catch (ClassCastException e) {
}
}
// You can Call the event from fragment as mentioned below
// mCallback is the activity context.
mCallback.Update();
Activity :
public class MainActivity extends Activity
implements YourFragment.OnCallbackReceived {
// Implemented method.
public override void Update() {
// Write your logic here.
}
If you are calling an activity from a fragment and you want to send data to Activity you can use intents like below:
Intent intent = new Intent(getActivity(), YourActivity.class);
String name = "Transporter";
intent.putExtra("name", name);
startActivity(intent);
And in your activity you should get the data like this:
try {
Intent intent = getIntent();
String name = intent.getStringExtra("name");
} catch(Exception e) {
e.printStackTrace();
}
You need to create an interface.
Like
interface DataReciver
{
void getData(String data);
}
public class MainActivity extends AppcompactActivity
{
// On fragment load
oncreate
{
DataReciver obj=new DataReciver()
{
@overide
void getData(String data)
{
// Here is your data in data variable
}
}
frgamenttranstatiion.add(YOUR CONTAINER, new FRAGMENT1(obj));
}
}
Create a fragment with constructor
public class Fragment1
{
Fragment1(DataReciver datareciver)
{
datareciver.getData("amit sharma");
}
}
Currently best approach(and my suggestion) is using ViewModel
. you can find samples in android site. But I should says it is still beta version.
https://developer.android.com/topic/libraries/architecture/viewmodel.html
You can do it like
Create Method in activity like
public void doSomething(String abc)
{
// do your stuff here
}
and access it from fragment
like
((HomeActivity)getActivity()).doSomething(string);