0

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

1
  • this question has got flooded with answers in just 5 min after posting the questtion....... Commented Apr 12, 2011 at 8:49

4 Answers 4

7

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

0

It would appear that

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

returns null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.