metinkale38
metinkale38

Reputation: 738

Android - Fragment Views get NULL outside onCreateView

i have a Fragment and the View is stored into a Class variable in onCreateView:

    private FrameLayout mView;
    private TextView countdown;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle bdl) {
            mView = (FrameLayout)inflater.inflate(R.layout.vakit_fragment, container, false);
            countdown = (TextView) mView.findViewById(R.id.countdown);
    ...
            return mView;

    }

both are non-Null here and wont be modified anywhere in my code.

later this is called from the Main Activity:

         MainFragment frag = (MainFragment) mAdapter.getItem(mPager.getCurrentItem());
         if(frag!=null) {
         frag.onSecond();
         }

and in the Fragment:

protected void onSecond(){
    String left=times.getLeft();


    if(countdown!=null)     
        countdown.setText(left);

}

in onSecond both mView and countdown are ever NULL, why? I cant explain it.

metin

Upvotes: 2

Views: 2928

Answers (2)

Patricia Li
Patricia Li

Reputation: 1356

onCreateView is called only when the fragment draws the UI. In this case, onSecond is called before onCreateView, so mView hasn't been inflated yet, which is why it's null. You can get around this by putting the onSecond logic into onCreateView.

Upvotes: 3

Kitesurfer
Kitesurfer

Reputation: 3561

I think you create another instance of your Fragments in the adapter.getItem() Method.

Upvotes: 5

Related Questions