Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android; Declaring edittext in class body (Out of any method)

I have experience with programming languages but am a bit new to android programming.

I have a program with some fields that function as labels(textview), buttons, and data entry(edittext).

Whenever i declare them at the beginning of the program out of any methods(but in the class of course), when I start my application it crashes and simulation gives a "unfortunately, your program has stopped" alert.

Eclipse doesn't give any errors for the declaration and i did use the same way for defining regular variables with no issue. It also gives the same error when i declare a mediaplayer object in the class body.

Does anyone know why it gives error? And is there another way to declare global objects like edittext, viewtext, etc... Declaring them over and over again in methods sounds weird to me.

Thank you!!

public class TrainerActivity extends Activity {

Button stopTimer = (Button)findViewById(R.id.StopTimer);
Button startTimer = (Button)findViewById(R.id.StartTimer);
EditText totalTime = (EditText)findViewById(R.id.TotalTime);
EditText enterMin = (EditText)findViewById(R.id.EnterMin);
EditText enterSec = (EditText)findViewById(R.id.EnterSec);

private boolean breaker = false;

@Override

public void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    startTimer.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Button_StartTimer();
        }
    });

    stopTimer.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Button_StopTimer();
        }
    });
}
like image 865
Dogan Sinar Avatar asked Jan 17 '23 14:01

Dogan Sinar


1 Answers

Without seeing example code of what you're trying it's impossible to say for definite (we don't do mind-reading here). But let me guess, you're doing something like this?...

public class MyActivity extends Activity {

    TextView tv1; // This is fine.
    TextView tv2 = (TextView) findViewById(R.id.textview2); // Don't do this.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv1 = (TextView) findViewById(R.id.textview1); // This is fine
        tv1.setText("Some text"); // This works

        tv2.setText("Some text"); // NullPointerException here

    }
}

The tv2.setText(...) will fail because you used findViewById(...) BEFORE you call setContenetView(...) and as a result, tv2 will be null.

It's quite acceptable to declare your widgets as instance members in your Activity but don't try to use findViewById(...) until AFTER you have set your content view.

like image 109
Squonk Avatar answered Feb 20 '23 11:02

Squonk