开发者

Android: Null Pointer Exception at Text View

Here is a code for which I face the Exception

public class SHOSuper extends Activity{

String officerName;
String arr[];
String[] offN;
public void onCreate(Bundle savedInstanceState) {
    try{
        super.onCreate(savedInstanceState);
        final TextView tv;
        tv=(TextView)findViewById(R.id.txt1);
        System.out.println("I AM NEW ACTIVITY");
        arr=Receiver.split(Receiver.orignal, ","); 
        String value1= arr[1];
        System.out.println("Array index " + value1);
        String value2=arr[2];
        System.out.println("Array 2nd index " + value2);
        tv.setText(value1 + " At " + value2);
        officerName= arr[5];
        offN =new String[officerName.length()];
        offN=Receiver.split(officerName, "_");
    }
    catch(Ex开发者_如何学编程ception e){
        e.printStackTrace();
    }

setContentView(R.layout.main);
  }
}

On line tv.setText(value1 + " At " + value2); I face Null pointer Exception like this

**04-12 13:25:18.105: WARN/System.err(527): java.lang.NullPointerException
04-12 13:25:18.265: WARN/System.err(527):     at com.sho.SHOSuper.onCreate(SHOSuper.java:24)**

Can you help me?


findViewById() finds the view in your current contentView, not a random id in an xml.

So when you do this:

tv=(TextView)findViewById(R.id.txt1);

It cannot find the ID, even if it is available in your layout.main: the layout isn't set yet. Call the setContentView(R.layout.main); before you try and find any views.

(you can also use an inflater to get a 'random' view, and then add it to another view, but that doesn't seem what you are looking for)


Move setContentView(R.layout.main); before doing tv=(TextView)findViewById(R.id.txt1);


Call this function

setContentView(R.layout.main)

before calling

tv=(TextView)findViewById(R.id.txt1);

because findViewById() searches in the view hierarchy set by setContentView()


It would appear that

tv=(TextView)findViewById(R.id.txt1);

returns null

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