2017-05-29 132 views
-1
崩溃时

所以我试着用一个按钮的点击,但应用程序崩溃切换活动,我也得到了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" /> 

的Java进行了onclicklistner

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为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); 
+0

你能表现出更多这样的代码?它在一个方法里面吗? – codeMagic

+0

更新它与更多的代码假设你的意思是java不xml –

+0

显示更多的代码,你定义的按钮 –

回答

0

您所面临的问题,因为你的按钮不正确初始化为Android的运行时间。请尝试更改相同的标识符你给巴顿和意图

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

希望工程

相关问题