简体   繁体   中英

App crashes when opened

I am making an android app where the user inputs a team number and then switches to a new activity, but once I make the Apk file and run it, the app crashes automatically, I can't tell why.

Please help.

Here is the code for the MainActivity :

package com.ftc.pitradar;

import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;

import com.ftc.pitradar.DataHandler;

public class MainActivity extends Activity {
    public static String TEAMNAME = "Team Name";
    EditText txt = (EditText) this.findViewById (R.id.txt_num);
    Button btn = (Button) findViewById (R.id.scout);
    public boolean dataentered(){
        if(!txt.getText().toString().matches(""))
        {
            return true;
        }
        else{
            return false;
        }
    }
    public void pit()
    {
        if(this.dataentered())
        {
            DataHandler.teamname = txt.getText().toString();
            Intent intent = new Intent(this, PitActivity.class);
            intent.putExtra(TEAMNAME, DataHandler.teamname);
            startActivity(intent);
        }
        else{
            Toast.makeText(this, "Please input all team data", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn.setOnClickListener(new OnClickListener (){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dataentered();
                pit();
            }
        });
    }
}

When you call setOnClickListener() on btn in onCreate() , btn is null, so a NullPointerException is thrown.

At the top of the class, declare your view instance variables but don't assign them yet:

EditText txt;
Button btn;

Then in onCreate() :

txt = (EditText) findViewById (R.id.txt_num);
btn = (Button) findViewById (R.id.scout);

At this point, btn is no longer null, so you can call setOnClickListener() on it.

Make sure that you have implement the correct Layout XML file. If in R.layout.activity_main are not the buttons, it will fail! Which IDE are you using?

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