rofihe
rofihe

Reputation: 13

Set Text from Fragment to Navigation Drawer in Activity

I have an Activity. In the Activity, I have a Navigation Drawer on the Left and a fragment. In the Navigation Drawer, I have a textview for Name. I want to set the text view from Fragment to Navigation Drawer in activity

Here's the image:

Here the Code in Activity(MyActivity.java):

public TextView name;
    
    NavigationView navigationView =  findViewById(R.id.navigationview);
    View headerView = navigationView.getHeaderView(0);
    name = headerView.findViewById(R.id.sName);
    
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,homeSideDrawerLayout,home_toolbar, R.string.navigation_open,R.string.navigation_close);
    toggle.getDrawerArrowDrawable().setColor(Color.WHITE);
    homeSideDrawerLayout.addDrawerListener(toggle);
    toggle.syncState();

In Fragment Side,

String nameToSet = "kevin";
MyActivity myActivity = new MyActivity();
myActivity.name.setText(nameToSet);

But it's showing the following error

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

Upvotes: 1

Views: 211

Answers (1)

ferini
ferini

Reputation: 1958

You do not want to call MyActivity myActivity = new MyActivity(); as it creates a new activity. Instead, you need to get reference to the activity that the fragment is in:

MyActivity myActivity = (MyActivity)getActivity();

There is also a documentation exactly on communicating between fragment and activity.

Upvotes: 3

Related Questions