Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException on findViewById() in android

In the following code i get a NullPointerException on lines 9/10 with findViewById().
In my main class I just instantiated an object from this class, to use .getFrom()

public class UserInteraction extends Activity {
EditText etFrom;
int from;
EditText etTill;
int till;

public UserInteraction(){
    etFrom = (EditText)findViewById(R.id.et_from);
    etTill = (EditText)findViewById(R.id.et_till);
}

public int getFrom() {
    String s = etFrom.getText().toString();
    int i = Integer.parseInt(s);
    return i;
}

public int getTill() {
    String s = etTill.getText().toString();
    int i = Integer.parseInt(s);
    return i;
}

Is it that the contentView is set in my main class ..? What could be the cause ?

like image 957
pointour Avatar asked May 22 '11 19:05

pointour


People also ask

How to fix null pointer exception in Android?

How to fix the NullPointerException? To avoid NullPointerException we have to initialize the Textview component with the help of findviewbyid( ) method as shown below. The findViewbyId( ) takes the “id” value of the component as the parameter. This method helps locate the component present in the app.

What is null pointer exception in Android?

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

Why is findViewById returning NULL?

FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.

How does findViewById work on Android?

The findViewById() method is a method of Android's View and Activity classes. The method is used to find an existing view in your XML layout by its android:id attribute. The same can be done for any valid Android View object, such as a Button or a CheckBox view.


1 Answers

The setContentView method should be called with appropriate layout before calling findViewById. It is usually called in onCreate(Bundle savedInstance) method.

like image 131
MByD Avatar answered Sep 28 '22 06:09

MByD