Reputation: 13
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();
}
});
}
}
Upvotes: 0
Views: 73
Reputation: 79
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?
Upvotes: 0
Reputation: 5926
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.
Upvotes: 1