2011-08-19 124 views
1

我想設置一個TextView這聽起來很簡單的文本,但在這裏不斷拋出的錯誤是我的功能:TextView.setText()拋出NullPointerException異常

private void getAndPutNum(){ 
    TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
    String myNum = tm.getLine1Number(); 
    TextView numDisplay = (TextView)findViewById(R.id.myNum); 
    try{ 
     numDisplay.setText(myNum); 
    }catch(Exception e){ 
     Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG).show(); 
     e.printStackTrace(); 
    } 
} 

我在我的「用途設置READS_PHONE_STATE許可'我的Manifest。任何人都可以看到我可能做錯了什麼?

UPDATE:
這裏是我的佈局代碼:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" android:weightSum="1"> 
<TextView android:gravity="center|center_vertical|center_horizontal" android:textAppearance="?android:attr/textAppearanceLarge" android:text="@string/number" android:textSize="65px" android:layout_gravity="center|center_vertical|center_horizontal" android:layout_height="fill_parent" android:layout_weight=".8" android:layout_width="fill_parent" android:layout_marginTop="-40dp" android:keepScreenOn="true" android:id="@+id/myNum"></TextView> 

+0

請張貼您的佈局xml – MByD

回答

2

我試圖打電話給我的方法之前我setContentView()因此當方法試圖訪問當前元素的佈局也導致在NullPointerException

0

在佈局的文本設置爲@字符串/號碼,嘗試擺脫這一點。

0

是包含在一個內部類的活性的這getAndPutNum()方法,並且該內部類是對話或甚anoter活動?如果是這樣,注意一種可能性(它發生在我身上好幾次):

class Activity1 extends Activity { 
    public void onCreate(...) { 
     setContentView(R.layout.some_xml); // your R.id.myNum is in this layout 
    } 

    class InnerDialog extends Dialog { 
     public void onCreate(...) { 
      setContentView(R.layout.other_xml); // but this layout DOESN'T have R.id.myNum 
     } 

     private void getAndPutNum() { 
      findViewById(R.id.myNum); // This will return NULL, because it's 
             // looking for myNum in other_xml, instead of 
             // some_xml. 

      // You should qualify findViewById() 
      Activity1.this.findViewById(R.id.myNum); 
     } 
    }