11

I'm trying to set the text of the navigation drawer activity from the fetched data on my database, but when i try to do so, it throws the following error

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

Am I missing something or did I do something wrong in my code?

public void fetchDb(){
    String email = getIntent().getExtras().getString("EMAIL");

    TextView txtName = findViewById(R.id.nameText);
    TextView txtEmail = findViewById(R.id.emailText);
    String name, ema;

    DatabaseHelper dbh = new DatabaseHelper(this);

    newDb = dbh.getReadableDatabase();
    Cursor c = newDb.rawQuery("SELECT * FROM user WHERE user_email = \'" + email+"\'", null);
    if (c.moveToFirst()){
        do {
            name = c.getString(1);
            ema = c.getString(2);

            txtName.setText(name);
            txtEmail.setText(ema);

        } while(c.moveToNext());
    }
    c.close();
    newDb.close();
}
udit7395
  • 626
  • 5
  • 16

3 Answers3

47

Null pointer try to say that the textview is null. That can happen beacause the findviewbyid is not matching with the right one on your xml. Be sure your id matches on your xml and java file

  • The textviews are located on nav_header_main_menu.xml, not on activity_main_menu.xml, is it possible to edit the nav_header_main_menu text views on the MainMenu class? – Ivan Aldwin A. Cristobal Apr 01 '18 at 07:25
  • 3
    you need to find it on the view of nav_header. First create view for header and find it. NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); View header= navigationView.getHeaderView(0); text= header.findViewById(R.id.text); – sachinmaharjan182 Apr 01 '18 at 07:28
6

Possibly there are two situation.. If u are using older version of Android studio then u should use this TextView txtName = (TextView)findViewById(R.id.nameText);

Another possibility is that may be the layout is different where the textview is declared.

Mihir Joshi
  • 117
  • 4
  • 1
    i am not using an older version, but i think it is the different layout. since the textviews i am declaring are in the nav_header_main_menu.xml file. not in the activity_main_menu.xml – Ivan Aldwin A. Cristobal Apr 01 '18 at 07:11
  • 2
    Yeah..then u have to pass the navheader context to findviewbyid.. `NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); View hView = navigationView.getHeaderView(0); TextView nav_user = (TextView)hView.findViewById(R.id.nav_name);` – Mihir Joshi Apr 01 '18 at 07:14
  • 1
    Do not make assumptions as answer . First read the question . – ADM Apr 01 '18 at 07:14
  • Thanks i was missing the correct layout! – Jose Mhlanga May 31 '20 at 13:25
1

This actually fixed my problem:
How to change text of a TextView in navigation drawer header?

I was trying to set the navigation headers text from my Main Class.