Jin
Jin

Reputation: 890

Android View is not null, but casting to ViewGroup makes it null

I have an Activity that adds a new view onPostCreate() like so:

View rootView = findViewById(android.R.id.content);
((ViewGroup)rootView).addView(myView);


When this code runs, I get a NullPointerException. However, if I don't cast it and check the output:

View rootView = findViewById(android.R.id.content);
Log.v(TAG, "rootView is " + rootView);


I get the log:

1340-1340/com.example.app V/MyActivity﹕ rootView is android.widget.FrameLayout@414d1b48

Why does this happen?

EDIT: I forgot to add that setContentView() was called in the preceding onCreate() and I did call super.onPostCreate() before the cast

Upvotes: 1

Views: 150

Answers (2)

Distwo
Distwo

Reputation: 11749

Make sure myView is not null in the following line:

((ViewGroup)rootView).addView(myView);

Upvotes: 2

maciekjanusz
maciekjanusz

Reputation: 4775

Casting is not a problem, or else a ClassCastException would be thrown. It seems your myView that you pass to addView(View view) method is null, I don't see any other possibility. Make sure you've initialized myView properly.

Upvotes: 2

Related Questions