How to access custom arraylist in fragment - android

I have tablayout in my app,and i want to set recyclerview in tablayout fragment.if i set static String array it is working fine.but i dont know how can i access custom arraylist in fragment to set data in my recyclerview.following is my code can any one help me with that
public class CategoriesActivity extends AppCompatActivity{
private Header myview;
private ArrayList<SubcategoryModel> subct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categoris_activity);
ArrayList<CategoryModel> filelist = (ArrayList<CategoryModel>)getIntent().getSerializableExtra("categorylist");
System.out.println("Category list size"+filelist.size());
myview = (Header) findViewById(R.id.categorisactivity_headerView);
myview.setActivity(this);
TabLayout tabLayout = (TabLayout) findViewById(R.id.cat_tab_layout);
for(int i = 0; i < filelist.size(); i++){
subct=filelist.get(i).getItems();
for(int j=0;j<subct.size();j++)
{
}
System.out.println("SubCategory list size"+subct.size());
}
for(int i = 0; i < filelist.size(); i++){
tabLayout.addTab(tabLayout.newTab().setText(filelist.get(i).getCategory_typename()));
ArrayList<SubcategoryModel> subct=filelist.get(i).getItems();
for(int j=0;j<subct.size();j++)
{
}
}
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("key", filelist);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.categories_pager);
CategoriesAdapter mPagerAdapter = new CategoriesAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(mPagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public class CategoriesAdapter extends FragmentStatePagerAdapter {
ArrayList<CategoryModel> catlist;
int numoftabs;
public CategoriesAdapter(FragmentManager fm, int numoftabs) {
super(fm);
this.numoftabs = numoftabs;
}
#Override
public Fragment getItem(int position) {
Log.v("adapter", "getitem" + String.valueOf(position));
return FirstFragment.create(position);
}
#Override
public int getCount() {
return numoftabs;
}
}
}
Fragment
public class FirstFragment extends Fragment {
// Store instance variables
public static final String ARG_PAGE = "page";
private int mPageNumber;
private Context mContext;
private int Cimage;
private ArrayList<SubcategoryModel> subcatlist;
private RecyclerView rcylervw;
private ArrayList<CategoryModel> filelist;
public static FirstFragment create(int pageNumber){
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
// image uri get uri of image that saved in directory of app
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.test, container, false);
// Get the Bundle Object
Bundle bundleObject = getActivity().getIntent().getExtras();
// Get ArrayList Bundle
ArrayList<CategoryModel> classObject = (ArrayList<CategoryModel>) bundleObject.getSerializable("key");
System.out.println("Frag Category list size"+classObject.size());
rcylervw=(RecyclerView)rootView.findViewById(R.id.subcategory_recycler_view);
rcylervw.setHasFixedSize(true);
MyAdapter adapter = new MyAdapter(new String[]{"test one", "test two", "test three", "test four", "test five" , "test six" , "test seven"});
rcylervw.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rcylervw.setLayoutManager(llm);
return rootView;
}
getting NPE here
// Get the Bundle Object
Bundle bundleObject = getActivity().getIntent().getExtras();
// Get ArrayList Bundle
ArrayList<CategoryModel> classObject = (ArrayList<CategoryModel>) bundleObject.getSerializable("key");

Make CategoryModel implements serializable. Put data in bundle using
Bundle args = new Bundle();
args.putSerializable("key", data);
fragment.setArguments(args);
Then, while getting data use:
if (getArguments() != null) {
classObject = (ArrayList<CategoryModel>) getArguments().getSerializable("key");
}

Make CategoryModel implement Parcelable then use bundle.putParcelableArrayList(key,list) and bundle.getParcelableArrayList(key)

Related

Passing a List From the MainActivity to a Fragment

