切换活动时应用程序崩溃

时间:2017-05-29 16:02:43

标签: android

所以即时尝试通过单击按钮切换活动但应用程序崩溃并且我收到了logcat错误

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at jake.poewiki.Red.onCreate(Red.java:22)

按钮的xml

<Button
    android:background="@android:color/holo_orange_dark"
    android:textColor="#ffffff"
    android:id="@+id/GoToRed"
    android:layout_width="78dp"
    android:layout_height="48dp"
    android:text="Red"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="519dp"
    android:layout_marginLeft="0dp"
    app:layout_constraintLeft_toLeftOf="parent" />

onclicklistner的Java

 public class Gems extends AppCompatActivity {
Button GoRed, GoGreen, GoBlue, GoWhite, GoUniqueGems, GoHome, GoClasses, GoItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gems);
    GoGreen = (Button) findViewById(R.id.GotoGreen);
    GoRed = (Button) findViewById(R.id.GoToRed);
    GoBlue = (Button) findViewById(R.id.GoToBlue);
    GoWhite = (Button) findViewById(R.id.GoToWhite);
    GoUniqueGems = (Button) findViewById(R.id.GoToUnique);
    GoHome = (Button) findViewById(R.id.GoToHome);
    GoItems = (Button) findViewById(R.id.GoToItems);
    GoClasses = (Button) findViewById(R.id.GoToClasses);

    GoRed.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent GoRed = new Intent(Gems.this, Red.class);
            startActivity(GoRed);
        }
    });

OnCreate for Red.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_red);
    GoGems = (Button) findViewById(R.id.GoToGems);
    GoItems = (Button) findViewById(R.id.GoToItems);
    GoHome = (Button) findViewById(R.id.GoToHome);
    GoClasses = (Button) findViewById(R.id.GoToClasses);

第22行是一个点击监听器,允许用户返回到宝石页面

    GoGems.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent GoGems = new Intent(Red.this, Gems.class);
            startActivity(GoGems);

1 个答案:

答案 0 :(得分:0)

您遇到问题,因为您的Button未正确初始化为Android运行时。尝试更改您为Button和Intent提供的相同标识符

GoRed.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent i= new Intent(Gems.this, Red.class);
        startActivity(i);
    }
});

希望它有效