it just simple Android code like this
there was a textview and a list view.
public class MaintActivity extends Activity {
private TextView text = (TextView)super.findViewById(R.id.text);
//cause android application crash
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
//when I write this.text = (TextView) super.findViewById(R.id.text); here, I get rid of crashing
}
}
解决方案
Generally, there's nothing wrong in calling a method when initializing a variable in Java. However, in this specific case:
private TextView text = (TextView)super.findViewById(R.id.text);
You cannot call findViewById() before onCreate(). The code will NPE because the activity Window has not yet been set up. Also you likely want to call it after setContentView() so it will actually have a chance of returning something.
In Android activities in general, you shouldn't really be doing anything at runtime before onCreate().