setText with onClick button and onCreate crashes the application… here is a solution to the problem.
setText with onClick button and onCreate crashes the application
How do I change
my text field when the app starts, and how do I change it again when I click the button?
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myText=(TextView)findViewById(R.id.myActivityTextView);
myText.setText("Launch Text Change");
}
public void myButtonclicked(View v){
TextView myText=(TextView)findViewById(R.id.myActivityTextView);
myText.setText("Button Change Text");
}
activity_main.xml
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/myText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="@+id/myButton"
android:layout_below="@+id/myText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="myButtonclicked"/>
Solution
The ID of your TextView
in xml is myText
. Change your
lookup for
TextView myText=(TextView)findViewById(R.id.myActivityTextView);
to
TextView myText=(TextView)findViewById(R.id.myText);
It should work.