Update view pager indicator from fragment - android

i'am tryning to update my view pager indicator from my fragment.
My problem is the project is structured like this:
MainActivity -> FragmentA -> FragmentStatePagerAdapter -> FragmentProduct
I've tried implementing an interface in the adapter but the adapter isn't able to catch the event, only the mainActivity is catching the event.
So the only thing i want it's to update view pager (FragmentStatePagerAdapter) from the fragment.
MainActivity:
public class ProductDetailActivity extends ActivityBase implements ProductFragment.OnFragmentInteractionListener, TabIndicatorListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void updateTabIndicator(ProductFragment productFragment) {
} }
**FragmentA - Set adapter etc etc **
public class ProductFragmentDetails extends FragmentBase {
private NavigationHelper navHelper = NavigationHelper.getInstance();
ViewPager viewPager;
PagerAdapter adapter;
TabPageIndicator indicator;
List<ProductPagerAdapter.RegisterValue> prices;
private FragmentManager fm;
ProductPagerAdapter pagerUpdater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
createDummyPrices();
View mainView = inflater.inflate(R.layout.fragment_product_details, container);
viewPager = (ViewPager) mainView.findViewById(R.id.pager);
viewPager.setVisibility(View.VISIBLE);
indicator = (TabPageIndicator) mainView.findViewById(R.id.indicator);
fm = getActivity().getSupportFragmentManager();
adapter = new ProductPagerAdapter(fm, getActivity().getApplicationContext(), indicator, prices);
viewPager.setAdapter(adapter);
indicator.setViewPager(viewPager);
indicator.setVisibility(View.VISIBLE);
return mainView;
}}
FragmentStateAdapter
public class ProductPagerAdapter extends FragmentStatePagerAdapter implements IconPagerAdapter, TabIndicatorListener {
... init vars etc etc
#Override
public void startUpdate(ViewGroup container) {
super.startUpdate(container);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
return Integer.toString(position + 1);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) { super.setPrimaryItem(container, position, object);
}
#Override
public void finishUpdate(ViewGroup container) {
super.finishUpdate(container);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return super.isViewFromObject(view, object);
}
#Override
public Parcelable saveState() {
return super.saveState();
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
super.restoreState(state, loader);
}
/**
* Get icon representing the page at {#code index} in the adapter.
*
* #param index
*/
#Override
public int getIconResId(int index) {
return prices.get(index).icon;
}
#Override
public int getCount() {
return prices.size(); //The number of items in the pagerAdapter must be equal to number of products
}
// Instantiate the fragment to display for that page
#Override
public Fragment getItem(int position) {
String productPrice = Double.toString(prices.get(position).price);
return ProductFragment.newInstance(productPrice, "OBS");
}
#Override
public void updateTabIndicator(ProductFragment productFragment) {
}
FragmentProduct
public class ProductFragment extends FragmentBase {
init some vars and fields....
Context context;
TabIndicatorListener tabIndicatorListener;
public static ProductFragment newInstance(String price, String observations) {
ProductFragment fragment = new ProductFragment();
Bundle args = new Bundle();
args.putString(ARG_PRICE, price);
args.putString(ARG_OBSERVATIONS, observations);
fragment.setArguments(args);
return fragment;
}
public ProductFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
if (getArguments() != null) {
mParamPrice = getArguments().getString(ARG_PRICE);
mParamObservation = getArguments().getString(ARG_OBSERVATIONS);
}
try {
tabIndicatorListener = (TabIndicatorListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement TabIndicatorListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View productView = inflater.inflate(R.layout.fragment_product, container, false);
initViews(productView); //Its initialized the views..
btnAbsent.setOnClickListener(clickOnBtnAbsent);
btnValidate.setOnClickListener(clickOnBtnValidate);
editTxtPrice.setText(String.valueOf(mParamPrice));
return productView;
}
/**
* #param productView
*/
private void initViews(View productView) {
txtViewProductName = (TextView) productView.findViewById(R.id.txtViewNameProduct);
txtViewPrice = (TextView) productView.findViewById(R.id.txtViewPrice);
}
#Override
protected int getActionBarMenuRes() {
return 0;
}
#Override
protected int getMainLayoutRes() {
return 0;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public View.OnClickListener clickOnBtnAbsent = new View.OnClickListener() {
#Override
public void onClick(View v) {
tabIndicatorListener.updateTabIndicator(ProductFragment.this);
//Here is where i want to update my view pager indicator
}
};
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}

First of all I'm surprised that you didn't encounter problems due to the FragmentManager you used. Instead of :
fm = getActivity().getSupportFragmentManager();
you should use the dedicated FragmentManager for nested fragments:
fm = getChildFragmentManager();
Secondly, related to the listener target you can use one of the methods of the fragment class, getParentFragment(). This method returns, for nested fragments, the container fragment:
// in ProductFragment
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mListener = ((ProductFragmentDetails) getParentFragment()).getListener();
}
In ProductFragmentDetails you'll have the method:
public (OnFragmentInteractionListener) getListener() {
return (OnFragmentInteractionListener) adapter;
}

Related

How to create a multi-step registration form using viewpager and multiple fragments?

I want to create a multi-step registration form in my android app. I wish to use the viewpager with multiple fragments and each fragment being a step in a registration.
At the end, I want to submit all the data submitted in each fragment using an activity to a mysql database. Can I get a small sample code for this?
This is what I have tried so far. I am able to implement a viewpager with multiple fragments. I have created an interface in the StepOne.java Fragment so as to communicate to an activity. But I am not able to retrieve data from these fragments. It throws a null-pointer exception on line 52.
Here is my code:
SliderActivity.java:
public class SliderActivity extends AppCompatActivity {
ViewPager viewPager;
EditText edName,edPassword, edConfPass;
TextView tvShowAll;
ViewPagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slider);
viewPager = findViewById(R.id.view_pager);
mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mPagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void selectIndex(int newIndex) {
viewPager.setCurrentItem(newIndex);
}
#Override
public void onBackPressed() {
int currentPosition = viewPager.getCurrentItem();
if (currentPosition != 0) {
viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
} else {
super.onBackPressed();
}
}
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new StepOne();
case 1:
return new StepTwo();
case 2:
return new StepThree();
}
return null;
}
#Override
public int getCount() {
return 3; //three fragments
}
}
}
StepOne.java:
public class StepOne extends Fragment {
Button buttonInFragment1;
EditText edName;
public interface ActivityFragmentCallback {
void onSetName(String name);
}
ActivityFragmentCallback listener;
public StepOne() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_step_one, container, false);
edName = rootView.findViewById(R.id.edName);
buttonInFragment1 = rootView.findViewById(R.id.button_one);
if(buttonInFragment1 != null) {
buttonInFragment1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),edName.getText().toString(),Toast.LENGTH_SHORT).show();
if(edName != null) {
listener.onSetName(edName.getText().toString());
}
switch (view.getId()){
case R.id.button_one:
((SliderActivity)getActivity()).selectIndex(1);
break;
}
}
});
}
return rootView;
}
#Override
public void onAttach(Context context){
super.onAttach(context);
try {
listener = (ActivityFragmentCallback)context;
}catch (ClassCastException c){
c.printStackTrace();
}
}
}
MessageActivity.java: Here is where I need all the data submitted from all the fragments
public class MessageActivity extends AppCompatActivity implements StepOne.ActivityFragmentCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
}
#Override
public void onSetName(String name){
// tvShowAll = findViewById(R.id.tvShowAll);
// tvShowAll.setText(name);
Toast.makeText(getApplicationContext(),name, Toast.LENGTH_LONG).show();
}
}
Below is some reference link for step by step registration;
Hope you have help
https://github.com/stepstone-tech/android-material-stepper
https://github.com/baoyachi/StepView?utm_source=android-arsenal.com&utm_medium=referral&utm_campaign=3774

