David Silva
David Silva

Reputation: 67

How to transfer data from different fragments in tabLayout?

I have a problem passing the selected Item of my ListView to another fragment.

I have a TabbedActivity with 2 tabs. 1st is called OngletCours and the 2nd is called OngletNotes.

I'm getting an error while passing the Item I clicked on.

I have tried the whole weekend but without sucess to transfer the Item I clicked on to the 2nd tab/fragment.

Here is the code from my 1st Fragment/Tab OngletCours (I'm only showing you the setOnItemClickListener :

     l1.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            OngletNotes fragment = ((Onglets)getActivity()).getOngletNotes();

            if(fragment == null) {
                fragment = OngletNotes.newInstance();
            }
            //récupération de la position convertie en String de l'item que j'ai choisi
            String item = l1.getItemAtPosition(i).toString();

            Bundle args = new Bundle();
            args.putString("Item",item);

            fragment.setArguments(args);

            getFragmentManager().beginTransaction().add(R.id.container, fragment).addToBackStack(null).commit();
            ((Onglets)getActivity()).goToFragment(1);
        }

    });

My 2nd tab/Fragment OngletNotes looks like this :

public class OngletNotes extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.ongletnotes, container, false);
    //where i want to insert the selectedItem
    TextView Cours = (TextView)rootView.findViewById(R.id.TVCours);

    Bundle bundle=getArguments();
    String cours="";
    //ERROR !
    cours = bundle.getString("Item");
    //Retrieve the value
    Cours.setText(cours);

    return rootView;
}

public static OngletNotes newInstance() {
    OngletNotes fragment = new OngletNotes();
    // put values which you want to pass to fragment
    // Bundle args = new Bundle();
    // fragment.setArguments(args);
    return fragment;
}

I have the following error :

03-06 12:48:13.959 1033-1033/com.example.dasilvadd.students E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException at com.example.dasilvadd.students.OngletNotes.onCreateView(OngletNotes.java:23)

Line 23 is the following one :

Bundle bundle=getArguments();

Please help me solving this, I really need to advance in my project. Thank you in advance !

Upvotes: 1

Views: 1463

Answers (5)

fazal ur Rehman
fazal ur Rehman

Reputation: 404

in Case of kotlin you can create newInstance in fragment;

class TeamTwoFragment :Fragment {
   lateinit var eventsX: EventsX
   lateinit var stateList: StateList
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

}
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    arguments?.let {
        eventsX = it.getParcelable (EVENT_X)!!
        stateList = it.getParcelable(STATE_LIST)!!
    }

}
fun newInstance(someInt: EventsX, events: StateList): TeamTwoFragment {
    val myFragment = TeamTwoFragment().apply {
        val args = Bundle()
        args.putParcelable(EVENT_X, someInt)
        args.putParcelable(STATE_LIST, events)
        setArguments(args)
    }

    return myFragment
}

 And from tablayout activity or fragments when setup tablayout:
  
 setupViewPager(binding.viewPager,TeamOneFragment().newInstance(eventsX,events))

Upvotes: 0

Raja Jawahar
Raja Jawahar

Reputation: 6952

Don't use Bundle for transfer data if you have only two framgent in the tab.

I will explain you from the beginning..

For ViewPager you need list of Fragments right. Just like below

List<Fragment> fragmentsList = new ArrayList<Fragment>();
fragmentsList.add(Fragment1)-->OngletCours
fragmentsList.add(Fragment2)-->OngletNotes

You will pass the above list in ViewPagerAdapter.

Have one function in Fragment2 like below

 public void getDataFromFragmentOne(String item){
 // Do the mannipulation
 }

When the item clicked in FragmentOne Just call the above function like below

((OngletNotes)getParentFragment.fragmentsList.get(1)).getDataFromFragmentOne(item)..

The above should work perfectly..Because you are not handling data in onCreateView or onCreate.. Whenever the item is clicked you will pass the data to the secondframent which is already there in viewpager because of offsreenpage limt.

Upvotes: 0

Hmm
Hmm

Reputation: 86

Provide a constructor for your fragment

 public OngletNotes () {
        setArguments(new Bundle());
    }

Upvotes: 0

Remario
Remario

Reputation: 3863

Use shared preferences, create a shared preference in OngletCours then read from in OngletNotes. there is a single instance of this class that all clients share , so in this case it makes sense.Go to this link to refresh it code syntax.https://developer.android.com/training/basics/data-storage/shared-preferences.html

hey just remember this for future purposes, serialize your data whenever your store it. a great library is gson. Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.Just something to think about still.

Upvotes: 1

AskNilesh
AskNilesh

Reputation: 69681

try this

Use Bundle to send String:

YourFragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("YourKey", "YourValue");
fragment.setArguments(bundle);

//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container,fragment).commit();

In onCreateView of the new Fragment:

//Retrieve the value
    String value = getArguments().getString("YourKey");

i hope it will work for your case

Upvotes: 0

Related Questions