-2

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...

Pidu2
  • 3
  • 1

2 Answers2

0

Please do follow the android app life cycle

App life cycle

m0rpheu5
  • 600
  • 4
  • 16
0

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.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • Hi, thanks for your comment :) I'm really new to this ;) could you show me some example-¨code pls? sorry :/ – Pidu2 May 07 '14 at 19:29