Passing data by using bundle between tablayout

1.2k views Asked by At

I am using Bundle to passing data from my First TabFragment but it prompts out with the NullPointerException. Error is occur when getArguments() in list_fragments2 in second tab

MainActivity Fragment

list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
Toast.makeText(this, "" + b, Toast.LENGTH_SHORT).show();

SecondActivity Fragment

 public class list_fragment2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View h = inflater.inflate(R.layout.tab2, container, false);
        TextView textView = (TextView) h.findViewById(R.id.textView);

        Bundle bundle=getArguments();

        //your string
        if(bundle != null) {
            String test = bundle.getString("test");
            textView.setText(test);
        }
            return h;

    }
}
2

There are 2 answers

6
beeb On BEST ANSWER

Do you actually load your second fragment?

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
fragmentTransaction.replace(placeholder, fragment);
fragmentTransaction.commit();
0
RoShan Shan On

I think you can create your instance of list_fragment2 code within list_fragment2. Maybe your codes recreated list_fragment2 many times.

public static list_fragment2 createInstance() {
        list_fragment2 fragment = new list_fragment2();
        Bundle bundle = new Bundle();
        bundle .putString("test","text");
        fragment.setArguments(bundle);
        return fragment;
    }