user3138759
user3138759

Reputation: 13

NullPointerException when setting text on fragment from activity

I set the text on the textview located on the fragment, it returns a NullPointerException. It works when the fragments are added statically but it crashes when i'm using dynamically added fragments.

this is the function that is called when I want to set the text on the fragment.

@Override
public void countrySelected(String wordIn) {
    word = wordIn;
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
        display.setCountryText(wordIn);          
    }else{          
        display = new DisplayFragment();
        //display.setCountryText(wordIn);           
        fragmentTransaction.addToBackStack(list.getTag());          
        fragmentTransaction.replace(R.id.fragment_place,display,"disp");                        
        fragmentTransaction.commit();                           
        display.setCountryText(wordIn);
    }

}

this is the fragment.

public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.right,container, false);
      txt = (TextView) view.findViewById(R.id.txtView);
      Log.d("LOOOOADED", "Loaded");
      return view;        
}   

public void setCountryText(String word){            
    txt.setText(word);              
}

When I set the text on the statically added fragments, it works just fine. But when I set the text on the dynamically added fragment, it doesn't log "LOOOOADED", which means it never reached the onCreateView() method.

Upvotes: 1

Views: 92

Answers (1)

Raghunandan
Raghunandan

Reputation: 133570

You are calling the method display.setCountryText(wordIn); too soon before the fragment is attached to activity.

Look at framgent lifecycle. You need to wait till the fragment is attached to the activity and then call display.setCountryText(wordIn).

Upvotes: 1

Related Questions