Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(R.id.EmailTextView);     String email = localdatabase.getUserEmail();     emailTextView.setText(email);     } } 

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

like image 890
Milos Cuculovic Avatar asked Feb 10 '12 13:02

Milos Cuculovic


People also ask

What is findViewById () method used for?

FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.

What is findViewById R ID?

findViewById is the method that finds the View by the ID it is given. So findViewById(R. id. myName) finds the View with name 'myName'.

How does findViewById work on Android?

In the case of an Activity , findViewById starts the search from the content view (set with setContentView ) of the activity which is the view hierarchy inflated from the layout resource. So the View inflated from R. layout. toast is set as child of content view?

What does findViewById return?

findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .


1 Answers

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;     @Override   public void onCreate(Bundle savedInstanceState){      super.onCreate(savedInstanceState);      setContentView(id_number_of_layout);      emailTextView = (TextView) findViewById(R.id.EmailTextView);      // ... whatever other set up you need to do ...   }    public void getUserInformation() {      // .... regular code ...    } } 
like image 131
DeeV Avatar answered Sep 26 '22 01:09

DeeV