Search code examples
androidandroid-fragments

Passing values from Activity to Fragment


I'm using Navigation drawer after login in my app. In Navigation drawer I am using a fragment called "profile" for displaying the user information. I want to passing data from loginpage activity to the profile fragment.

Bundle bundle = new Bundle();
Intent home =  new Intent(LoginPage.this, HomeActivity.class);
startActivity(home);
bundle.putString("name", gname);
Profile profile = new Profile();
profile.setArguments(bundle);

And this is my Profile Fragment:

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    name = this.getArguments().getString("name");
    ntext.setText(name);

    return inflater.inflate(R.layout.activity_profile, container, false);
}

But I am getting Null Pointer Exception. I can't understand what is the problem! If there are another way to pass Data from activity to fragment, please tell me!


Solution

  • You need to create a function in your Profile fragment called newInstance that creates the fragment and set the arguments through there, then returns the fragment with the arguments. Like this

    public static Profile newInstance(String name){
        Profile profile = new Profile();
        Bundle bundle = new Bundle();
        bundle.putString("name", name);
        profile.setArguments(bundle);
        return profile;
    }
    

    Then create the fragment in your activity like this

    Profile profile = Profile.newInstance(gname);
    

    And get the arguments how you have been doing in the onCreate in the fragment.

    You also should be creating the Fragment in the activity you are using it in. So if it's in your home activity you will want to pass the data from the login activity, then build the fragment in the onCreate for the home activity.

    Intent home = new Intent(this, HomeActivity.class);
    intent.putExtra("name", gname);
    startActivity(home);
    

    in the HomeActivity

    Bundle extras = getIntent().getExtras();
    String gname = extras.getString("name");
    Profile profile = Profile.newInstance(gname);