我正在尝试设置 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();
}
}
我在 list 的“使用权限”中设置了 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>
最佳答案
我试图在 setContentView()
之前调用我的方法,因此当该方法试图访问布局中的当前元素时,它导致了 NullPointerException
关于android - TextView.setText() 抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7115729/