Fragment is null while using FragmentStatePagerAdapter - android

I have 3 bottom navigation tabs in my application :
Home
MyTour
Profile
In MyTour, I am using MyTourFragment which have 3 different tabs :
Pending(0)
Success(1)
Failed(2)
For all three tabs(Pending, Success, Failed) I am using FragmentMyTourJobList and depend on condition I am showing pending or success or failed data in all three tabs.
Problem statement :
When I click on MyTour Navigation Item, Pending Fragment instance is coming null and I am only able to see blank fragment but if i click to success or failed then I can see data. Pending tab data is only visible after coming back from other tabs but not initially.
Here is MyTourFragment code :
public class MyTourFragment {
public MyTourFragment() {
}
public static MyTourFragment newInstance(MyTourFragmentListener myTourFragmentListener) {
return new MyTourFragment(myTourFragmentListener);
}
private MyTourFragment(MyTourFragmentListener myTourFragmentListener) {
this.mMyTourFragmentListener = myTourFragmentListener;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewModel.setNavigator(this);
setHasOptionsMenu(true);
//Get the Tab Id.
Bundle bundle = this.getArguments();
if (bundle != null) {
mViewModel.setSelectedDateTimeMillis(bundle.getLong("todaysDateForMyTour", Calendar.getInstance().getTimeInMillis()));
mSelectedTabId = bundle.getInt(KEY_SELECTED_TAB, 0);
}
mMyTourJobsListPagerAdapter = new MyTourJobsListPagerAdapter(this, mViewModel.getTourIdForSelectedDate(), this);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mFragmentMyTourBinding = getViewDataBinding();
mFragmentMyTourBinding.vpMyTour.setOffscreenPageLimit(2);
mFragmentMyTourBinding.vpMyTour.setCurrentItem(0);
mFragmentMyTourBinding.vpMyTour.setAdapter(mMyTourJobsListPagerAdapter);
mFragmentMyTourBinding.tabLayoutMyTour.setupWithViewPager(mFragmentMyTourBinding.vpMyTour, true);
mFragmentMyTourBinding.tabLayoutMyTour.addOnTabSelectedListener(this);
setUpTabs();
}
private void setUpTabs() {
//Select the current Tab.
mFragmentMyTourBinding.vpMyTour.setCurrentItem(mSelectedTabId);
//Refresh job list as per the selected date.
FragmentMyTourJobsList fragmentMyTourJobsList = mMyTourJobsListPagerAdapter.getFragmentAtTab(mSelectedTabId); **// this is null first time**
if (fragmentMyTourJobsList != null) {
fragmentMyTourJobsList.refreshJobsList(mViewModel.getTourIdForSelectedDate());
}
}
}
Here is MyTourJobsListPagerAdapter code :
public class MyTourJobsListPagerAdapter extends FragmentStatePagerAdapter {
private static final int MY_TOUR_JOBS_LIST_PAGES_COUNT = 3;
private static final int POSITION_TAB_PENDING = 0;
private static final int POSITION_TAB_SUCCESS = 1;
private static final int POSITION_TAB_FAILED = 2;
private HashMap<Integer, FragmentMyTourJobsList> mTabsFragments = new HashMap<Integer, FragmentMyTourJobsList>();
private long mTourId;
private FragmentMyTourJobsList.FragmentMyTourJobsListListener mFragmentMyTourJobsListListener;
public MyTourJobsListPagerAdapter(Fragment fragment, long tourId, FragmentMyTourJobsList.FragmentMyTourJobsListListener fragmentMyTourJobsListListener) {
super(fragment.getChildFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.mTourId = tourId;
this.mFragmentMyTourJobsListListener = fragmentMyTourJobsListListener;
}
public void setTourId(long tourId) {
this.mTourId = tourId;
}
#Override
public int getCount() {
return MY_TOUR_JOBS_LIST_PAGES_COUNT;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
mTabsFragments.put(position, (FragmentMyTourJobsList) fragment);
return fragment;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
mTabsFragments.remove(position);
super.destroyItem(container, position, object);
}
#Override
public Fragment getItem(int position) {
FragmentMyTourJobsList fragmentMyTourJobsList;
switch (position) {
case POSITION_TAB_SUCCESS:
fragmentMyTourJobsList = getFragmentWithBundle(Constants.JOB_STATUS_SUCCESSFUL);
break;
case POSITION_TAB_FAILED:
fragmentMyTourJobsList = getFragmentWithBundle(Constants.JOB_STATUS_FAILED);
break;
case POSITION_TAB_PENDING:
default:
fragmentMyTourJobsList = getFragmentWithBundle(Constants.JOB_STATUS_ACCEPTED);
break;
}
return fragmentMyTourJobsList;
}
public FragmentMyTourJobsList getFragmentAtTab(int tabPosition) {
return mTabsFragments.get(tabPosition);
}
private FragmentMyTourJobsList getFragmentWithBundle(String jobsStatus) {
FragmentMyTourJobsList fragmentToLoad = FragmentMyTourJobsList.newInstance();
Bundle bundle = new Bundle();
bundle.putString(FragmentMyTourJobsList.KEY_ARG_JOBS_STATUS, jobsStatus);
bundle.putLong(FragmentMyTourJobsList.KEY_ARG_TOUR_ID, mTourId);
bundle.putSerializable(FragmentMyTourJobsList.KEY_ARG_FRAGMENT_MY_TOUR_JOBS_LIST_LISTENER, mFragmentMyTourJobsListListener);
fragmentToLoad.setArguments(bundle);
return fragmentToLoad;
}
}
Everything is working but when i will go to Pending tab first time then it's not working. I am missing anything here?
Added FragmentMytourJobList
public class FragmentMyTourJobsList extends BaseFragment<FragmentMyTourJobsListBinding, MyTourJobsListViewModel> implements MyTourJobsListNavigator {
public static FragmentMyTourJobsList newInstance() {
return new FragmentMyTourJobsList();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewModel.setNavigator(this);
Bundle bundle = this.getArguments();
if (bundle != null) {
mJobsStatus = bundle.getString(KEY_ARG_JOBS_STATUS);
mTourId = bundle.getLong(KEY_ARG_TOUR_ID, 0);
}
}
#Override
public int getBindingVariable() {
return myTourJobsListViewModel;
}
#Override
public int getLayoutId() {
return R.layout.fragment_my_tour_jobs_list;
}
#Override
public MyTourJobsListViewModel getViewModel() {
mViewModel = ViewModelProviders.of(this, new ViewModelProviderFactory(Objects.requireNonNull(getActivity()).getApplication())).get(MyTourJobsListViewModel.class);
return mViewModel;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mFragmentMyTourJobsListBinding = getViewDataBinding();
// fetch job list from database
ArrayList<JobUiModel> jobList = mViewModel.fetchJobs(mTourId, mJobsStatus);
RecyclerView.LayoutManager rvLayoutManager = new LinearLayoutManager(getActivity());
mFragmentMyTourJobsListBinding.rvMyTourJobs.setLayoutManager(rvLayoutManager);
// initialize adapter
mJobsListAdapter = new MyTourJobsListAdapter(getContext(), jobList, mJobsStatus);
mFragmentMyTourJobsListBinding.rvMyTourJobs.setAdapter(mJobsListAdapter);
mJobsListAdapter.setClickInterface(this);
mFragmentMyTourJobsListBinding.rvMyTourJobs.addItemDecoration(new EndOffsetItemDecoration(CommonUtils.dpToPx(56)));
}
void refreshJobsList(long tourId) {
if (tourId > 0) {
mTourId = tourId;
mViewModel.fetchJobs(tourId, mJobsStatus);
// fetch job list from database
ArrayList<JobUiModel> jobList = mViewModel.fetchJobs(mTourId, mJobsStatus);
mJobsListAdapter.setDataset(jobList);
mJobsListAdapter.notifyDataSetChanged();
} else {
mJobsListAdapter.setDataset(null);
mJobsListAdapter.notifyDataSetChanged();
}
}
}

Related

How to send input from searchview which is in an activity to fragment which is in the view pager of that activity

So i have a searchview placed in an activity which has a tablayout and viewpager.In the viewpager there is a fragment for each tab with a textview.What im trying to do is to get the input from the searchview and set the text of the textview with that input and i cant seem to be able to do it.I tried to put the input from the searchview in a bundle(this being done in the activity),and then get the arguments in the fragment in onCreateView() but the problem is that the activity and the fragment are being created simultaneously wthich means that the input from the searchview would be null.
This is the Activity:
public class SearchActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
SearchView searchView;
Toolbar toolbar;
ImageButton imageButtonBack;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
bindUI();
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.AddFragment(new NewestFragment(), "Newest"); // this line can cause crashes
viewPagerAdapter.AddFragment(new OldestFragment(), "Oldest"); // this line can cause crashes
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
setSearchView();
setImageButtonBack();
}
private void setSearchView() {
searchView.requestFocus();
View v = searchView.findViewById(R.id.search_plate);
v.setBackgroundColor(Color.parseColor("#ffffff"));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Bundle bundle = new Bundle();
bundle.putString("searchViewText", searchView.getQuery().toString());
NewestFragment newestFragment = new NewestFragment();
OldestFragment oldestFragment = new OldestFragment();
newestFragment.setArguments(bundle);
oldestFragment.setArguments(bundle);
searchView.clearFocus();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Bundle bundle = new Bundle();
bundle.putString("searchViewText", searchView.getQuery().toString());
NewestFragment newestFragment = new NewestFragment();
OldestFragment oldestFragment = new OldestFragment();
newestFragment.setArguments(bundle);
oldestFragment.setArguments(bundle);
return false;
}
});
}
private void bindUI() {
imageButtonBack = findViewById(R.id.back);
tabLayout = findViewById(R.id.tabs);
viewPager = findViewById(R.id.view_pager);
searchView = findViewById(R.id.search_view_searchactivity);
toolbar = findViewById(R.id.toolbar_selected_category);
}
private void setImageButtonBack() {
imageButtonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
The adapter of the ViewPager:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>(); // this line can cause crashes
private final List<String> titlesList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fragmentManager) {
super(fragmentManager);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return titlesList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titlesList.get(position);
}
public void AddFragment(Fragment fragment, String title) {
fragmentList.add(fragment); // this line can cause crashes
titlesList.add(title);
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
And here is the fragment:
public class NewestFragment extends Fragment {
View view;
TextView textView;
public NewestFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_search_newest, container, false);
textView=view.findViewById(R.id.tttttttttttttttttttt);
try {
String searchViewText=getArguments().getString("searchViewText");
textView.setText(searchViewText);
}
catch (Exception e){
//something
}
return view;
}
}
The fragments are attached to activity so first activity is created lets leave that but I think you should use a MVVM pattern and create viewmodel and then you can observe the search view and update the fragment textview using that viewmodel class
https://codelabs.developers.google.com/codelabs/kotlin-android-training-live-data/index.html#0
To change the fragments that are created by a FragmentPagerAdapter, you should use a DynamicFragmentPagerAdapter. Refer to the following code below.
public class DynamicFragmentPagerAdapter extends PagerAdapter {
private static final String TAG = "DynamicFragmentPagerAdapter";
private final FragmentManager fragmentManager;
public static abstract class FragmentIdentifier implements Parcelable {
private final String fragmentTag;
private final Bundle args;
public FragmentIdentifier(#NonNull String fragmentTag, #Nullable Bundle args) {
this.fragmentTag = fragmentTag;
this.args = args;
}
protected FragmentIdentifier(Parcel in) {
fragmentTag = in.readString();
args = in.readBundle(getClass().getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(fragmentTag);
dest.writeBundle(args);
}
protected final Fragment newFragment() {
Fragment fragment = createFragment();
Bundle oldArgs = fragment.getArguments();
Bundle newArgs = new Bundle();
if(oldArgs != null) {
newArgs.putAll(oldArgs);
}
if(args != null) {
newArgs.putAll(args);
}
fragment.setArguments(newArgs);
return fragment;
}
protected abstract Fragment createFragment();
}
private ArrayList<FragmentIdentifier> fragmentIdentifiers = new ArrayList<>();
private FragmentTransaction currentTransaction = null;
private Fragment currentPrimaryItem = null;
public DynamicFragmentPagerAdapter(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
private int findIndexIfAdded(FragmentIdentifier fragmentIdentifier) {
for (int i = 0, size = fragmentIdentifiers.size(); i < size; i++) {
FragmentIdentifier identifier = fragmentIdentifiers.get(i);
if (identifier.fragmentTag.equals(fragmentIdentifier.fragmentTag)) {
return i;
}
}
return -1;
}
public void addFragment(FragmentIdentifier fragmentIdentifier) {
if (findIndexIfAdded(fragmentIdentifier) < 0) {
fragmentIdentifiers.add(fragmentIdentifier);
notifyDataSetChanged();
}
}
public void removeFragment(FragmentIdentifier fragmentIdentifier) {
int index = findIndexIfAdded(fragmentIdentifier);
if (index >= 0) {
fragmentIdentifiers.remove(index);
notifyDataSetChanged();
}
}
#Override
public int getCount() {
return fragmentIdentifiers.size();
}
#Override
public void startUpdate(#NonNull ViewGroup container) {
if (container.getId() == View.NO_ID) {
throw new IllegalStateException("ViewPager with adapter " + this
+ " requires a view id");
}
}
#SuppressWarnings("ReferenceEquality")
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
final FragmentIdentifier fragmentIdentifier = fragmentIdentifiers.get(position);
// Do we already have this fragment?
final String name = fragmentIdentifier.fragmentTag;
Fragment fragment = fragmentManager.findFragmentByTag(name);
if (fragment != null) {
currentTransaction.attach(fragment);
} else {
fragment = fragmentIdentifier.newFragment();
currentTransaction.add(container.getId(), fragment, fragmentIdentifier.fragmentTag);
}
if (fragment != currentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
currentTransaction.detach((Fragment) object);
}
#SuppressWarnings("ReferenceEquality")
#Override
public void setPrimaryItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
Fragment fragment = (Fragment) object;
if (fragment != currentPrimaryItem) {
if (currentPrimaryItem != null) {
currentPrimaryItem.setMenuVisibility(false);
currentPrimaryItem.setUserVisibleHint(false);
}
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
currentPrimaryItem = fragment;
}
}
#Override
public void finishUpdate(#NonNull ViewGroup container) {
if (currentTransaction != null) {
currentTransaction.commitNowAllowingStateLoss();
currentTransaction = null;
}
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return ((Fragment) object).getView() == view;
}
#Override
public Parcelable saveState() {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("fragmentIdentifiers", fragmentIdentifiers);
return bundle;
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
Bundle bundle = ((Bundle)state);
bundle.setClassLoader(loader);
fragmentIdentifiers = bundle.getParcelableArrayList("fragmentIdentifiers");
}
}

Added fragments to viewpager are empty

the fragments show an empty screen in the viewpager
Have used this library for adding tabs gihub
Referred to this solution for adding the fragments adding fragments to viewpager
Here is the code
public class HorizontalNtbActivity extends android.support.v4.app.FragmentActivity {
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_horizontal_ntb);
initUI();
}
private void initUI() {
CreateFragment createFragment = new CreateFragment();
GroupFragment groupFragment= new GroupFragment();
HomeFragment homeFragment= new HomeFragment();
ProfileFragment profileFragment = new ProfileFragment();
DashPagerAdapter dashPagerAdapter = new DashPagerAdapter(getSupportFragmentManager(),4);
dashPagerAdapter.addFragment(homeFragment);
dashPagerAdapter.addFragment(createFragment);
dashPagerAdapter.addFragment(profileFragment);
dashPagerAdapter.addFragment(groupFragment);
final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
viewPager.setAdapter(dashPagerAdapter);
final String[] colors = getResources().getStringArray(R.array.tabcolors);
final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
final ArrayList<NavigationTabBar.Model> models = new ArrayList<>();
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_first),
Color.parseColor(colors[0]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_sixth))
.title("Home")
.badgeTitle("NTB")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_second),
Color.parseColor(colors[1]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_eighth))
.title("Groups")
.badgeTitle("with")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_third),
Color.parseColor(colors[2]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_seventh))
.title("Create")
.badgeTitle("state")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_fourth),
Color.parseColor(colors[3]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_eighth))
.title("Profile")
.badgeTitle("icon")
.build()
);
navigationTabBar.setBgColor(Color.parseColor("#424242"));
navigationTabBar.setActiveColor(Color.parseColor("#ffffff"));
navigationTabBar.setInactiveColor(Color.parseColor("#9E9E9E"));
navigationTabBar.setModels(models);
navigationTabBar.setViewPager(viewPager, 0);
navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
navigationTabBar.getModels().get(position).hideBadge();
Toast.makeText(HorizontalNtbActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(final int state) {
}
});
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
for (int i = 0; i < navigationTabBar.getModels().size(); i++) {
final NavigationTabBar.Model model = navigationTabBar.getModels().get(i);
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
model.hideBadge();
}
}, i * 100);
}
}
}, 500);
}}
This is the Adapter
public class DashPagerAdapter extends FragmentPagerAdapter {
public final List<Fragment> fragments = new ArrayList<>();
public DashPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
int mNumOfTabs;
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: {
return HomeFragment.newInstance("sdfsdfsdfsdf");
}
case 1: {
return CreateFragment.newInstance("adfsdfsfd");
}
case 2: {
return GroupFragment.newInstance("adfsdfsfd");
}
case 3: {
return ProfileFragment.newInstance("abcd");
}
default:
return null;
}
}
public void addFragment(Fragment fragment) {
fragments.add(fragment);
notifyDataSetChanged();
}
#Override
public boolean isViewFromObject(final View view, final Object object) {
return view.equals(object);
}
#Override
public int getCount() {
return 4;
}
}
These is a fragment. All the other fragments are similar
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
TextView textView = (TextView) view.findViewById(R.id.homefragmenttextview);
textView.setText(getArguments().getString("msg"));
// Inflate the layout for this fragment
return view;
}
public static HomeFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString("msg", text);
HomeFragment fragment = new HomeFragment();
fragment.setArguments(args);
return fragment;
}
}
Here is how it looks
image for reference
In your adapter, change this
#Override
public boolean isViewFromObject(final View view, final Object object)
{
return view.equals(object);
}
To this
#Override
public boolean isViewFromObject(final View view, final Object object)
{
return view == object;
}

