2016-10-02 68 views
1

这是我在我的商店活动类的代码,每次运行它,它崩溃,我不知道为什么。我只是Android工作室的初学者,所以我只是试着制作一个应用程序。每当我打开我的商店活动,它崩溃

import android.app.Activity; 
import andrstrong textoid.os.Bundle; 
import android.view.View; 
import android.view.Window; 
import android.widget.Button; 

import static com.example.dazx15.spaceevasion.R.*; 

public class ShopActivity extends Activity { 
final Button buy1 = (Button) findViewById(id.buy_1); 

private int best = 0; 
private int coin=0; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 

    buy1.setVisibility(View.INVISIBLE); 
    super.onCreate(savedInstanceState); 
    this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(layout.activity_shop); 



} 
//when you click the buy button 
public void buySpaceship() 
{ 
    coin=GamePanel.coin; 
    if(coin<=500) 
    { 
     coin=coin - 500; 
     buy1.setText("OWNED"); 
     buy1.setClickable(false); 

    } 
} 
public void update() { 
    best = GamePanel.best; 
    GamePanel.coin=coin; 

    //if the score is 500 above 
    if (best <= 500) { 
     buy1.setVisibility(View.VISIBLE); 

     } 
    } 
    } 
+0

请阅读http://stackoverflow.com/help/how-to-ask,请不要像你这样的短语请帮助我。 –

+0

我忘了也值得阅读http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

回答

0

改变这一行:

final Button buy1 = (Button) findViewById(id.buy_1); 

final Button buy1; 

和你onCreate应该是这样的:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(layout.activity_shop); 
    buy1 = (Button)findViewById(id.buy_1); 
    buy1.setVisibility(View.INVISIBLE); 
} 

您的应用程序崩溃,因为这行:

final Button buy1 = (Button) findViewById(id.buy_1); 

你想初始化按钮的权利?但是,该语句在创建活动的新实例时执行(我的意思是构造函数被调用,而不是onCreate)。那时候,活动中的观点尚未布置!这导致findViewById找不到视图,因此它返回null

现在在onCreate中,您试图将buy_1的可见性设置为隐藏。但是,由于buy_1为空,因此没有设置!因此,会抛出空指针异常并导致应用程序崩溃。

+0

谢谢先生清扫:)但我有另一个问题,我怎么能更新按钮buy1因为它没有更新,当我运行我的应用程序仍然不可见 – dazx15

+0

@ dazx15当然它不可见!在'onCreate'中将按钮的可见性设置为'INVISIBLE'! – Sweeper

+0

我设置了不可见的,因为如果分数达到500,所以如果我的分数(最好)等于或大于500,我想将其设置为可见500按钮buy1更新为可见即多数民众赞成我想要做的 – dazx15

相关问题