-1

I'm currently facing a problem when trying to edit the text of a TextView in the OnCreate method of an Activity. As I understand, setContentView must be called before trying to change the text, however I am still having trouble with this.

Here is the code in question :

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

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    userEmailtext = (TextView) findViewById(R.id.emailText);
    mAuth = FirebaseAuth.getInstance();
    mUser = mAuth.getCurrentUser();
    userEmailtext.setText("This Does Not Work");
}

This Activity includes the Android Studio default sliding menu. The aim of this setText is to change the email address text of the sliding menu. I believe the problem may lie in the fact that the sliding menu is part of a different layout file, meaning there is no "emailText" textview leading to the null pointer exception, however I am still not sure how this would be rectified.

Any help is appreciated.

Dby
  • 111
  • 2
  • 5
Sam
  • 348
  • 1
  • 10

2 Answers2

0

It depends on where is your R.id.emailText component.

If it is directly in your R.layout.activity_dash_board, the code should work. If it is in R.id.nav_view, you should reach it via navigationView.findViewById(R.id.emailText)

ibrahimyilmaz
  • 18,331
  • 13
  • 61
  • 80
0

You should init your TextView instace from NavigationView. In your case:

userEmailtext = (TextView) navigationView.getHeaderView(0).findViewById(R.id.emailText);
Jose Angel Maneiro
  • 1,226
  • 9
  • 20
  • Thanks for the solution, works perfectly! Would you please explain the use of the number 0 in the getHeaderView method, does it act as some sort of index? – Sam Apr 04 '18 at 14:02
  • Yeah, you can read this answer to complete the information. Greetings. https://stackoverflow.com/a/33194816/4871526 – Jose Angel Maneiro Apr 04 '18 at 14:19