2017-05-29 116 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); 
    } 
}); 

希望工程

相關問題