开发者

TextView.setText() throwing NullPointerException

开发者 https://www.devze.com 2023-03-29 07:57 出处:网络
I\'m trying to set the text of a TextView which sounds simple enough but it keeps throwing errors here\'s my function:

I'm trying to set the text of a TextView which sounds simple enough but it keeps throwing errors here's my function:

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

I've set READS_PHONE_STATE in my 'Uses Permission' of my Manifest. Can anyone see what I might be doing wrong?

UPDATE:

Here's my layout code:

<?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_ve开发者_C百科rtical|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>


I was attempting to call my method before I setContentView() thus when the method attempted to access current elements in the layout it resulted in a NullPointerException


the text in your layout is set to @string/number, try getting rid of that.


Is this getAndPutNum() method contained in an inner class of the activity, AND this inner class is a dialog or even anoter activity? If so, watch out for one possibility (it happened to me several times):

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

精彩评论

暂无评论...
验证码 换一张
取 消