Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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();
}
like image 964
Ivan Aldwin A. Cristobal Avatar asked Apr 01 '18 07:04

Ivan Aldwin A. Cristobal


Video Answer


3 Answers

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

like image 126
sachinmaharjan Avatar answered Nov 09 '22 07:11

sachinmaharjan


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.

like image 35
Mihir Joshi Avatar answered Nov 09 '22 05:11

Mihir Joshi


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.

like image 39
Ivan Aldwin A. Cristobal Avatar answered Nov 09 '22 07:11

Ivan Aldwin A. Cristobal