push data from Fragment to Fragment

I am new to Android. Please excuse me if it's a silly question:
If i click on button of a Fragment - it has to trigger a test and show the result in other Fragment. So to make things simple, have written a code on button click as follows. It's not working. Please suggest.
My actual intent is to register a log.add BroadcastReceiver, so that anywhere any log error or debug is called, that message has to appear in the TestStatusFragment.
public class TriggerTestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_trigger, container, false);
Button stopScheduler = (Button) view.findViewById(R.id.testButton);
stopScheduler.setOnClickListener((View sview) -> {
View teststatusView = inflater.inflate(R.layout.fragment_teststatus, container, false);
TextView textView = (TextView) teststatusView.findViewById(R.id.text_view);
textView.setText("test result....");
});
return view;
}
}
MainActivity.java
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TriggerTestFragment(), "TRIGGERTEST");
adapter.addFragment(new TestStatusFragment(), "TEST STATUS");
viewPager.setAdapter(adapter);
}
Second Fragment:
public class TestStatusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getContext();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_teststatus, container, false);
return view;
}
}
Use interface to communicate between them.
Fragment One
public class FragOne extends Fragment {
EditText etxtName, etxtDesc;
Button btnSubmit;
String name, desc;
private OnFragmentInteractionListener mListener;
public FragOne() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_one, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
etxtName = (EditText) view.findViewById(R.id.etxtName);
etxtDesc = (EditText) view.findViewById(R.id.etxtDesc);
btnSubmit = (Button) view.findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = etxtName.getText().toString().trim();
desc = etxtDesc.getText().toString().trim();
if(name == null || desc == null) {
Toast.makeText(getActivity(), "Both fields required", Toast.LENGTH_SHORT).show();
} else {
mListener.onFragmentInteraction(name, desc);
etxtName.setText("");
etxtDesc.setText("");
}
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String name, String desc);
}
}
Fragment Two
public class FragTwo extends Fragment implements FragOne.OnFragmentInteractionListener{
TextView textView, textDesc;
public FragTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_two, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = (TextView) view.findViewById(R.id.txtName);
textDesc = (TextView) view.findViewById(R.id.txtDesc);
}
#Override
public void onFragmentInteraction(String name, String desc) {
textView.setText(name);
textDesc.setText(desc);
}
}
Init fragments
fragOne = new FragOne();
fragTwo = new FragTwo();
PagerAdapter
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
MainActivity need implement onFragmentInteraction interface
public class MainActivity extends AppCompatActivity implements FragOne.OnFragmentInteractionListener{
static FragOne fragOne;
static FragTwo fragTwo;
MyPagerAdapter myPagerAdapter;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragOne = new FragOne();
fragTwo = new FragTwo();
viewPager = (ViewPager) findViewById(R.id.viewPager);
myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(myPagerAdapter);
}
#Override
public void onFragmentInteraction(String name, String desc) {
myPagerAdapter.onFragmentInteraction(name, desc );
}
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
}
You can read full article here https://www.mytrendin.com/passing-data-between-fragments/

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.

