I've seen quite a few posts about this "issue" with RecyclerView, but I can't manage to fix it.
Every time I scroll, my custom CheckBoxes (starStyle) keep turning on/off.
I've tried to follow other solutions here on Stack, but none seems to do the job for me.
Just to explain the structure of my app, I've a long list (each item has a StarStyle CheckBox): when I click on an item, the app takes me in the Details Page for that item, where I can set the CheckBox, too. I managed to bind the list's checkbox and the one in the detail page, but I still having this annoying problem.
Here my code for the ListFragment:
public class PetrolStationListFragment extends Fragment {
private RecyclerView mPetrolStationRecyclerView;
private PetrolStationAdapter mAdapter;
private int itemPosition;
private int mLastAdapterClickPosition = -1;
private List<Boolean> mCheckState = new ArrayList<>();
public static boolean toBeCreated;
private static final String ARG_POSITION = "position";
// Design pattern to instantiate a new fragment.
public static PetrolStationListFragment newInstance(int position) {
PetrolStationListFragment fragment = new PetrolStationListFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
/********************************************************/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_petrol_station_list, container, false);
mPetrolStationRecyclerView = (RecyclerView) view.findViewById(R.id.petrol_recycler_view);
mPetrolStationRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
PetrolStationDAO petrolStationDAO = PetrolStationDAO.get(getActivity());
List<PetrolStation> petrolStations = petrolStationDAO.getPetrolStations();
if (mAdapter == null || toBeCreated) {
mAdapter = new PetrolStationAdapter(petrolStations);
mPetrolStationRecyclerView.setAdapter(mAdapter);
toBeCreated = false;
} else {
if (mLastAdapterClickPosition < 0) {
mAdapter.setPetrolStations(petrolStations);
mAdapter.notifyDataSetChanged();
} else {
mAdapter.notifyItemChanged(mLastAdapterClickPosition);
mLastAdapterClickPosition = -1;
}
mAdapter.notifyItemChanged(itemPosition);
}
}
private class PetrolStationHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private PetrolStation mPetrolStation;
private TextView mNameTextView;
private TextView mAddressTextView;
private TextView mDistanceTextView;
private CheckBox mCheckBox;
private int mPosition;
public PetrolStationHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mNameTextView = (TextView) itemView.findViewById(R.id.list_item_station_name_text_view);
mAddressTextView = (TextView) itemView.findViewById(R.id.list_item_station_address_text_view);
mDistanceTextView = (TextView) itemView.findViewById(R.id.list_item_station_distance_text_view);
mCheckBox = (CheckBox) itemView.findViewById(R.id.checkbox);
}
public void bindPetrolStation(PetrolStation petrolStation, int position) {
mPetrolStation = petrolStation;
mNameTextView.setText(mPetrolStation.getName());
mAddressTextView.setText("Via Verdi, 19/A");
mDistanceTextView.setText("300 meters");
mPosition = position;
//mCheckBox.setChecked(mPetrolStation.isFavourite());
mCheckBox.setChecked(mCheckState.get(mPosition));
Log.d("BIND_POSITION", "position: " + mPosition + " / status: " + mCheckState.get(mPosition));
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
boolean boxChecked = mPetrolStation.isFavourite();
Log.d("BOX_CHECKED_POSITION", "boxChecked: " + boxChecked);
if (boxChecked) {
mPetrolStation.setFavourite(false);
} else {
mPetrolStation.setFavourite(true);
}
if (boxChecked) {
mCheckState.set(mPosition, false);
} else {
mCheckState.set(mPosition, true);
}
Log.d("CHECK_POSITION", "mCheckState: " + mCheckState);
// TODO: DB connection.
// PetrolStationDAO.get(getActivity()).updateItem(mCrime);
}
});
}
#Override
public void onClick(View v) {
itemPosition = mPetrolStationRecyclerView.getChildAdapterPosition(v);
Intent intent = PetrolStationPagerActivity.newIntent(getActivity(), mPetrolStation.getId());
startActivity(intent);
}
}
private class PetrolStationAdapter extends RecyclerView.Adapter<PetrolStationHolder> {
private List<PetrolStation> mPetrolStations;
public PetrolStationAdapter(List<PetrolStation> petrolStations) {
mPetrolStations = petrolStations;
for (int i = 0; i < mPetrolStations.size(); i++) {
mCheckState.add(false);
}
}
#Override
public PetrolStationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_petrol_station, parent, false);
return new PetrolStationHolder(view);
}
#Override
public void onBindViewHolder(PetrolStationHolder holder, int position) {
PetrolStation petrolStation = mPetrolStations.get(position);
holder.bindPetrolStation(petrolStation, position);
// holder.setIsRecyclable(false);
}
#Override
public int getItemCount() {
return mPetrolStations.size();
}
public void setPetrolStations(List<PetrolStation> petrolStations) {
mPetrolStations = petrolStations;
}
}
}
Here the one for the DetailsFragment:
public class PetrolStationFragment extends Fragment {
private static final String ARG_PETROL_STATION_ID = "petrol_station_id";
private PetrolStation mPetrolStation;
private TextView mInfo;
private CheckBox mCheckBox;
private static TabLayout mTabLayout;
private static ViewPager mViewPager;
private static int intItems = 2;
// Navigation Tab constants.
private static final int SELF_SERVICE_POSITION = 0;
private static final int FULL_SERVICE_POSITION = 1;
// Design pattern to instantiate a new fragment.
public static PetrolStationFragment newInstance(long petrolStationId) {
Bundle args = new Bundle();
args.putLong(ARG_PETROL_STATION_ID, petrolStationId);
PetrolStationFragment fragment = new PetrolStationFragment();
fragment.setArguments(args);
return fragment;
}
/********************************************************/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long mId = getArguments().getLong(ARG_PETROL_STATION_ID);
mPetrolStation = PetrolStationDAO.get(getActivity()).getPetrolStation(mId);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStace) {
View view = inflater.inflate(R.layout.fragment_petrol_station, container, false);
mInfo = (TextView) view.findViewById(R.id.petrol_station);
mCheckBox = (CheckBox) view.findViewById(R.id.checkbox);
mInfo.setText(mPetrolStation.getName());
mCheckBox.setChecked(mPetrolStation.isFavourite());
// TODO: to fix.
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isFavourite) {
mPetrolStation.setFavourite(isFavourite);
}
});
// Setup Views.
mTabLayout = (TabLayout) view.findViewById(R.id.pager_header);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
// Set an Adapter for the View Pager.
TabPagerAdapter tabPagerAdapter = new TabPagerAdapter(getChildFragmentManager());
mViewPager.setAdapter(tabPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(SELF_SERVICE_POSITION);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
int flag;
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mInfo.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
mPetrolStation.setName(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
// Return fragment with respect to position.
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case SELF_SERVICE_POSITION: {
fragment = SelfServiceFragment.newInstance();
return fragment;
}
case FULL_SERVICE_POSITION: {
fragment = FullServiceFragment.newInstance();
return fragment;
}
}
return null;
}
#Override
public int getCount() {
return intItems;
}
// This method returns the title of the tab according to its position.
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case SELF_SERVICE_POSITION: {
String mSelfService = getResources().getString(R.string.self_service);
return mSelfService;
}
case FULL_SERVICE_POSITION: {
String mFullService = getResources().getString(R.string.full_service);
return mFullService;
}
}
return null;
}
}
}
Any hints about how to solve this issue?
Am I missing some kind of check?
Use a List of boolean type to hold the state of the checkbox. By default fill your collection with a false value.
When you select a checkbox change the state of the map using the set method
As you know When you scroll there will be a call to your adapter there you read the value from the map using get and set it to checkbox
List < Boolean > checkstate = new ArrayList < Boolean > ();
// Inside the adapter constructor
for (i = 0; i < itemSize; i++) {
checkstate.add(false);
}
Inside your Viewholder add below Line what it does is whatever the updated value of checkbox will set to your checkbox. Initially all the Items will be false
yourCheckbox.setChecked(checkstate.get(position));
Now inside onCheckedChanged Listener
if (boxchecked) {
checkstate.set(position, true);
} else {
checkstate.set(position, false);
}
Related
I'm using ViewPager2 and RecyclerView develop to Search activity.
What I want is use text entered in EditText as request parameter and response data is reflected in the RecyclerView.
I checked that the data was responded normally, but it was not reflected in the view.
I read so many questions and posts, but I couldn't solve the problem that the view was not refreshed.
Upon checking, data was added to the list of RecyclerView, the methods of the RecyclerView Adapter were not executed at all.
SearchActivity
public class SearchActivity extends AppCompatActivity {
private ActivitySearchBinding binding;
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2};
private final String key;
private BusStopInterface busStopInterface;
private PlaceholderFragment fragment;
private SectionsPagerAdapter sectionsPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySearchBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
sectionsPagerAdapter = new SectionsPagerAdapter(SearchActivity.this);
ViewPager2 pager = binding.viewPager;
pager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = binding.tabs;
EditText searchBox = binding.searchBox;
fragment = new PlaceholderFragment();
new TabLayoutMediator(tabs, pager, (tab, position) -> tab.setText(TAB_TITLES[position])).attach();
RetrofitClient retrofitClient = RetrofitClient.getInstance();
busStopInterface = RetrofitClient.getRetrofitInterface();
searchBox.addTextChangedListener(textWatcher);
pager.registerOnPageChangeCallback(pageChangeCallback);
}
ViewPager2.OnPageChangeCallback pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
if (position == 0) {
Log.d("position", "Bus stop");;
} else if (position == 1) {
Log.d("position", "Bus");;
}
}
};
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
busStopInterface.getBusStop(key, 25, "json", 25, s.toString()).enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
if (response.isSuccessful()) {
Example example = response.body();
Items items = example.getResult().getBody().getItems(); //I checked the data response.
fragment.resetRecyclerView(items.getItem());
sectionsPagerAdapter.notifyDataSetChanged();
Log.d("retrofit", "Data fetch success");
} else {
Log.d("retrofit", "Data fetch fail");
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Log.d("retrofit", t.getMessage());
}
});
}
};
}
PlaceholderFragment
public class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private PageViewModel pageViewModel;
private FragmentSearchBinding binding;
public List<BusStopItem> items = new ArrayList<>();
public SearchRecyclerViewAdapter adapter = new SearchRecyclerViewAdapter(items);
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, index);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = new ViewModelProvider(this).get(PageViewModel.class);
int index = 1;
if (getArguments() != null) {
index = getArguments().getInt(ARG_SECTION_NUMBER);
}
pageViewModel.setIndex(index);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentSearchBinding.inflate(inflater, container, false);
View root = binding.getRoot();
pageViewModel.getIndex().observe(getViewLifecycleOwner(), new Observer<Integer>() {
#Override
public void onChanged(Integer index) {
if (index == 1) {
adapter.setItemViewType(SearchRecyclerViewAdapter.VIEWTYPE_BUS_STOP);
} else if (index == 2) {
adapter.setItemViewType(SearchRecyclerViewAdapter.VIEWTYPE_BUS);
}
}
});
return root;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = binding.searchRecyclerView;
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), 1));
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
public void resetRecyclerView(List<BusStopItem> newItems) {
items.clear();
items.addAll(newItems);
adapter.notifyDataSetChanged();
}
}
SearchRecyclerViewAdapter
public class SearchRecyclerViewAdapter extends RecyclerView.Adapter<SearchRecyclerViewAdapter.ViewHolder> {
public static final int VIEWTYPE_BUS_STOP = 0;
public static final int VIEWTYPE_BUS = 1;
int mItemViewType;
List<BusStopItem> busStopItems;
public class ViewHolder extends RecyclerView.ViewHolder {
TextView busStopName, busStopId, busStopLocation, busName, busArea, busRoute;
public ViewHolder(#NonNull View itemView) {
super(itemView);
busStopName = itemView.findViewById(R.id.busStopName);
busStopId = itemView.findViewById(R.id.busStopId);
busStopLocation = itemView.findViewById(R.id.busStopLocation);
busName = itemView.findViewById(R.id.busName);
busArea = itemView.findViewById(R.id.busArea);
busRoute = itemView.findViewById(R.id.busRoute);
}
public void setBusStopItem(BusStopItem item) {
busStopName.setText(item.getNodenm());
if(item.getNodeno() != null) {
busStopId.setText(item.getNodeno().toString());
}
}
}
public SearchRecyclerViewAdapter(List<BusStopItem> busStopItems) {
this.busStopItems = busStopItems;
}
public void setItemViewType(int viewType) {
mItemViewType = viewType;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = null;
if (viewType == VIEWTYPE_BUS_STOP) {
view = inflater.inflate(R.layout.search_bus_stop_item, parent, false);
} else if (viewType == VIEWTYPE_BUS) {
view = inflater.inflate(R.layout.search_bus_item, parent, false);
}
SearchRecyclerViewAdapter.ViewHolder vh = new SearchRecyclerViewAdapter.ViewHolder(view);
return vh;
}
#Override
public int getItemViewType(int position) {
return mItemViewType;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if (mItemViewType == VIEWTYPE_BUS_STOP) {
holder.setBusStopItem(busStopItems.get(position));
} else if (mItemViewType == VIEWTYPE_BUS) {
}
}
#Override
public int getItemCount() {
return busStopItems.size();
}
}
SectionsPagerAdapter
public class SectionsPagerAdapter extends FragmentStateAdapter {
public SectionsPagerAdapter(FragmentActivity fa) {
super(fa);
}
#NonNull
#Override
public Fragment createFragment(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getItemCount() {
return 2;
}
}
What I tried
public void resetRecyclerView(List<BusStopItem> newItems) {
items.clear();
items.addAll(newItems);
adapter.notifyDataSetChanged();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
}
java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.fragment.app.FragmentTransaction androidx.fragment.app.FragmentManager.beginTransaction()' on a null object reference
You create PlaceholderFragment but not add it to FragmmentManger.
fragment = new PlaceholderFragment();
When `busStopInterface.getBusStop()` get return, you set data to
private PlaceholderFragment fragment
and fragment is not attach to any Activity,so UI dosen't refresh. You should get PlaceholderFragment instance from SectionsPagerAdapter or create PlaceholderFragment instance for SectionsPagerAdapter, and you can set data to real PlaceholderFragment
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySearchBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
fragments = new ArrayList<>();
fragments.add(PlaceholderFragment.newInstance(1));
fragments.add(PlaceholderFragment.newInstance(2));
sectionsPagerAdapter = new SectionsPagerAdapter(SearchActivity.this, fragments);
ViewPager2 pager = binding.viewPager;
pager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = binding.tabs;
EditText searchBox = binding.searchBox;
new TabLayoutMediator(tabs, pager, (tab, position) -> tab.setText(TAB_TITLES[position])).attach();
RetrofitClient retrofitClient = RetrofitClient.getInstance();
busStopInterface = RetrofitClient.getRetrofitInterface();
searchBox.addTextChangedListener(textWatcher);
pager.registerOnPageChangeCallback(pageChangeCallback);
}
public class SectionsPagerAdapter extends FragmentStateAdapter {
private final List<PlaceholderFragment> fragments;
public SectionsPagerAdapter(FragmentActivity fa, List<PlaceholderFragment> fragments) {
super(fa);
this.fragments = fragments;
}
#NonNull
#Override
public Fragment createFragment(int position) {
return fragments.get(position);
}
#Override
public int getItemCount() {
return 2;
}
}
busStopInterface.getBusStop(key, 25, "json", 25, s.toString()).enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
if (response.isSuccessful()) {
Example example = response.body();
Items items = example.getResult().getBody().getItems(); //I checked the data response.
fragments.get(1).resetRecyclerView(items.getItem());
Log.d("retrofit", "Data fetch success");
} else {
Log.d("retrofit", "Data fetch fail");
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Log.d("retrofit", t.getMessage());
}
});
PS. remove
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
I've a viewpager looping a multiple fragments and set in a viewpager. Each fragment has a listview with checkbox. On clicking any one item of a list it will notify all the fragments so that all checkbox remains unchecked and only clicked item will be checked.
CreateGroupStep1
public class CreateGroupStep1 extends BaseActivity implements IGroup {
private TabLayout tabLayout;
private ViewPager viewPager;
private ImageView next_btn,back;
private int current_item_position;
private ViewPagerAdapter adapter;
private ArrayList<Interest> interestList;
ArrayList<String>al_sports;
ArrayList<String>al_list_collect;
private ArrayList<String>al_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group_step1);
storeDataOfArrayList();
al_list_collect=new ArrayList<String>();
initViews();
}
public void initViews() {
viewPager = (ViewPager) findViewById(R.id.viewpager);
RelativeLayout back=(RelativeLayout) findViewById(R.id.back);
back=(RelativeLayout) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
next_btn=(ImageView) findViewById(R.id.next_btn);
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent ii=new Intent(CreateGroupStep1.this,CreateGroupStep2.class);
//startActivity(ii);
Toast.makeText(CreateGroupStep1.this, "", Toast.LENGTH_SHORT).show();
}
});
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(CreateGroupStep1.this.getSupportFragmentManager());
for (int i=0;i<al_title.size();i++)
{
adapter.addFragment(InterestFragmentForGroup.getInstance(al_sports),al_title.get(i));
viewPager.setAdapter(adapter);
}
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(10);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
current_item_position = position;
// Toast.makeText(CreateGroupStep1.this, "scrolled", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClickedNextButton(final String message) {
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CreateGroupStep1.this,message, Toast.LENGTH_SHORT).show();
}
});
}
public 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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void storeDataOfArrayList()
{
saveData();
al_sports=new ArrayList<>();
al_sports.add("Baseball");
al_sports.add("Basketball");
al_sports.add("Bowling");
al_sports.add("Cricket");
al_sports.add("Football");
al_sports.add("Golf");
al_sports.add("Handball");
al_sports.add("Hockey");
al_sports.add("Jogging");
al_sports.add("Racquetball");
al_sports.add("Running");
al_sports.add("Skiing");
al_sports.add("Snowboarding");
al_sports.add("Soccer");
al_sports.add("Swimming");
al_sports.add("Tennis");
}
private void saveData()
{
al_title=new ArrayList<String>();
al_title.add("Sports");
al_title.add("LifeStyle");
al_title.add("Adventure");
al_title.add("Recreation");
al_title.add("The Arts");
al_title.add("College");
al_title.add("Sos");
al_title.add("Industry");
al_title.add("LocalBiz");
al_title.add("Corporate");
}
}
InterestAdapterForGroup
public class InterestAdapterForGroup extends RecyclerView.Adapter<InterestAdapterForGroup.MyViewHolder> implements IGroup {
public int selectedPosition = -1;
IGroup inter;
private LayoutInflater inflater;
private ArrayList<Interest> stList;
private Context mContext;
private ArrayList<Interest> checked_item = new ArrayList<>();
public InterestAdapterForGroup(Context context, ArrayList<Interest> al_list) {
this.mContext = context;
this.stList = al_list;
inflater = LayoutInflater.from(context);
inter = (IGroup) mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_ethnic, parent, false);
InterestAdapterForGroup.MyViewHolder holder = new InterestAdapterForGroup.MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final int pos = position;
final Interest interest = stList.get(position);
holder.title.setText(interest.getName());
if (position == selectedPosition) {
holder.chkSelected.setChecked(true);
} else {
holder.chkSelected.setChecked(false);
}
holder.chkSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
interest.isSelected = isChecked;
if (isChecked) {
checked_item.clear();
checked_item.add(interest);
selectedPosition = position;
} else {
checked_item.remove(interest);
selectedPosition = -1;
}
notifyDataSetChanged();
}
}
});
clickedItems();
}
public void clickedItems() {
if (checked_item.size() > 0) {
if (Constants.GLOBAL_ARRAY.size() > 0) {
Constants.GLOBAL_ARRAY.clear();
for (int i = 0; i < checked_item.size(); i++) {
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
}
}
ArrayList<String> al_name = new ArrayList<String>();
ArrayList<String> al_nam = new ArrayList<String>();
for (int i = 0; i < checked_item.size(); i++) {
al_name.add(checked_item.get(i).getEmailId());
}
for (int i = 0; i < checked_item.size(); i++) {
al_nam.add(checked_item.get(i).getName());
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
inter.onClickedNextButton(al_nam.toString());
}
public ArrayList<Interest> getCheckedItemList() {
return stList;
}
#Override
public int getItemCount() {
return stList.size();
}
#Override
public void onClickedNextButton(String message) {
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CheckBox chkSelected;
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txt_ethnic);
chkSelected = (CheckBox) itemView
.findViewById(R.id.chk);
}
#Override
public void onClick(View v) {
}
}
}
InterestFragmentForGroup
public class InterestFragmentForGroup extends BasePagerFragment implements IPager {
private ArrayList<String> interestList;
private ArrayList<Interest> interestListfunction;
public static Fragment getInstance(ArrayList<String> interestList){
Bundle bundle = new Bundle();
bundle.putSerializable("interestList",interestList);
InterestFragmentForGroup interestsFragment = new InterestFragmentForGroup();
interestsFragment.setArguments(bundle);
return interestsFragment;
}
public void getInterestList(){
interestList = (ArrayList<String>) getArguments().getSerializable("interestList");
}
private RecyclerView recyclerView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sports_fragment, container, false);
initViews(rootView);
return rootView;
}
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.drawerList);
getInterestList();
setData();
}
public void setData() {
interestListfunction = new ArrayList<>();
for (int i = 0; i < interestList.size(); i++) {
Interest st = new Interest(interestList.get(i), interestList.get(i), false);
interestListfunction.add(st);
}
adapter2 = new InterestAdapterForGroup(getActivity(), interestListfunction);
recyclerView.addItemDecoration(new DividerDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(adapter2);
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
}
}
I am implementing tablayout using view pager and in my scenario I have two tab. In my first tab I have add data which store in share preference. and when I move to second tab then data should be retrieve from share preference and show in listview. When I add the data from my first tab then data is added successfully but not show in my second tab means I have to close my application and again restart the app so that I can see saved the detail which saved from my first tab.
Below is my Activity code.
public class FragmentExample extends AppCompatActivity {
private ViewPagerAdapter viewPagerAdapter;
#BindView(R.id.tabCountryState)
TabLayout tabCountryState;
#BindView(R.id.viewPager)
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_example);
ButterKnife.bind(this);
setViewPager();
setTabIcon();
viewPager.setOffscreenPageLimit(2);
tabCountryState.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.e("Current tab is ", "===> " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setViewPager() {
// set Adaapter.
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), FragmentExample.this);
viewPager.setAdapter(viewPagerAdapter);
tabCountryState.setupWithViewPager(viewPager);
}
// set custom icon to tab in Tablayout.
private void setTabIcon() {
// First Tab
View firstTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_first, null);
TextView tvFirsIcon = ButterKnife.findById(firstTab, R.id.tvFirsIcon);
tvFirsIcon.setText("First Tab");
tabCountryState.getTabAt(0).setCustomView(firstTab);
// First Tab
View secondTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_second, null);
TextView tvSecondIcon = ButterKnife.findById(secondTab, R.id.tvSecondIcon);
tvSecondIcon.setText("Second Tab");
tabCountryState.getTabAt(1).setCustomView(secondTab);
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Context context;
private FirstFragment firstFragment;
private SecondFragment secondFragment;
public ViewPagerAdapter(FragmentManager fm, Context mainActivity) {
super(fm);
context = mainActivity;
new FirstFragment();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
firstFragment = new FirstFragment();
return firstFragment;
case 1:
secondFragment = new SecondFragment();
return secondFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return " " + position;
}
}
}
Here is my FirstFragment in which I have added the data into share preference.
public class FirstFragment extends Fragment {
private View v;
#BindView(R.id.btnSubmit)
Button btnSubmit;
#BindView(R.id.edtCityName)
EditText edtCityName;
#BindView(R.id.spStateName)
Spinner spStateName;
private Unbinder unbinder;
private ArrayList<String> alStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private SpinnerStateAdapter spinnerAdapter;
private int spinnerPosition;
private String strCityName, strSpinnerValue;
#OnClick(R.id.btnSubmit)
public void submit(View view) {
if (spinnerPosition !=0) {
strCityName = edtCityName.getText().toString().trim();
alAllStateCity = SessinoManager.getCityList(getActivity());
if (strCityName.length() > 0) {
alAllStateCity.get(spinnerPosition).getAlCityName().add(new CityStateModel(strCityName));
} else {
}
// Save new data to Session.
SessinoManager.saveCityList(getActivity(), alAllStateCity);
SecondFragment.cityAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "Detail saved successfully ", Toast.LENGTH_SHORT).show();
edtCityName.setText("");
} else {
Toast.makeText(getActivity(), "Please select state", Toast.LENGTH_SHORT).show();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_first, container, false);
unbinder = ButterKnife.bind(this, v);
// arraylist checking if data is available into session.
if(SessinoManager.getCityList(getActivity()).size()>0){
Log.e("First fragment "," if condition ");
alAllStateCity = SessinoManager.getCityList(getActivity());
alStateName = new ArrayList<>();
for(int i=0;i<alAllStateCity.size();i++){
alStateName.add(alAllStateCity.get(i).getStrStateName());
}
setStateSpinner();
}else{
loadArraylist();
setStateSpinner();
}
return v;
}
private void setStateSpinner() {
spStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
strSpinnerValue = alStateName.get(i).toString().trim();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinnerAdapter = new SpinnerStateAdapter(getActivity(), alStateName);
spStateName.setAdapter(spinnerAdapter);
}
private void loadArraylist() {
alAllStateCity = new ArrayList<>();
alStateName = new ArrayList<>();
alStateName.add(0, "Select State");
alStateName.add("Gujarat");
alStateName.add("Maharashtra");
alStateName.add("Madhya Pradesh");
for (int i = 0; i < alStateName.size(); i++) {
alAllStateCity.add(new AllStateCityModel(alStateName.get(i), alAllStateCity.size(), new ArrayList<CityStateModel>()));
}
SessinoManager.saveCityList(getActivity(), alAllStateCity);
}
#Override public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
Log.e("First fragment "," on destroy");
}
}
Here is my SecondFragment in which I have to get saved detail from Share preference.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}
And I am saving data into Share preference which is given below.
public class SessinoManager {
private static final String CITY_PREFERENCE = "city_preference";
// Save data to share preference.
public static void saveCityList(Context context, ArrayList<AllStateCityModel> alAllPlayList) {
try {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonUsers = gson.toJson(alAllPlayList);
editor.putString("all_play_list", jsonUsers);
editor.commit();
// Check to save data into share preferent
for(int j=0;j<alAllPlayList.size();j++){
Log.e("State name ","----------------------"+alAllPlayList.get(j).getStrStateName());
ArrayList<CityStateModel> cityName = alAllPlayList.get(j).getAlCityName();
for(int i=0;i<cityName.size();i++){
Log.e("cityName "," in session ==> "+cityName.get(i).getStrCity());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static ArrayList<AllStateCityModel> getCityList(Context context)
{
SharedPreferences settings;
List<AllStateCityModel> users = new ArrayList<>();
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
if (settings.contains("all_play_list"))
{
String jsonUsers = settings.getString("all_play_list", null);
Gson gson = new Gson();
AllStateCityModel[] userItems = gson.fromJson(jsonUsers,AllStateCityModel[].class);
users = Arrays.asList(userItems);
users= new ArrayList<AllStateCityModel>(users);
}
return (ArrayList<AllStateCityModel>) users;
}
}
When I add new city detail into first tab then data is data successfully but when I swipe or move to next then data is not displaying and I have to restart whole application to get updated data from Share preference. Kindly help me to resolve this issue. Thanks in advance.
I have resolved the problem by implementing below method setUserVisibleHint.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
// Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.e("setUserVisibleHint","setUserVisibleHint "+isVisibleToUser);
if(isVisibleToUser==true){
loadArrayList(context);
}
}
#Override
public boolean getUserVisibleHint() {
Log.e("getUserVisibleHint","getUserVisibleHint "+super.getUserVisibleHint());
return super.getUserVisibleHint();
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}
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.
I have a fragment(say X) which contain ViewPager and TabLayout and i am passing a fragment((say Y)with a list) three times to adapter of this viewpager but every time list is sorted by some parameter.
Y fragment contain RecyclerView. And i am passing that list to the adapter of this RecyclerView.
I am able to populate all the 3 tabs with fragment.But list inside recyclerview is not sorted.Only last tab with recyclerview was comming sorted
Please help me to find shortcoming of the code.
X Fragment
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.available_bus_fragment, null);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
List<Bus> departureTimeList = mBusList;
Collections.sort(departureTimeList, new Comparator<Bus>() {
#Override
public int compare(Bus lhs, Bus rhs) {
return lhs.getDepartureTime().compareTo(rhs.getDepartureTime());
}
});
Fragment departureFragment = new AvailableRecyclerViewFragment(departureTimeList);
if (getArguments()!= null) {
departureFragment.setArguments(getArguments());
}
adapter.addFragment(departureFragment, "Departure");
List<Bus> durationTimeList = mBusList;
Collections.sort(durationTimeList, new Comparator<Bus>() {
#Override
public int compare(Bus lhs, Bus rhs) {
return lhs.getDurationForSorting() - rhs.getDurationForSorting();
}
});
Fragment durationFragment = new AvailableRecyclerViewFragment(durationTimeList);
if (getArguments() != null) {
durationFragment.setArguments(getArguments());
}
adapter.addFragment(durationFragment, "Duration");
List<Bus> priceList = mBusList;
Collections.sort(priceList, new Comparator<Bus>() {
#Override
public int compare(Bus lhs, Bus rhs) {
return lhs.getFares() - rhs.getFares();
}
});
Fragment priceFragment = new AvailableRecyclerViewFragment(priceList);
if (getArguments()!= null) {
priceFragment.setArguments(getArguments());
}
adapter.addFragment(priceFragment, "Fare");
viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
This is my adapter of viewpager.
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragments = new ArrayList();
private final List<String> mFragmentTitles = new ArrayList();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
Y fragment (AvailableRecyclerViewFragment.java)
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.available_list_fragment, null);
recycler_view = (RecyclerView) rootView.findViewById(R.id.recycler_view);
adapter = new CustomRecyclerViewAdapter(getActivity(), mBusList);
adapter.notifyDataSetChanged();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recycler_view.setLayoutManager(mLayoutManager);
recycler_view.setItemAnimator(new DefaultItemAnimator());
recycler_view.setHasFixedSize(true);
recycler_view.setAdapter(adapter);
return rootView;
}
Adapter for Recyclerview
public class CustomRecyclerViewAdapter extends RecyclerView.Adapter<CustomRecyclerViewAdapter.CustomViewHolder> {
private List<Bus> dataList;
Context mContext;
public CustomRecyclerViewAdapter(Context context, List<Bus> list) {
dataList = list;
mContext = context;
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView tv_departureTime;
public TextView tv_arrivalTime;
public TextView tv_duration;
public TextView tv_price;
public TextView tv_availableSeats;
public TextView tv_travels;
public TextView tv_busType;
public CustomViewHolder(View view) {
super(view);
tv_departureTime = (TextView) view.findViewById(R.id.tv_departureTime);
tv_arrivalTime = (TextView) view.findViewById(R.id.tv_arrivalTime);
tv_duration = (TextView) view.findViewById(R.id.tv_duration);
tv_price = (TextView) view.findViewById(R.id.tv_price);
tv_availableSeats = (TextView) view.findViewById(R.id.tv_availableSeats);
tv_travels = (TextView) view.findViewById(R.id.tv_travels);
tv_busType = (TextView) view.findViewById(R.id.tv_busType);
}
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_list_row, parent, false);
final Animation anim = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_in_left);
itemView.setAnimation(anim);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
Bus bus = dataList.get(position);
holder.tv_arrivalTime.setText("" + bus.getArrivalTime());
String[] data = bus.getDuration().split(":");
holder.tv_departureTime.setText("" + bus.getDepartureTime());
holder.tv_duration.setText("" + data[0] + "hr " + data[1] + "min");
if (bus.getFareList() != null) {
String fare = "";
for (FareDetails tempFare : bus.getFareList()) {
fare = fare + tempFare.getTotalFare() + ("/");
}
holder.tv_price.setText("" + fare.substring(0, fare.length() - 1).toString());
} else {
holder.tv_price.setText("" + bus.getFares());
}
holder.tv_availableSeats.setText("" + bus.getAvailableSeats() + " seats");
holder.tv_travels.setText(bus.getTravels());
holder.tv_busType.setText(bus.getBusType());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
inside of Fragment X(where your ViewPager is) call method setOnPageChangeListener:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
As you see inside of onPageSelected() call notifyDataSetChanged for your viewpager adapter. Then it should sort fragment that you're on.