Is it possible to pass data from an Activity using Bundle to a Fragment that has no OnCreate
Asked
Active
Viewed 524 times
-4
-
you can implement onCreate in fragment: check here: https://developer.android.com/reference/android/app/Fragment.html#onCreate(android.os.Bundle) – Jaydeep Devda Jun 08 '17 at 04:30
-
fragment has a onCreate() but you can not pass data from activity you need eventbus or interface approach. – Arpit Patel Jun 08 '17 at 04:30
-
no,is impossible – John Joe Jun 08 '17 at 04:31
-
Its not necessary to have onCreate method in fragment to get passed data. You can get data in fragment by using getArguments() in any of fragment lifecycle method after it attached. – Vindhya Pratap Singh Jun 08 '17 at 05:04
2 Answers
2
Try this one
public class SampleActivity extends AppCompactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
if (savedInstanceState == null) {
Fragment fragment = new SampleFragment();
Bundle args = new Bundle();
args.putInt("sample_int", 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment)
.commit();
}
}
}
public class SampleFragment extends Fragment {
@Override
public void onResume() {
Bundle args = getArguments();
if (args != null) {
int sampleInt = args.getInt("sample_int", -1);
}
}
}

VinayagaSundar
- 1,673
- 17
- 18
0
From Activity, you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}

Amit Thakkar
- 94
- 1
- 9