简体   繁体   中英

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!

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);

In Kotlin, you can access an activity variable from a fragment like this

(activity as ActivityClassName).variableName

I don't have much experience in Java, but I believe this is that code translated into Java

((ActivityClassName) getActivity()).variableName

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