Passing different lists to different fragment tabbed in the activity - android

In my app there's an Activity with three tabs, each of them contains a ListFragment.
The ListFragment must show different contents, but when I pass it through the bundle it gets overwritten and I get three fragments with the same content (the latest one)
Here's the code:
In the onCreate method of the Activity:
{...
Fragment fragment;
Bundle bundle= new Bundle();
for(int i = 0; i<CATEGORIES.size(); i++) {
fragment = new MyListFragment();
bundle.putSerializable("Data", data.get(i));
fragment.setArguments(bundle);
screens.put(CATEGORIES.get(i),fragment);
}
setUpViewPagerAndTabs();
...
... }
protected void setUpViewPagerAndTabs(){
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setOffscreenPageLimit(screens.size()+1);
mAdapter = new PageAdapter(screens, getSupportFragmentManager());
mViewPager.setAdapter(mAdapter);
tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
tabs.setTabMode(TabLayout.MODE_FIXED);
tabs.setupWithViewPager(mViewPager);
}
In the Fragment class this line produces the overwriting of the corresponding data:
ArrayList<String> names = (ArrayList<String>)
b.getSerializable(Activity.DATA);
even if I try to pass the value of the counter (i) to the fragment, in order to pick the right element of data in the fragment, it gets overwritten.
How can I resolve this?
Thank you in advance

Not sure if it is the case. However you are passing the reference to the same bundle (out of the scope) to all the three fragments. It might depend on when the serialization / deserialization takes effect, but if it happen after the loop you have three fragment pointing to the same content of the bundle (the last one).
Try to move the bundle creation inside the loop:
for(int i = 0; i<CATEGORIES.size(); i++) {
Bundle bundle= new Bundle();
fragment = new MyListFragment();
bundle.putSerializable("Data", data.get(i));
fragment.setArguments(bundle);
screens.put(CATEGORIES.get(i),fragment);
}

Related

Create tab dynamically in TabLayout

Any idea on how to dynamically create tab in TabLayout? I am implement it with ViewPager using FragmentStatePagerAdapter, or is there any other approach? like TabWidget/TabHost? any kind of suggestion will be appreciated...
Here you go -
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
ImageListFragment fragment2 = new ImageListFragment();
Bundle bundle2 = new Bundle();
bundle2.putInt("eventId", 100);
fragment2.setArguments(bundle2);
for(int i = 0; i < count; i++){
ImageListFragment fragment = new ImageListFragment();
Bundle bundle = new Bundle();
bundle.putInt("eventId", eventIds.get(i));
bundle.putInt("id", id);
fragment.setArguments(bundle);
adapter.addFragment(fragment, eventNames.get(i));
}
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
viewPager.setOffscreenPageLimit(1);
So basically you need to run a loop and create new fragment everytime and add it to your adapter.

how to pass data from activity to swipable fragments?

i have data in activity in which some data i want to show in activity itself and some data i want to show in three swipable fragments. so how do i pass data from activity to that fragments. i am gonna put image of what i want to do.
Please give solution about this.Thanks.
I think your main question is how to pass data from activity to fragment?Right?
You can pass data from activity to fragment by creating a Bundle and put some data to it and then pass it to the setArguments method.
YourFragment yourFragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putInt(KEY_RECIPE_INDEX, index);//you can use bundle.putString or others to pass different types of data
yourFragment.setArguments(bundle);
Now you can retrive the data in your fragment by using getArguments
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int index = getArguments().getInt(ViewPagerFragment.KEY_RECIPE_INDEX);
//........
You also ask in your question that you have some data in your activity and some of the data you want to show on activity and some of them you want to show in swipable fragments.Now I am going to show you how to do that by using an example.
Suppose you have two swipable tab and each tab has a fragment
final IngredientsFragment ingredientsFragment = new IngredientsFragment();
Bundle bundle = new Bundle();
bundle.putInt(KEY_RECIPE_INDEX, index);
ingredientsFragment.setArguments(bundle);
final DirectionsFragment directionsFragment = new DirectionsFragment();
bundle = new Bundle();
bundle.putInt(KEY_RECIPE_INDEX, index);
directionsFragment.setArguments(bundle);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewPager);
viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
#Override
public android.support.v4.app.Fragment getItem(int position) {
return position == 0 ? ingredientsFragment : directionsFragment;
}
#Override
public CharSequence getPageTitle(int position) {
return position == 0 ? "Ingredients" : "Directions";
}
#Override
public int getCount() {
return 2;
}
});
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
I think there is no problem of the data that you want to show in your activity.
Qick recap: You pass the data to fragment by creating a bundle and put some data and use yourfragment.setArguments(yourBundle).
Now I think you can pass data to swipable views.
Hope this helps!

