2012-10-31 46 views
0

我有2個方法使用相同的2個按鈕+ 1個TextView。事情是這樣的:Android - 全局變量java.lang.NullPointerException

public void startChange(View v) { 
    final Button start = (Button) findViewById(R.id.start); 
    final Button restart = (Button) findViewById(R.id.restart); 
    final TextView check = (TextView) findViewById(R.id.check); 
    //TO-DO part - Sets check to something based on buttons TagID 
} 

public void restartChange (View v) { 
    final Button start = (Button) findViewById(R.id.start); 
    final Button restart = (Button) findViewById(R.id.restart); 
    final TextView check = (TextView) findViewById(R.id.check); 
    //TO-DO part - Restars everything to basic position 
} 

一切正常。但只要我做了這個按鈕和TextView的全局變量,我得到了顯示java.lang.NullPointerException。 任何想法如何解決它?

編輯: 問題解決了。 只認爲你需要做的是在全球定義來定義按鈕和TextView的在onCreate方法不..

例子:

public class Example extends Activity { 
    Button start; 
    Button restart; 
    TextView t; 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     start = (Button) findViewById(R.id.start); 
     restart = (Button) findViewById(R.id.restart); 
     check = (TextView) findViewById(R.id.check); 
    } 
} 
+1

你如何定義爲全局變量?你能展示那部分嗎? – kosa

+0

請發佈堆棧跟蹤(完整的錯誤消息)和錯誤發生的代碼。 –

+2

如果您找到解決方案,可以將其作爲答案發布。你將能夠在兩天內接受。 – Yamaneko

回答

0

問題解決了。 只有想不到你要做的是定義不全局定義在onCreate方法按鈕和TextView的..

例子:

public class Example extends Activity { 
    Button start; 
    Button restart; 
    TextView t; 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     start = (Button) findViewById(R.id.start); 
     restart = (Button) findViewById(R.id.restart); 
     check = (TextView) findViewById(R.id.check); 
    } 
} 
0

您必須添加setContentView(R.layout.main);

public class Example extends Activity 
{ 
    Button start; 
    Button restart; 
    TextView t; 

    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     start = (Button) findViewById(R.id.start); 
     restart = (Button) findViewById(R.id.restart); 
     check = (TextView) findViewById(R.id.check); 
    } 
}