2016-02-09 27 views
1

我正在創建一個基本的Android應用程序。我創建了一個名爲mathexpresionTVTextView對象,並將其分配給我希望它引用的textview的id值。儘管爲其賦值,但獲得nullpointerexception

TextView mathExpressionTV = (TextView) findViewById(R.id.mathexpressiontextview); 

我也有一個按鈕,如果用戶按下它,它會在textview上顯示1。

Button oneButton = (Button) findViewById(R.id.button1) 
    oneButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       mathExpressionTV.append("0"); 
      } 
     }); 

我將使用mathExpressionTV通過類,因此我已經delcared它作爲一個全局變量,而不是我的onCreate();方法,但oneButton在我onCreate();聲明。

這是錯誤輸出:Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

+0

在哪個函數中執行此代碼? – 0xDEADC0DE

回答

2

你可以聲明它作爲一個全球性的,但你需要轉換爲TextViewonCreate。不能使用findViewById以外的方法的一個活動

TextView mathExpressionTV; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.yourActivity); 

    mathExpressionTV = (TextView) findViewById(R.id.mathexpressiontextview); 

    ... 
} 
+0

噢好吧,謝謝修復它。你知道我們是否可以引用其他View對象,如果它不在當前avctivity的佈局中?例如。如果在佈局A.xml和我的當前活動中有一個textview,C.java將內容設置爲B.xml,將能夠從A.xml中獲得rextview的引用。 –

+0

這通常不是您應該嘗試的做。如果你膨脹其他佈局,可以這樣做,看看:https://stackoverflow.com/questions/4211189/how-to-get-id-in-different-layout –

+0

那麼你是否推薦膨脹其他佈局? –

0

你有3種選擇:

  1. 使用findViewByIdonCreate方法
  2. textView創建一個全局變量,併爲其分配在onCreate方法中
  3. 傳遞活動對象,或獲取活動對象並使用它:activity.findViewById
相關問題