How to get element back on popBackStack( )

I have two fragments: in the first fragment I do it:
ritorno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
manager.beginTransaction().replace(R.id.content_frame,new SearchFlight()).addToBackStack(null).commit();
}
});
and this works well. In the second I need to return to the first fragment, so I decide to do this:
String s = element.getText().toString(); //I need to return it
FragmentManager manager = getActivity().getSupportFragmentManager();
SearchFragment fragment = new SearchFragment();
manager.popBackStack();
I need to return to the first fragment this String. How could I do it?
Thanks
There are 3 ways
Static Variable : Define public static variable in first fragment, update its value in second fragment.
BroadcastReceiver
EventBus you can even find EventBus tutorial here
pass string to BR or EventBus and you can fetch it in first fragment by defining appropriate method or listener.
Try doing it with a bundle object.
String s = element.getText().toString(); //item to be returned
FragmentManager manager = getActivity().getSupportFragmentManager();
SearchFragment fragment = new SearchFragment();
Bundle bundle = new Bundle();
bundle.putString("key", "value");
fragment.setArguments(bundle);
manager.popBackStack();
And then, in your SearchFragment resolve the bundle like:
Bundle bundle = this.getArguments();
bundle.getString("key");
Do the resolution part of the bundle in your onCreateView of the SearchFragment. Do place a null check on the resolution part of the bundle. If the bundle is not resolved, then the getString("key") method will give a null pointer exception.

Why are all these fragments receiving the same bundle items?

I'm trying to add Fragments to a view. I have a String Array and I would like to create a new fragment for each one. Seems like a simple task.
String[] items = getResources().getStringArray(R.array.myArray);
for (int i = 0; i < items.length; i++) {
Bundle bundle = new Bundle();
bundle.putString("category", items[i]);
Fragment frag = new MyFragment();
frag.setArguments(bundle);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.mga_viewParentContainer, frag, "frag_" + i);
ft.commit();
Log.i ("FT commit called on item:", items [i]);
} // for loop
This creates a new fragment for every item in the array, however every fragment is getting the "category" bundle item from the last item in the array. So all fragments inflate the same info.
However, the Log reports all items as theyes should be.
Why is this happening?

Getting the ID in a list of fragments in a PagerActivity

I have a working PagerActivity (extends FragmentActivity) with a bunch of Fragment objects in it. Everything works fine but what I want to do now is to display the number of the Fragment in the list (let's say there are 25 Fragment objects and I want to display the current number in that list of Fragments).
How can I do that? Is there some method I can call in the Fragment object?
I'm filling the PagerAdapter like this (snippet):
fragments = new Vector<Fragment>();
for (int i = 0; i < wiList.length; i++) {
WhiteboardImage tmpWi = wiList[i];
Bundle bundle = new Bundle();
bundle.putString("wiImage", gson.toJson(tmpWi));
bundle.putInt("positionInList", positionInList);
bundle.putInt("totalCount", wiList.length);
fragments.add(Fragment.instantiate(params[0], GalleryFragment.class.getName(), bundle));
}
mPagerAdapter = new GalleryPagerAdapter(getSupportFragmentManager(), fragments);
Thanks for any help!
I assume GalleryPagerAdapter is a FragmentViewPager? Then the number of fragments would be fragments.size(), no?

Categories

Resources