I am new to android programming and I can't figure out what i'm doing wrong.
My code:
Every time I run the code, the emulator works just fine, but when I try to open the app it show the error message.
Please help. Thanks.
first you must inflate your layout by setContentView
method .
second in onCreate
method , bind your view .
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
TextView tf1 = (TextView) findViewById(R.id.tf0);
tf1.setText("Hello World!");
}
You must call setContentView
before calling findViewById
.
void onCreate() {
super.onCreate()
setContentView(R.layout.my_activity_layout)
TextView tf1 = findViewById(R.id.tf0)
tf1.setText("hello")
}
You need SetContentView(R.layout.your_layout)
before calling findViewById
.
For example:
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
tf1 = findViewById(R.id.tf0);
tf1.setText("text")
I suspect tf1
is null because the layout hasnt been inflated yet also setContentView(view)
is required to be called in onCreate
to inflate the view. Also at the point you are declaring the tf1
(outside onCreate
) the reference will be null.
Try this
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tf1 = (TextView) findViewById(R.id.tf0);
tf1.setText("Hello World!");
}