I'm still new to Android programming, so this question is pretty simple. I see a lot of code examples on the Internet where user interface components like TextView are initialized and accessible in the onCreate() method of Activity.
When I use Android Studio to create a new project - FirstApp - with default settings, an empty action called MainActivity , bringing activity_main and fragment_main along with it, I can immediately compile it into an APK, deploy it on my device, and I get a screen with The "FirstApp" heading and the TextView in the upper left corner showing "Hello world!"
If I give TextView identifier textview1 and create a member variable, TextView myTextView; , then I can refer to it in the onCreate() Method of Activity, for example (without compiler errors, course):
@Override protected void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); myTextView = (TextView) findViewById (R.id.textview1); myTextView.setText ("Hello tablet!"); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction().add (R.id.container,new PlaceholderFragment()).commit(); } }
However, if I compile and run the APK, this results in "Unfortunately, FirstApp has stopped." message.
Earlier, I came across this problem by moving the startup code that accesses the user interface components to the onStart() Activity method, for example:
@Override protected void onStart() { super.onStart(); myTextView = (TextView) findViewById (R.id.textview1); myTextView.setText ("Hello tablet!"); }
This will cause the working APK with one TextView to display โHello tablet!โ In the upper left. - my simple questions doubled ...
- If the project uses fragments, I should fully expect that the user interface components will not be available in the
onCreate() Activity method, how do I see what happens with a lot of code examples on the Internet, perhaps because they have not been created yet? - Is access to the user interface components acceptable in the
onStart() method of Activity (which works) - or should I do something else? I also used the onCreateView method for Fragment before, but is it best to access the user interface components inside the fragment actually in the onCreate() method for the fragment that I haven't tried yet?
I also note that the onCreate() method of Fragment Android Studio creates for you when you create a new project, there is no stub provided ... but onCreateView does, and the life-cycle documentation implies (for me, anyway), that this may be the best place for such things.
Any recommendations on this subject are welcome.