How to update fragments dynamically in viewpager android

I am working on one application which contains dynamic pages,so that i have taken viewpager.I created one fragment dynamically it creates,in that fragment i am calling webservice after success response i am refreshing data ,but fragment is not updating.I am using StatePagerAdapter.
code:
public class CustomPagerAdapter extends FragmentStatePagerAdapter
{
private ArrayList<InstituteVO> _instituteList;
private ArrayList<CourseItemVO> _courses;
public CustomPagerAdapter(FragmentManager fm, ArrayList<InstituteVO> instituteList)
{
super(fm);
_instituteList = instituteList;
_courses=new ArrayList<>();
}
#Override
public Fragment getItem(int position)
{
PagerItemFragment fragment = new PagerItemFragment();
fragment.setItemInfo(_instituteList.get(position), this);
// fragment.setCourses(_courses);
return fragment;
}
#Override
public int getCount()
{
return _instituteList.size();
}
public int getItemPosition(Object item) {
return super.getItemPosition(item);
}
public class PagerItemFragment extends BaseFragment implements OnWebServiceResponseListener,View.OnClickListener
{
private RecyclerView _courseView;
private CourseCustomRecycleAdapter _adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.institute_pager_layout, null);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
setData();
}
private void setData()
{
callDataService(_item);
}
private void callDataService(String slug)
{
WebServiceController.getInstance().serviceGET(this, new InstituteProcessor(), url, AppConstants.METHOD_GET, slug);
}
#Override
public void onWebServiceResponseSuccess(OnWebServiceDataProcessListener response)
{
if (response != null && response instanceof InstituteProcessor)
{
_adapter.setData(((InstituteProcessor)response).getInstituteVO().getCourses());
}
}
}