Update the row item data of recyclerview

The fragment consists of View Pager which shows the product count that
needs to be updated when the product is deleted or added .
public class SubCategoryFragment extends BaseFragment implements OnItemClickListener
{
private View rootView;
private MasterCategory subCategory;
private RecyclerView subCategoryRecyclerView;
private SubCategoryListAdapter subCategoryListAdapter;
private ArrayList<MasterCategory> superSubCategories;
private String iconImageURL;
private ArrayList<MerchantOrder> merchantorder;
/*private IRequestComplete iRequestComplete;*/
private int categoryId;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return rootView = inflater.inflate(R.layout.fragment_category_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
initialiseUI();
}
initialise fragment
protected void initialiseUI()
{
categoryId = getArguments().getInt("categoryId");
iconImageURL = (String) getArguments().getSerializable("iconImageURL");
subCategory = (MasterCategory) getArguments().getSerializable("data");
subCategoryRecyclerView = (RecyclerView) rootView.findViewById(R.id.category_list_rc_view);
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
subCategoryRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(context);
subCategoryRecyclerView.setLayoutManager(mLayoutManager);
superSubCategories = subCategory.getCategories();
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
if (superSubCategories != null && !superSubCategories.isEmpty())
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories, iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
subCategoryListAdapter.setmOnItemClickListener(this);
updateListView();
}
else
{
rootView.findViewById(R.id.text_no_order_error).setVisibility(View.VISIBLE);
((TextView) rootView.findViewById(R.id.text_no_order_error)).setText("No Category found!");
}
}
Update the listview
private void updateListView()
{
if (subCategoryListAdapter == null)
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories,iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
}
else
{
subCategoryListAdapter.notifyDataSetChanged();
}
subCategoryListAdapter.notifyDataSetChanged();
}
the itemclick opens up a fragment which displays the product details
#Override
public void onItemClick(View view, int position)
{
/*MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryProductsFragment superSubCategoryProductsFragment = new SuperSubCategoryProductsFragment();
superSubCategoryProductsFragment.setArguments(bundle);
manageFragment(superSubCategoryProductsFragment, SuperSubCategoryProductsFragment.class.getName(), CategoryDetailsFragment.class.getName(), bundle);*/
/*ArrayList<MasterCategory> superSubCategories = subCategoryListAdapter.getSuperSubCategory(position).getCategories();
if (null != superSubCategories){
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryListFragment categoryDetailsFragment = new SuperSubCategoryListFragment();
categoryDetailsFragment.setArguments(bundle);
manageFragment(categoryDetailsFragment, SuperSubCategoryListFragment.class.getName(), SubCategoryFragment.class.getName(), null);
}*/
MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
superSubCategories.getSubCategoryCount();
superSubCategories.getProductCount();
subCategoryListAdapter.notifyDataSetChanged();
if (superSubCategories.isHasChildCategory())
{
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
Intent intent = new Intent(context, BaseFragmentActivity.class);
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SuperSubCategoryFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
else
{
Intent intent = new Intent(context, BaseFragmentActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("categoryId", superSubCategories.getCategoryId());
bundle.putString("categoryName", superSubCategories.getName());
bundle.putBoolean("isSubCatProducts", !superSubCategories.isHasChildCategory());
bundle.putInt("ProductCount", superSubCategories.getProductCount());
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SubCategoryProductsFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(subCategoryRecyclerView);
subCategoryRecyclerView.getAdapter().notifyDataSetChanged();
}
}
This is my Adapter attached to the fragment
public class SubCategoryListAdapter extends RecyclerView.Adapter<SubCategoryListAdapter.ViewHolder> implements View.OnClickListener {
private static final String TAG = SubCategoryListAdapter.class.getSimpleName();
private ArrayList<MasterCategory> superSubCategories;
private ImageLoader imageloader;
private com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener;
private String iconImageURL;
#Override
public void onClick(View view)
{
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(view, (Integer) view.getTag());
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView name;
public TextView productCount;
public NetworkImageView image;
public ViewHolder(View itemLayoutView)
{
super(itemLayoutView);
productCount = (TextView) itemLayoutView.findViewById(R.id.product_count);
name = (TextView) itemLayoutView.findViewById(R.id.name);
image = (NetworkImageView) itemLayoutView.findViewById(R.id.image);
}
}
public SubCategoryListAdapter(ArrayList<MasterCategory> superSubCategories, String iconImageURL)
{
this.superSubCategories = superSubCategories;
imageloader = Global.getInstance().getImageLoader();
this.iconImageURL = iconImageURL;
}
#Override
public SubCategoryListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.super_category_list_row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position)
{
holder.name.setText("" + superSubCategories.get(position).getName());
holder.image.setDefaultImageResId(R.drawable.logo_amoda);
holder.image.setImageUrl(iconImageURL, imageloader);
if(!superSubCategories.get(position).isHasChildCategory())
{
holder.productCount.setText("" + superSubCategories.get(position).getProductCount());
}
else
{
holder.productCount.setText("");
holder.productCount.setBackgroundResource(R.drawable.icn_right_arrow);
}
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(this);
}
public void setmOnItemClickListener(com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener)
{
this.mOnItemClickListener = mOnItemClickListener;
}
#Override
public int getItemCount()
{
if (superSubCategories != null)
return superSubCategories.size();
else
return 0;
}
public MasterCategory getSuperSubCategory(int position)
{
return superSubCategories.get(position);
}
}
This is my View pager in my activity
private void showSubCategoryTabs()
{
setToolbarTitle(category != null ? category.getName() : "");
try
{
mPromotionalImage.setDefaultImageResId(R.drawable.nodeals_img);
mPromotionalImage.setImageUrl(category.getImageUrl(), imageLoader);
}
catch (Exception e)
{
e.printStackTrace();
}
tabContent = new ArrayList<String>();
for (MasterCategory subCategories : category.getCategories())
{
/*Check if the sub-sub category has super-sub category or not.*/
if (null != subCategories.getCategories())
tabContent.add(subCategories.getName());
}
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
Fragment fragment = ((SectionsPagerAdapter) mViewPager.getAdapter()).getFragment(position);
if (fragment != null)
{
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter
{
private SectionsPagerAdapter sectionspageradapter;
private FragmentManager fragmentManager=null;
private Bundle bundle=new Bundle();
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
fragmentManager=fm;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
Object obj=super.instantiateItem(container,position);
if(obj instanceof Fragment)
{
Fragment f=(Fragment)obj;
String tag=f.getTag();
f.onResume();
}
return obj;
}
#Override
public Fragment getItem(int position)
{
MasterCategory subCategories = category.getCategories().get(position);
if (subCategories.isHasChildCategory())
{
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("iconImageURL", category.getIconImageUrl());
bundle.putSerializable("data", category.getCategories().get(position));
subCategoryFragment.setArguments(bundle);
return subCategoryFragment;
}
else
{
SubCategoryProductsFragment subCategoryProductsFragment = new SubCategoryProductsFragment();
Bundle bundle = new Bundle();
bundle.putInt("categoryId", subCategories.getCategoryId());
bundle.putString("categoryName", subCategories.getName());
bundle.putBoolean("isSubCatProducts", true);
subCategoryProductsFragment.setArguments(bundle);
return subCategoryProductsFragment;
}
}
#Override
public int getCount()
{
return tabContent.size();
}
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
return tabContent.get(position);
}
public Fragment getFragment(int position)
{
String tag = String.valueOf(mMerchantSubCategories.get(position));
return fragmentManager.findFragmentByTag(tag);
}
}
#Override
public void onResume()
{
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
super.onResume();
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
//*Unregister event bus when the app goes in background*//*
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
public void onError(VolleyError volleyError)
{
UIHelper.stopProgressDialog(mProgressDialog);
Functions.Application.VolleyErrorCheck(this, volleyError);
}
just add this method to your viewPager adapter and your problem is solved.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this is override method of viewPager.
when you swipe one fragment to another it will automatically refresh page.
try this approach.. maybe its work for you..
put this code in your SubCategoryListAdepter
public void delete(int position) { //removes the row
superSubCategories.remove(position);
notifyItemRemoved(position);
}
make onClickListener to your ViewHolder:
suppose you click on your text and this row will be deleted.
#Override
public void onClick(View v) {
if(v.getId() == R.id.name){
//calls the method above to delete
delete(getAdapterPosition());
}
now you can also add data like this way.. thats working fine at runtime.. no need to refresh your page.

Strange behavior of ViewPager

I am using for my Android app PagerSlidingTabStrip and Material Navigation Drawer libraries. I am watching strange behavior of ViewPager - when I am opening it first time, it works normally, but I am opening it again, ViewPager is empty, as without adapter.
MainActivity:
public class MainActivity extends AppCompatActivity {
private Drawer drawer;
private int lastSelection;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private boolean isClickedByUser = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = new DrawerBuilder().withActivity(MainActivity.this)
.withToolbar(toolbar).addDrawerItems(
new PrimaryDrawerItem().withName(R.string.name1)
.withIcon(R.drawable.icon1),
new PrimaryDrawerItem()
.withName(R.string.name2)
.withIcon(R.drawable.icon2))
.withOnDrawerItemClickListener(
new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(AdapterView<?> adapterView, View view,
int position, long id,
IDrawerItem iDrawerItem) {
switch (position) {
case 0:
setTitle(R.string.title1);
break;
case 1:
setTitle(R.string.title2);
break;
}
FragmentManager fManager = getSupportFragmentManager();
FragmentTransaction transaction = fManager.beginTransaction();
transaction.replace(R.id.container, PlaceholderFragment.newInstance(
position)).commitAllowingStateLoss();
lastSelection = position;
return false;
}
})
.build();
drawer.setSelection(0);
}
#Override
public void onBackPressed() {
if (drawer != null && drawer.isDrawerOpen()) {
drawer.closeDrawer();
} else {
super.onBackPressed();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
drawer.setSelection(lastSelection);
}
}
PlaceholderFragment, in that ViewPager is done:
public class PlaceholderFragment extends Fragment {
private static final String ID = "id";
private int id;
public static PlaceholderFragment newInstance(int id) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch (id) {
case 0:
rootView = inflater.inflate(R.layout.view1, container, false);
break;
case 1:
rootView = inflater.inflate(R.layout.tabs, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.viewPager);
pager.setAdapter(new PagerAdapter(getActivity().getSupportFragmentManager()));
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setShouldExpand(true);
tabs.setIndicatorColorResource(R.color.tab_indicator_color);
tabs.setTextColorResource(R.color.tab_text_color);
break;
default:
break;
}
return rootView;
}
private class PagerAdapter extends FragmentPagerAdapter {
private int[] titlesResIds = { R.string.title1, R.string.title2 };
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return getString(titlesResIds[position]);
}
#Override
public int getCount() {
return titlesResIds.length;
}
#Override
public Fragment getItem(int position) {
return TabFragment.newInstance(position);
}
}
}
TabFragment:
public class TabFragment extends ListFragment {
private static final String ID = "id";
private int id;
public static TabFragment newInstance(int id) {
TabFragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
public TabFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://host/")
.build();
String result = null;
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(response));
reader.setLenient(true);
ArrayList<Message> messages = gson.fromJson(reader,
new TypeToken<ArrayList<Message>>(){}.getType());
int i = messages.size() - 1;
while (i != -1) {
if (messages.get(i).getType() != id)
messages.remove(i);
i--;
}
ArrayAdapter adapter = new MyListAdapter(messages);
setListAdapter(adapter);
}
};
asyncTask.execute();
return inflater.inflate(R.layout.fragment, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent messageIntent = new Intent(getActivity(), MessageActivity.class);
startActivity(messageIntent);
}
private class MyListAdapter extends ArrayAdapter {
private Context context = getActivity();
private ArrayList<Message> messages;
public MyListAdapter(ArrayList<Message> messages) {
super(getActivity(), R.layout.list_adapter);
this.messages = messages;
}
#Override
public int getCount() {
return messages.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_adapter, parent, false);
holder = new ViewHolder();
holder.imageIcon = (ImageView) convertView.findViewById(R.id.list_icon);
holder.textDatetime = (TextView) convertView.findViewById(R.id.list_text_datetime);
holder.textPrimary = (TextView) convertView.findViewById(R.id.list_text_primary);
holder.textSecondary = (TextView) convertView.findViewById(R.id.list_text_secondary);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Message message = messages.get(position);
long timestamp = message.getTimestamp() * 1000;
Date date = new Date(timestamp);
String datetime = new SimpleDateFormat("dd.MM.yyyy hh:mm", Locale.US).format(date);
holder.imageIcon.setImageResource(message.getIcon() == 0 ?
R.drawable.icon1 :
R.drawable.icon2);
holder.textDatetime.setText(datetime);
holder.textPrimary.setText(message.getTitle());
holder.textSecondary.setText(message.getMessage());
return convertView;
}
private class ViewHolder {
ImageView imageIcon;
TextView textDatetime;
TextView textPrimary;
TextView textSecondary;
}
}
}
I already decided my problem. I'm insert method getChildFragmentManager() in my PlaceholderFragment as in this answer - How set ViewPager inside a Fragment.

