【问题标题】:TextView.setText() throwing NullPointerExceptionTextView.setText() 抛出 NullPointerException
【发布时间】:2011-08-22 10:16:53
【问题描述】:

我正在尝试设置 TextView 的文本,这听起来很简单,但它不断抛出错误,这是我的函数:

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。谁能看到我可能做错了什么?

更新:
这是我的布局代码:

<?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>

【问题讨论】:

    标签: android textview


    【解决方案1】:

    我试图调用我的方法之前 I setContentView() 因此,当该方法试图访问布局中的当前元素时,它会导致 NullPointerException

    【讨论】:

      【解决方案2】:

      您的布局中的文本设置为@string/number,尝试摆脱它。

      【讨论】:

        【解决方案3】:

        这个 getAndPutNum() 方法是否包含在活动的内部类中,并且这个内部类是对话框甚至是另一个活动?如果是这样,请注意一种可能性(它发生在我身上好几次):

        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);
                 }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-11
          • 2013-09-07
          • 2013-06-18
          • 2016-07-07
          • 2014-10-02
          • 2012-05-21
          • 2014-08-15
          • 2013-08-06
          相关资源
          最近更新 更多