سؤال

I started with my first Apps on Android some days ago. I'm using Eclipse with Android SDK.

In every Tutorial, I see Code in onCreate(). But whenever I'm doing something in onCreate(), my App crashes at the start.

Do you know what the problem could be?

If I do things like

Button btn1 = (Button) findViewById(R.id.button1);

in onCreateOptions(), it's working fine...

هل كانت مفيدة؟

المحلول

The views you're attempting to find with findViewById() are not yet in the activity view hierarchy. They are in the fragment which is not yet created. They are not in the activity layout set with setContentView(). Therefore a null is returned and attempting to do something with the null causes an NPE.

The fragment transaction that creates the fragment view hierarchy and attaches it to the activity is usually run in onStart() of the activity lifecycle. onStart() comes after onCreate().

The tutorials are probably written without considering fragments and have the views in the activity layout directly.

نصائح أخرى

Please do follow the android app life cycle

App life cycle

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top