-4

Is it possible to pass data from an Activity using Bundle to a Fragment that has no OnCreate

2 Answers2

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