i have this android code .I have my layout for button defined in the xml file .i want to set the text for button here by getting it by id .but the app force closes.whats wrong ?
package com.action ;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class ActionActivity extends Activity {
@Override
public void onCreate(Bundle i){
super.onCreate(i);
Button button=(Button) findViewById(R.id.but);
button.setText("Hey!!");
setContentView(R.layout.main);
}
}
Thnx…
You have to use
setContentView(R.layout.main);before usingfindViewById().If you don’t do that,
findViewById()will returnnull(since no view with that ID is in the current layout) and you will get aNullPointerExceptionwhen trying to set the text on theTextView.The correct version of
onCreate()should look like this: