Reputation: 83
I'm trying to prepare a view to be shown by update the text in the textview before I ever switch over to that view.
I've declared the textview variable as public, initialized it in the OnCreate
Info = (TextView) findViewById(R.id.BackDialogText);
And then when it comes time to change the text, I get a nullpointerException
Info.setText(TheString);
setContentView(R.layout.mydialog_layout);
I've run the app without the setText and it runs fine, showing me my view with the predefined text. Is there some trick I'm missing to update the text of the view?
Upvotes: 0
Views: 120
Reputation: 1618
Basically before you set the view
setContentView(R.layout.mydialog_layout);
to your activity you cannot use the elements inside the view in your code. So you must have something like this in your code
setContentView(R.layout.mydialog_layout);
Info = (TextView) findViewById(R.id.BackDialogText); // you cannot initialize your view before setcontentview
Info.setText(TheString); //this line must be always called after setContentView
Upvotes: 1
Reputation: 7569
findViewById() finds Views in the View you're calling it from.
edit: sorry my Mac was crashing and I couldn't expand further. Basically, in Android only the foreground Activity is living at any one point. So even modifying one View from another Activity is not a good idea. If it's just the text you want to modify, then you have a couple of options, the easiest is to have a public static variable in one of the Activities, and calling setText with that variable.
So for instance:
public class Activity1 extends Activity {
private static theString = "";
public static void setString(String s) {
theString = s;
}
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.mydialog_layout);
Info = (TextView) findViewById(R.id.BackDialogText);
Info.setText(TheString);
}
}
and then in Activity2 you can call:
Activity1.setString("New String");
Upvotes: 0
Reputation: 28093
Just interchange the line positions.
Below is the working snippet.
setContentView(R.layout.mydialog_layout);
Info.setText(TheString);
Upvotes: 1