Reputation: 199
I'm learning Android development and I'm wondering why is my app crashing
Main code:
package com.tester.myapp;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
public class Main extends Activity {
Button carrega;
TextView texto;
@Override
protected void onCreate(Bundle savedInstanceState) {
carrega = (Button)findViewById(R.id.carregar);
texto = (TextView)findViewById(R.id.textView3);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
carrega.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
texto.setText("newtext");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And my XML is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/textView3"
android:layout_width="fill_parent"
android:layout_height="35dp"
android:background="#A5BB76"
android:text="@string/message" />
<Button
android:id="@+id/carregar"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="@string/OK"
/>
</LinearLayout>
And this app works OK just by the XML, but if I define those variables (Button and TextView) it crashes at start. Why is this happening? How can I solve this? If I take off my Java new code (and maintain the default) the app works, but it doesn't whenever I declare one of those variables.
I appreciate your time. Thank you very much. Any help would be great.
Upvotes: 0
Views: 505
Reputation: 8939
You should Initialise the View after the setContentView(R.layout.activity_main);
Change It
@Override
protected void onCreate(Bundle savedInstanceState) {
carrega = (Button)findViewById(R.id.carregar);
texto = (TextView)findViewById(R.id.textView3);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
To
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
carrega = (Button)findViewById(R.id.carregar);
texto = (TextView)findViewById(R.id.textView3);
Upvotes: 4