Butterknife view in Fragment is null reference if call from parent activity

i have problem with using Butterknife libray. There is I have SearchActivity.class use ViewPager with 3 Fragment in FragmentSearchAdapter:
SearchActivity.class
mAdapter = new FragmentSearchAdapter(getSupportFragmentManager(), SearchActivity.this);
mAdapter.addFragment("search histori");
mAdapter.addFragment("search query");
mAdapter.addFragment("search result");
mPager.setAdapter(mAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int currentIndex) {
if(currentIndex==2) {
SearchResultFragment SearchResultFragment = (SearchResultFragment) mAdapter.getItem(2);
if (SearchResultFragment != null) {
SearchResultFragment.setDescription("Text 1","Text 2");
}
}
}
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
});
FragmentSearchAdapter.class
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
SearchHistoryFragment search_histori = new SearchHistoryFragment();
return search_histori;
case 1:
SearchQueryFragment search_query = new SearchQueryFragment();
return search_query;
case 2:
SearchResultFragment search_result = new SearchResultFragment();
return search_result;
}
return null;
}
Where one fragment is SearchResultFragment.Class
public class SearchResultFragment extends Fragment {
#Bind(R.id.text1)
TextView text1;
#Bind(R.id.text2)
TextView text2;
private String page_index;
private PageAlquranActivity activity;
public SearchResultFragment() {
}
public static SearchResultFragment newInstance(int page_index) {
SearchResultFragment fragment = new SearchResultFragment();
Bundle args = new Bundle();
args.putString(Variabel.page_index, String.valueOf(page_index));
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
page_index = getArguments().getString(Variabel.page_index);
}
activity = (PageAlquranActivity) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_search_result, container, false);
ButterKnife.bind(this, v);
return v;
}
public void setDescription(String s1, String s2) {
text1.setText(s1);
text2.setText(s2);
}
#Override
public void onAttach(Context context) {super.onAttach(context);}
#Override
public void onDetach() {
super.onDetach();
}
}
My Problem : when call method SearchResultFragment.setDescription("Text 1","Text 2"); from SearchActivity, I get error :
null object reference
each TextView. This error if use ButterKnife,but if not, it's work if I declare View like this :
text1 = rootView.findViewById(R.id.text1);
text2 = rootView.findViewById(R.id.text2);
in onCreateView.
so how to solve it ? Sorry for my English. Thanks.
#AmayDiam you need to bind ButterKnife again in the called method. Pass along the dependency for the bind - the fragment view from the OnPageChangeListener
SearchActivity.class
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int currentIndex)
{
if(currentIndex==2)
{
SearchResultFragment SearchResultFragment = (SearchResultFragment) mAdapter.getItem(2);
if (SearchResultFragment != null)
{
SearchResultFragment.setDescription(mPager.getChildAt(currentIndex)"Text 1","Text 2");
}
}
}
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
});
SearchResultFragment.Class
public void setDescription(View view,String s1, String s2)
{
ButterKnife.bind(this, view);
//
text1.setText(s1);
text2.setText(s2);
}
Had similar issue too, just because I've added butterknife from Android Studio's Dependency management and not by copy-pasting gradle lines from Butterknife website.
So I had to add
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
instead of just
compile 'com.jakewharton:butterknife:8.5.1'

Categories

Resources