MiloŇ° MiloŇ° - 1 year ago 72
Android Question

findViewById() not working in a not MainActivity class

I have a text view in my Lyout and I would like to set some text to this textview.
This should be made in a class which is not a MainActivity class.

The problem is that I got a null pointer exception.

Here is my code:

public class UserInformations extends Activity{

TextView emailTextView;
LocalDatabase localdatabase= new LocalDatabase(this);

public void getUserInformation()
emailTextView = (TextView) findViewById(;
String email = localdatabase.getUserEmail();

When I am doing this in the Main Activity class, it works, but it doesn't work not in another class.

Answer Source

Calling findViewById() on the Activity object will only work if the current Activity layout is set by setContentView. If you add a layout through some other means, then you need the View object of the layout and call findViewById() on it.

View v = inflater.inflate(id_number_of_layout); # such as R.layout.activity_main
View innerView = v.findViewById(id_number_of_view_inside_v);

If the layout is supposed to be the main layout of the activity, then do this:

public class MyActivity extends Activity{
  TextView emailTextView; 

  public void onCreate(Bundle savedInstanceState){
     emailTextView = (TextView) findViewById(;
     // ... whatever other set up you need to do ...

  public void getUserInformation() {
     // .... regular code ... 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download