简体   繁体   中英

Android App crashing at beginning

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM