Search code examples
androidtextviewandroid-fragmentsbundlesettext

Args Bundle Not Passing to Android TextView


I have a Bundle in a fragment that passes a string to another fragment. This string needs to set text in a text view and my method isn't working. I'm not sure why but all my other strings pass thru.

Please take a look at my code and let me know what I have wrong - I don't get it...

From:

public void onClick(View v) {

        Bundle args = new Bundle();

        FragmentManager fm = getFragmentManager();
        final FragmentTransaction vcFT = fm.beginTransaction();
        vcFT.setCustomAnimations(R.anim.slide_in, R.anim.hyperspace_out, R.anim.hyperspace_in, R.anim.slide_out);

        switch (v.getId()) {

            case R.id.regulatoryBtn :

                String keyDiscriptionTitle = "Regulatory Guidance Library (RGL)";
                args.putString("KEY_DISCRIPTION_TITLE", keyDiscriptionTitle);

                RegulatoryDiscription rd = new RegulatoryDiscription();
                vcFT.replace(R.id.viewContainer, rd).addToBackStack(null).commit();
                rd.setArguments(args);
                break;
. . .
}

To:

public class RegulatoryDiscription extends Fragment {

    Bundle args = new Bundle();

    String DNS = "http://192.168.1.17/";
    String KEY_DISCRIPTION_TITLE = "KEY_DISCRIPTION_TITLE";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.discription_view, container, false);

        TextView title = (TextView) view.findViewById(R.id.discriptionTitle);
        String keyDiscriptionTitle = args.getString(KEY_DISCRIPTION_TITLE);
        title.setText(keyDiscriptionTitle);

        return view;
    }
 . . .
}

Solution

  • You are declaring args as a new Bundle in your RegulatoryDescription Fragment. This will initialize a new Bundle object that is completely empty

    You need to retrieve the already existing arguments that you passed in.

    ex.

    public class RegulatoryDiscription extends Fragment {
        Bundle args;
    
        String DNS = "http://192.168.1.17/";
        String KEY_DISCRIPTION_TITLE = "KEY_DISCRIPTION_TITLE";
      @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.discription_view, container, false);
    
            args = getArguments(); //gets the args from the call to rd.setArguments(args); in your other activity
    
            TextView title = (TextView) view.findViewById(R.id.discriptionTitle);
            String keyDiscriptionTitle = args.getString(KEY_DISCRIPTION_TITLE);
            title.setText(keyDiscriptionTitle);
    
            return view;
        }
    }