Everyone, I am a newbie to android development. Now I have a question that cannot be solved by myself. Anything wrong with the code below(especially the line marked in the code)?
MainActivity.java:
package com.amaker.ch02.app;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private TextView displayTextView = (TextView)findViewById(R.id.DisplayTextView); <--Possibly this line
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayTextView.setText("change in the code");
}
}
Run, and i got a message in AVD: The application has stopped unexpectedly. Please try again. But if i dont assign displayTextView immediately after declaration, IOW i change the code as follows, then everything goes well.
package com.amaker.ch02.app;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private TextView displayTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayTextView = (TextView)findViewById(R.id.DisplayTextView);
displayTextView.setText("change in the code");
}
}
Why? Any difference with the two codes?
The TextView is not part of the activity’s view hierarchy until after you call
setContentView(R.layout.main). When you declare the variable like this:the view does not yet exist, so
displayTextViewgets set tonull. Then you are getting aNullPointerExceptionwhen you try to callsetText()inonCreate().