I have a viewPager activity that makes multiple fragments with custom FragmentPagerAdapter.
I need to get the List<Audio> audioList and use it in my fragment.
Here is a small part of my MainActivity where I make the fragments. I do not think the rest of the MainActivity code is required in order to answer this question.
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
PagerAdapter pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), MainActivity.this, audioList);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
Here is my custom FragmentPagerAdapter:
public class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "Recommended", "Popular", "Rock", "Pop", "Blues", "Chill" };
Context context;
private List<Audio> audioList;
public PagerAdapter(FragmentManager fm, Context context, List<Audio> audioList) {
super(fm);
this.context = context;
this.audioList = audioList;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new BlankFragment();
case 1:
return new BlankFragment();
case 2:
return new BlankFragment();
case 3:
return new BlankFragment();
case 4:
return new BlankFragment();
case 5:
return new BlankFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
And I need to get the List<Audio> audioList into my Fragment here:
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.content_view, container, false);
//Get auidoList here
return rootView;
}
I also need to get the title of the tab in the future but my guess is that I would get it similarly to the audioList. If it is not then I could also use help on getting the tab title.
Additionally if the code style is wrong then I am always happy to have some feedback on it aswell.
The traditional way of doing this is by having an instance method that moves it all via a bundle.
Like this:
public class BlankFragment extends Fragment {
public static BlankFragment newInstance(String title, ArrayList<Audio> audioList) {
BlankFragment blankFragment = new BlankFragment();
Bundle bundle = new Bundle();
bundle.putString("Title", title);
bundle.putParcelableArrayList("AudioList", audioList);
blankFragment.setArguments(bundle);
return blankFragment;
}
public BlankFragment() {
// Required empty public constructor
}
private String title;
private ArrayList<Audio> audioList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
title = bundle.getString("Title");
audioList = getArguments().getParcelableArrayList("AudioList");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.content_view, container, false);
//Get auidoList here
return rootView;
}
}
Obviously your Audio class will need to implement parcelable for this to work. I found a great plugin (Android Parcelable Code Generator) in Android Studio for generating parcelable code that makes that quick and easy.

False data in customList in a dynamically created fragment

I have an Activity with 2 fragments.
Declared a ParentTabFragment in my Activity in which there is a TabLayout and a ViewPager.
There's a method in my ParentTabFragment called addPage which gets called in the Activity.
The addPage has another method called addFrag which is called from a ViewPagerAdapter creating the views in the ChildTabFragment dynamically.
There is a for loop which runs in the Activity, so the Fragments are created according to the number of items in the customList, creating the amount of tabs and pages in the Fragments.
In my ChildTabFragment I load a customList on tab selection event,
when I select a Tab in the ParentTabFragment, I call a getTabID() method from the ChildTabFragment and send the id of the Tab due to which I load the customList according to the id in the ParentTabFragment.
Problem is when I swipe or select tabs, duplicate/false data gets created in the customList.
I get the proper Id of the selected tab but when I try to pass it in the method, random id is called.
In my Activity Class:
for (int j =0;j<it.size();j++){
parentTabFragment.addPage(it.get(j).getTabMenuItem(), it.get(j).getTabMenuId() , selectedMenu);
}
ParentTabFragment:
public void addPage(String pagename, String pageId, String selectedMenu) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
//bundle.putString("pageID", pageId);
childTabFragment = new ChildTabFragment();
childTabFragment.setArguments(bundle);
adapter.addFrag(childTabFragment, pagename, pageId);
adapter.notifyDataSetChanged();
if (selectedMenu == null) {
viewPager.setCurrentItem(0);
} else {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
if (tabLayout.getTabAt(i).getText().equals(selectedMenu)) {
viewPager.setCurrentItem(i);
}
}
}
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
ChildTabFragment:
public class ChildTabFragment extends Fragment {
String childname;
int menuItemId;
TextView textViewChildName, txtViewItemId;
ListView childTabMenuList;
private ArrayList<ChildTabMenu_POJO> childTabMenuPojoList = new ArrayList<>();
private ListView listView;
private ChildTabMenuAdapter childTabMenuAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.child_tab_fragment, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
getIDs(view);
return view;
}
private void getIDs(View view) {
childTabMenuList = (ListView) view.findViewById(R.id.childTabMenuList);
loadChildMenu();
}
private void loadChildMenu(menuItemId) {
ChildTabMenu_POJO menu_pojo4 = new ChildTabMenu_POJO(String.valueOf(menuItemId), "4");
childTabMenuPojoList.add(menu_pojo4);
childTabMenuAdapter = new ChildTabMenuAdapter(childTabMenuPojoList, getActivity());
childTabMenuList.setAdapter(childTabMenuAdapter);
}
public void getTabID(int tabId) {
menuItemId = tabId;
Log.e("updatefrag", String.valueOf(menuItemId));
}
}
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<Adapter_POJO> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
Adapter_POJO adapter_pojo;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public int getItemCount() {
return mFragmentTitleList.size();
}
public void addFrag(Fragment fragment, String title, String pageId) {
mFragmentList.add(fragment);
adapter_pojo = new Adapter_POJO(title,pageId);
mFragmentTitleList.add(adapter_pojo);
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.view_pager_adapter_layout, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
tabItemName.setText(mFragmentTitleList.get(position).adapterMenuItem);
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
return view;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position).adapterMenuItem;
}
public String getPageId(int position){
return mFragmentTitleList.get(position).adapterMenuId;
}
}
If i understand your question so you need to create newInstance constructor for creating fragment with arguments
public static ChildTabFragment newInstance(int page, String title) {
FirstFragment fragmentFirst = new FirstFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
And Store instance variables based on arguments passed in your ChildTabFragment .
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
And now update the view in your onCreateView method
TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
tvLabel.setText(page + " -- " + title);
And the main thing you should returns the ChildTabFragment to display for that page from your ViewPagerAdapter like this.
#Override
public Fragment getItem(int position) {
return ChildTabFragment.newInstance(position,"page "+String.valueOf(position));
}

Unable to get position of selected tab on viewpager

How many tabs will be created it depends on web service. It means I cannot discover how many Tabs are going to be Created until web service is called.
The tabs contain the products which I want to show in grid view.
In my project I have ShopProductsPageFragments.java where tabs get created. Please have look below code :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CatPosition = getArguments().getInt("CatPosition");
StoreID = getArguments().getString("StoreID");
System.out.println("getStoreID in ShopProductsPageFragments="+ StoreID);
System.out.println("getCatPosition in ShopProductsPageFragments="+ CatPosition);
try {
ShopCategoryData = (GetProductCategoriesByStoreResponsePojo) getArguments().getSerializable("ShopCatNames");
}catch (Exception e){
e.printStackTrace();
}
assert ShopCategoryData != null;
List<Datum> shopcatdata = ShopCategoryData.getData();
for (int i = 0; i < shopcatdata.size(); i++) {
System.out.println("ShopCategoryData in ShopProductsPageFragments "+ shopcatdata.get(i).getCatName());
}
ShopProductsPageView = inflater.inflate(R.layout.activity_product_page_fragment ,container ,false);
viewPager = (ViewPager)ShopProductsPageView.findViewById(R.id.product_viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout)ShopProductsPageView.findViewById(R.id.product_tabs);
tabLayout.setupWithViewPager(viewPager);
return ShopProductsPageView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
List<Datum> shopcatdata = ShopCategoryData.getData();
for (int i = 0; i < shopcatdata.size(); i++) {
CommanShopProductFragment commanShopProductFragment = CommanShopProductFragment.newInstance(i);
String CatName = shopcatdata.get(i).getCatName();
Bundle bundle = new Bundle();
bundle.putString("StoreID",StoreID);
bundle.putString("CatName",CatName);
commanShopProductFragment.setArguments(bundle);
System.out.println("ShopCategoryData in ShopProductsPageFragments "+ shopcatdata.get(i).getCatName());
adapter.addFrag(commanShopProductFragment, shopcatdata.get(i).getCatName());
}
adapter.notifyDataSetChanged();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(CatPosition);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
FragmentManager fragmentManager;
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
fragmentManager = manager;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Here, you can see how tabs are created. I am using same fragment for showing data in Tabs as follows:
public class CommanShopProductFragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
View CategoryTabFragmentView;
GetStoreProductsByCategoriesPresenterImpl presenter;
RestClient service;
GridView gridView;
List<Datum> shopProduct;
ProductByCategoryGridViewAdapter mAdapter;
public CommanShopProductFragment() {
// Required empty public constructor
}
public static CommanShopProductFragment newInstance(int position) {
CommanShopProductFragment f = new CommanShopProductFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String CatName = getArguments().getString("CatName");
String StoreID = getArguments().getString("StoreID");
assert CatName != null;
System.out.println("CommanShopProductFragment >>>>>>>> CatName="+CatName);
assert StoreID != null;
System.out.println("CommanShopProductFragment >>>>>>>> StoreID="+StoreID);
CategoryTabFragmentView = inflater.inflate(R.layout.activity_category_tab_fragment ,container ,false);
service = ((LilubiApplication) getActivity().getApplication()).getNetworkService();
presenter = new GetStoreProductsByCategoriesPresenterImpl(this, service);
String page = "1", itemsPerPage = "10";
try {
presenter.GetStoreProductsByCategories(CatName, StoreID, page, itemsPerPage);
}catch (Exception e){
e.printStackTrace();
}
return CategoryTabFragmentView;
}
public void getStoreProductsByCategories(ProductByCategoriesResponsePojo productByCategoriesResponsePojo){
System.out.println("CategoryTabFragment in getMessage="+productByCategoriesResponsePojo.getMessage());
System.out.println("CategoryTabFragment in getStatus="+productByCategoriesResponsePojo.getStatus());
// prepared arraylist and passed it to the Adapter class
shopProduct = productByCategoriesResponsePojo.getData();
mAdapter = new ProductByCategoryGridViewAdapter(getActivity(),shopProduct);
// Set custom adapter to gridview
gridView = (GridView) CategoryTabFragmentView.findViewById(R.id.category_tab_view_grid_view);
gridView.setAdapter(mAdapter);
}
Now what I want is when user selects a tab then list of products should be displayed according to selected category from the tabs.
All product data also comes from web service. Let me know if I missed any thing to explain. Thank you.
I am editing my previous answer
Edit:
you can use viewpager.getCurrentItem() to get current position //include this in your activity with viewpager

TabLayout and ViewPager not showing correctly with two fragments

I have two fragments (Same class- PlayerFragment) and I set the ViewPager with this method:
private void setupViewPager(ViewPager viewPager) {
FragmentManager fManager = getSupportFragmentManager();
ViewPagerAdapter adapter = new ViewPagerAdapter(fManager);
Bundle args1 = new Bundle();
args1.putInt("Id",1);
PlayerFragment pf1 = new PlayerFragment();
pf1.setArguments(args1);
adapter.addFrag(pf1, "Players 1");
Bundle args2 = new Bundle();
args2.putInt("Id",2);
PlayerFragment pf2 = new PlayerFragment();
pf2.setArguments(args2);
adapter.addFrag(pf2, "Players 2");
viewPager.setAdapter(adapter);
}
I have two tabs but only the first tab shows me content, the other tab is empty.
And the first tabs shows me the contentent of the second one.
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
In the activity where I use the fragments I have this code:
final ViewPager viewPager = (ViewPager) findViewById(R.id.vpTeam);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabsTeam);
tabLayout.setupWithViewPager(viewPager);
Thanks!
Edit: This is the PlayerFragment
public class PlayerFragment extends Fragment {
private ProgressDialog progressDialog;
private List<Player> myPlayers = new ArrayList<>();
private int myTeamId = 14;
public PlayerFragment(){
}
public static PlayerFragment newInstance(int someInt) {
PlayerFragment myFragment = new PlayerFragment();
Bundle args = new Bundle();
args.putInt("TeamId", someInt);
myFragment.setArguments(args);
return myFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Bundle args = getArguments();
if(args!=null) {
myTeamId = args.getInt("TeamId");
}
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_player, container, false);
new BackgroundAsyncTask().execute();
return view;
}
}
Can you post the code of PlayerFragment? I'm pretty sure that the error is that you have the variables in that class as static. Also try to use the "new instance()" way for creating fragments --> Best practice for instantiating a new Android Fragment

Transfer data between fragments with pagerAdapter

Current Replaced fragment.
public class SlidingTabsFragment extends Fragment {
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
public SlidingTabsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_sample, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Context context= getActivity();
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
FragmentManager fm = getFragmentManager();
mViewPager.setAdapter(new Harkayin_PagerAdapter(fm,context));
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
...
Here is PagerAdapter, which holds three sliding pages with same fragment /Fragment_Hashvehamarner();/
public class Harkayin_PagerAdapter extends FragmentStatePagerAdapter {
private Context mContext;
public Harkayin_PagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public int getCount() { return 3;}
#Override
public CharSequence getPageTitle(int position) {
String[] tabs= mContext.getResources().getStringArray(R.array.hashvehamar_tabs);
return tabs[position];
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new Fragment_Hashvehamarner();
break;
case 1:
fragment = new Fragment_Hashvehamarner();
break;
case 2:
fragment = new Fragment_Hashvehamarner();
break;
default:
break;
}
if (fragment != null){
return fragment;
}else {
// error in creating fragment
Log.e("Harkayin_PagerAdapter", "Error in creating fragment");
return null;
}
}
}
And finally the page holder fragment
public class Fragment_Hashvehamarner extends Fragment {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
HashMap<String, List<String[]>> listDataChild;
ArrayList<String[]> listHeaderData;
View rootView;
public Fragment_Hashvehamarner() {}
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_hashvayin_plan, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// get the listview
expListView = (ExpandableListView) rootView.findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(rootView.getContext(), listHeaderData,
listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Inflate the layout for this fragment
private void prepareListData() {
DataAdapter mDbHelper = new DataAdapter(rootView.getContext());
mDbHelper.createDatabase();
mDbHelper.open();
listHeaderData = new ArrayList<String[]>(mDbHelper.getHashvehamarHeader(1));
listDataChild = new HashMap<String, List<String[]>>(mDbHelper.getHashvehamarChildData(1));
mDbHelper.close();
}
Now the question: how to get current page position from PageAdapter into current page holder fragment /Fragment_Hashvehamarner()/.
add below method to your Fragment_Hashvehamarner class.
public static final String EXTRA_PAGE_POSITION = "page.position";
public static Fragment_Hashvehamarner newInstance(int id) {
Bundle args = new Bundle();
args.putInt(EXTRA_PAGE_POSITION, id);
Fragment_Hashvehamarner fragment = new Fragment_Hashvehamarner();
fragment.setArguments(args);
return fragment;
}
and in onCreate method of Fragment_Hashvehamarner:
int mSelectedPosition= getArguments().getInt(EXTRA_PAGE_POSITION);
then in your adapter:
public Fragment getItem(int position) {
Fragment fragment = Fragment_Hashvehamarner.newInstance(position);
return fragment;
}

Categories

Resources