Android - Sending data from fragment to fragment using swipeview

Could be this is a dupe, but I've been looking for solutions and they always slightly differ from my problem.
So:
I'm currently creating an app that has 2 fragments that are swipeable. TaskGroupFragment shows a list and when you click on an item it wil slide to TasksFragment and show you a sublist. What I have to do now is send the id of the selected item from groups to tasks so I can get the sublist out of SQLite.
I know I'm supposed to communicate through the connected MainActivity and I'm already at the point that I've created an interface in TaskGroupsFragment and implemented this in the activity. Tried and tested and the activity receives the TaskGroupID.
The part where I'm stuck is getting this info in TasksFragment. Especially using swipeview makes this harder.
My code:
MainPagerAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
case 1: return TasksFragment.newInstance();
default: return TaskGroupFragment.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
TaskGroupActivity (sending fragment):
public class TaskGroupFragment extends ListFragment {
private DoItDataSource dataSource;
private List<TaskGroups> groups;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_group, container, false);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
JSONContainer jsonContainer = dataSource.sqliteToContainer();
dataSource.close();
groups = jsonContainer.getTask_groups();
TaskGroupAdapter adapter = new TaskGroupAdapter(getActivity(), groups);
setListAdapter(adapter);
return view;
}
public static TaskGroupFragment newInstance() {
TaskGroupFragment tgf = new TaskGroupFragment();
return tgf;
}
public interface OnTaskGroupSelectedListener {
public void onTaskGroupSelected(String taskGroupId);
}
OnTaskGroupSelectedListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnTaskGroupSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " Interface not implemented in activity");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((MainActivity)getActivity()).setCurrentItem(1, true);
mListener.onTaskGroupSelected(groups.get(position).getId());
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
pager = (ViewPager) findViewById(R.id.activity_main_pager);
pager.setAdapter(new MainPagerAdapter(getSupportFragmentManager()));
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// getting lists
//
}
private void resultHandling(String json, String day) {
if (day.equals("today")) {
Gson gson = new Gson();
containerToday = gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerToday, "Today");
} else if (day.equals("tomorrow")) {
Gson gson = new Gson();
containerTomorrow= gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerTomorrow, "Tomorrow");
}
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// Enter missing link here?
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment
implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button)
view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
tasks = dataSource.getTasks("204"); // 204 is a placeholder, TaskGroupId should be here
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
public static TasksFragment newInstance() {
TasksFragment tif = new TasksFragment();
return tif;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Solution
Thanks to Alireza! I had to make several changes to his proposed code, but in the end it helped me in finding the solution!
MainPageAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
// ADDED
private String taskGroupId;
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
// MODIFIED
case 1:
Bundle args = new Bundle();
logcat("before setBundle " + taskGroupId);
args.putString("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
default: return TaskGroupFragment.newInstance();
}
}
// ADDED
public void setTaskGroupId(String id){
this.taskGroupId = id;
}
#Override
public int getCount() {
return 2;
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
// ADDED
private MainPagerAdapter adapter;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
// ADDED
adapter = new MainPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.activity_main_pager);
// MODIFIED
pager.setAdapter(adapter);
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// Getting lists
//
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// ADDED
adapter.setTaskGroupId(taskGroupId);
pager.setAdapter(adapter);
pager.setCurrentItem(1);
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
private String taskGroupId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button) view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
// ADDED
Bundle bundle = getArguments();
taskGroupId = bundle.getString("taskGroupId");
// MODIFIED
dataSource.open();
tasks = dataSource.getTasks(taskGroupId);
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
// CAN BE REMOVED?
//public static TasksFragment newInstance() {
// TasksFragment tif = new TasksFragment();
// return tif;
//}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Please note that I'm using taskGroupId as a String, not an int.
First you need to make sure your adapter knows about taskGroupID. just add a variable and a public method to your adapter.
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private int taskGroupId;
public void setTaskGroupId(int id){
this.taskGroupId = id;
}
}
then store a reference to your adapter in your activity. Now simply call this method whenever GroupId changes
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
adapter.setTastGroupId = taskGroupId; //data needed to initialize fragment.
adapter.setCurrentItem(1); //going to TasksFragment page
}
then you need to put some argumants before starting your fragment.
#Override
public Fragment getItem(int i) {
//this code is only for case 1:
Bundle args = new Bundle();
args.putInt("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
}
and lastly use this data in your TaskFragment to show the right content.

Categories

Resources