質問

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