简体   繁体   中英

passing data from activity to fragment(navigation-component)

I have an activity through that I want to pass the data to a fragment. I am managing the fragments by the navigation component. Please guide me on how can i pass the data to fragments from my activity. thank you in advance

CODE FOR MAINACTIVITY.JAVA WHICH HOLDS FRAGMENT

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   
    setContentView(R.layout.activity_main);

    Toolbar toolbar = findViewById(R.id.toolbar);
    bnView = findViewById(R.id.bottom_navigation);
    bnView.setItemIconTintList(null);
    setSupportActionBar(toolbar);

    NavController navController = Navigation.findNavController(this, R.id.container);
    NavigationUI.setupWithNavController(bnView, navController);

}

this is the mainactivity where all the fragments are but before that i have a login activity through that i went inside the OTPActivity and through otp activity i enter inside the MAIN ACTIVITY.

CODE FOR THE LOGIN ACTIVITY

  binding.otpGetingBtn.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("ResourceType")
        @Override
        public void onClick(View view) {
            String vall = binding.editTextPhone.getEditText().getText().toString().trim();
            if (!ValidatePhoneNum()) {
                return;
            }else
            {
                Intent intent = new Intent(LoginSignupActivity.this, OTPActivity.class);
                intent.putExtra("mobile", vall);
                startActivity(intent);
                

            }

        }
    });

Pass the data to the MainActivity in a bundle/intent then get the bundle/intent in the fragment.

From Fragment class:

    Intent intent = requireActivity().getIntent();
    if (intent == null) {
        Log.v(LOG_TAG, "Intent is null");
        return;
    }
    Bundle bundle = intent.getExtras();
    if (bundle == null) {
        Log.v(LOG_TAG, "bundle is: NULL");
        return;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM