the following program force quit and crashes, I don’t understand why,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView tv = (TextView) findViewById(R.id.text);
Button btn1 = (Button) findViewById(R.id.button1);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void clicked(View v) {
tv.setText(btn1.getText());
}
}
but after moving the
TextView tv = (TextView) findViewById(R.id.text);
Button btn1 = (Button) findViewById(R.id.button1);
inside the clicked function it works, why is that?
thanks for any help..
Use the following code and it would start working.
You are using findViewById() before using setContentView() in the onCreate(), which would return null.