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();
Related
As i'm using FragNav library i have some items into List and when i switching on other fragment and after pressing on BackButton i have some other items into this List,
for example generally i have 1 item into List with RecyclerView after switching on other fragment and pressing back button on phone i have 2 items into RecyclerView and using onSaveInstanceState,
onActivityCreated couldn't resolve my problem
my Fragment:
public class HomeFragment extends BaseFragment implements IAnimationListener, View.OnClickListener, InstagramFeedsAdapter.OnClickListener {
...
// constructor
public static HomeFragment createInstance(int instance) {
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putInt(BaseFragment.ARGS_INSTANCE, instance);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.instagram_post_container, container, false);
activity = getActivity();
context = getActivity().getBaseContext();
mediaUrls = new ArrayList<>();
feedsSchema = new FeedsSchema();
feedsSchema.setId(1);
mediaUrls.add("http://gizasystems.com/wp-content/uploads/2014/08/natural-world-hero3.jpg");
feedsSchema.setFeed_media_url(mediaUrls);
feedsSchema.setFollowers_count(10);
feedsSchema.setFollowings_count(20);
feedsSchema.setPage_name("my test");
feedsSchema.setType(FeedsSchema.feed_types.IMAGE);
items.add(feedsSchema);
instagram_feeds = mView.findViewById(R.id.instagram_feeds);
layoutManager = new LinearLayoutManager(context);
instagram_feeds.setLayoutManager(layoutManager);
instagram_feeds.setNestedScrollingEnabled(false);
instagramFeedsAdapter = new InstagramFeedsAdapter(activity, context, this, items);
return mView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle arguments = getArguments();
}
#Override
public void onAnimationEnd() {
}
#Override
public void onClick(View view) {
int clickedItem = view.getId();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onItemClick(View view, String transitionName, int position) {
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("someVarA", new ArrayList<>(items));
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
items = savedInstanceState.getParcelableArrayList("someVarA");
}
}
and my Adapter:
public class InstagramFeedsAdapter extends RecyclerView.Adapter<InstagramFeedsAdapter.InstagramFeedsViewHolder>
implements PreviewView.OnPreviewChangeListener {
private OnClickListener listener;
private List<FeedsSchema> feedsItems;
private Context context;
private boolean hoveredOnPopup = false;
private ExoPlayerManager exoPlayerManager;
private Activity activity;
private enum feedType {
IMAGE,
IMAGESLIDER,
VIDEO
}
public InstagramFeedsAdapter(Activity activity, Context context, OnClickListener listener, List<FeedsSchema> items) {
this.listener = listener;
this.feedsItems = items;
this.context = context;
this.activity = activity;
}
#Override
public void onBindViewHolder(#NonNull final InstagramFeedsViewHolder holder, int position) {
int feedType = feedsItems.get(position).getType().ordinal();
implementingGeneralViewData(holder, position);
if (feedType == 0) {
if (feedsItems.get(position).getFeed_media_url().size() > 1) {
implementingImageSliderView(holder, position);
} else {
implementingImageView(holder, position);
}
} else {
implementingVideoPlayerView(holder, position);
}
}
private void implementingVideoPlayerView(InstagramFeedsViewHolder holder, int position) {
}
#SuppressLint("CheckResult")
private void implementingImageSliderView(final InstagramFeedsViewHolder holder, final int position) {
}
#SuppressLint("CheckResult")
private void implementingImageView(final InstagramFeedsViewHolder holder, final int position) {
}
#Override
public int getItemCount() {
return feedsItems.size();
}
public class InstagramFeedsViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, PopupInflaterListener, PopupStateListener, PopupOnHoverListener {
...
public InstagramFeedsViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
ButterKnife.bind(this, itemView);
}
#Override
public void onClick(View view) {
}
public void bind(int position) {
...
}
}
so here is my problem, i have only one activity from i launch my viewpager fragment, in my viewpager i have 4 fragments containing recyclerViews. Every Fragment contains item populated by data on the net, when i click into one i get a WebView Fragment, but when i click on the backbutton i lost my poisiton, cause it's recreating the whole activity.
I don't know how to not recreate the activity and get back my old position, or recreating it but not changing the item's positions and have my old position back. Here's my code. Where i should put what ?! Some help would be very very well come.
Thank You !!
My Activity Class :
public class LauncherActivity extends AppCompatActivity implements ListFragment.OnNewSelectedInterface{
public static final String VIEWPAGER_FRAGMENT = "view_pager";
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_launcher);
mImageView = (ImageView) findViewById(R.id.logoImageView);
mImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_indefinitely));
if(!isNetworkAvailable()){
alertUserAboutError();
} else {
relativeLayout.postDelayed(new Runnable() {
#Override
public void run() {
ViewPagerFragment savedFragment = (ViewPagerFragment)
getSupportFragmentManager().findFragmentByTag(VIEWPAGER_FRAGMENT);
if(savedFragment == null) {
ViewPagerFragment viewPagerFragment = new ViewPagerFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.activity_launcher, viewPagerFragment, VIEWPAGER_FRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
}, 2000);
}
}
#Override
public void onListNewSelected(int index, ArrayList<Articles> articles) {
WebViewFragment webViewFragment = new WebViewFragment();
Bundle bundle = new Bundle();
bundle.putInt(ViewPagerFragment.KEY_NEW_INDEX, index);
bundle.putParcelableArrayList(ListFragment.KEY_LIST, articles);
webViewFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getFragmentManager(), "error_dialog");
}
}
My ViewPagerClass :
public class ViewPagerFragment extends Fragment {
public static final String KEY_NEW_INDEX = "key_new_index";
private ViewPager mViewPager;
private TabLayout mTabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
final OldFactFragment oldFactFragment = new OldFactFragment();
final SportFragment sportFragment = new SportFragment();
final BuzzFragment buzzFragment = new BuzzFragment();
final NewsFragment newsFragment = new NewsFragment();
mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
mTabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
mViewPager.setOffscreenPageLimit(4);
mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
if(position == 0){
return oldFactFragment;
} else if (position == 1) {
return newsFragment;
} else if (position == 2){
return sportFragment;
} else return buzzFragment;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Pastly";
} else if (position == 1) {
return "politic";
} else if (position == 2){
return "sport";
} else return "buzz";
}
#Override
public int getCount() {
return 4;
}
});
mTabLayout.setupWithViewPager(mViewPager);
return view;
}
}
My ListFragment(Parent's class of the 4 Fragments in the ViewPager) :
public abstract class ListFragment extends Fragment {
public static final String KEY_LIST = "key_list";
public interface OnNewSelectedInterface {
void onListNewSelected(int index, ArrayList<Articles> articles);
}
protected static final String TAG = ListFragment.class.getSimpleName();
protected ArrayList<Articles> mArticlesList;
protected ItemAdapter mArticleAdapter;
protected RecyclerView mRecyclerView;
protected OnNewSelectedInterface mListener;
protected RecyclerView.LayoutManager mManager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mListener = (OnNewSelectedInterface) getActivity();
View view = inflater.inflate(R.layout.fragment_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
getInfos(getUrl());
return view;
}
protected abstract String[] getUrl();
private void getInfos(String[] url) {
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
for (int i = 0; i < getUrl().length; i++) {
Request request = new Request.Builder().url(url[i]).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
Log.v(TAG, jsonData);
getMultipleUrls(jsonData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getCurrentArticles(mArticlesList);
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
alertUserAboutError();
}
});
}
});
}
} else{
alertUserAboutError();
}
}
private void getMultipleUrls(String jsonData) throws JSONException {
if (mArticlesList == null) {
mArticlesList = getArticleForecast(jsonData);
} else {
mArticlesList.addAll(getArticleForecast(jsonData));
}
}
private void getCurrentArticles(ArrayList<Articles> articles) {
mArticleAdapter = new ItemAdapter(getActivity(), articles, mListener);
mRecyclerView.setAdapter(mArticleAdapter);
mManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mManager);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getActivity().getFragmentManager(), "error_dialog");
}
private ArrayList<Articles> getArticleForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
JSONArray articles = forecast.getJSONArray("articles");
ArrayList<Articles> listArticles = new ArrayList<>(articles.length());
for (int i = 0; i < articles.length(); i++) {
JSONObject jsonArticle = articles.getJSONObject(i);
Articles article = new Articles();
String urlImage = jsonArticle.getString("urlToImage");
article.setTitle(jsonArticle.getString("title"));
article.setDescription(jsonArticle.getString("description"));
article.setImageView(urlImage);
article.setArticleUrl(jsonArticle.getString("url"));
listArticles.add(i, article);
}
return listArticles;
}
}
And my ItemAdapter (Adapter Class) :
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ArticleViewHolder> {
private final ListFragment.OnNewSelectedInterface mListener;
protected ArrayList<Articles> mArticlesList;
protected Context mContext;
private int mPosition;
private int lastPosition = -1;
public ItemAdapter(Context contexts, ArrayList<Articles> mArticleLi, ListFragment.OnNewSelectedInterface listener){
mContext = contexts;
mArticlesList = mArticleLi;
mListener = listener;
}
#Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_linear, parent, false);
view.findViewById(R.id.textView).setSelected(true);
ArticleViewHolder articleViewHolder = new ArticleViewHolder(view);
articleViewHolder.setIsRecyclable(false);
return articleViewHolder;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(ArticleViewHolder holder, int position) {
mPosition = position;
holder.bindArticle(mArticlesList.get(position));
setAnimation(holder.itemView, position);
holder.mImageView.setClipToOutline(true);
}
private void setAnimation(View viewToAnimate, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(viewToAnimate.getContext(), android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return mArticlesList.size();
}
public class ArticleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
private TextView mTitle, mArticle;
private ImageView mImageView;
private ArticleViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.textView);
mArticle = (TextView) itemView.findViewById(R.id.showTextView);
mImageView = (ImageView) itemView.findViewById(R.id.imageView2);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
private void bindArticle(Articles article) {
mTitle.setText(article.getTitle());
mArticle.setText(article.getDescription());
mArticle.setVisibility(View.INVISIBLE);
Glide.with(mContext).load(article.getImageView()).into(mImageView);
}
#Override
public void onClick(View view) {
mListener.onListNewSelected(getLayoutPosition(), mArticlesList);
}
#Override
public boolean onLongClick(View view) {
String desc = mArticlesList.get(getAdapterPosition()).getDescription();
mArticle.setVisibility(View.VISIBLE);
mArticle.setText(desc);
mArticle.postDelayed(new Runnable() {
public void run() {
mArticle.setVisibility(View.INVISIBLE);
}
}, 3000);
return true;
}
}
}
In Your method onListNewSelected You are Replacing the new fragment with the old one as stated in this line
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
From Google Documentaion
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
So you are removing the old Fragment then adding the new one, When you are back to get the old fragment, It is not already there it will be created from scratch, So the position is already gone with the removed fragment.
While using the add method, Will add the new fragment above the previous one, when you go back the previous one already there with its state "Position"
I am having trouble implementing view.OnClickListener in my RecyclerView.Adapter. I am trying to implement multi-pane layout (landscape tablet layout version with RecyclerView and detail side by side). I have so far created this Activity:
public class MovieListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MovieListFragment movieListFragment = new MovieListFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recycler_view_fragment, movieListFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
which starts a Fragment:
public class MovieListFragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
public MovieListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MoviesAdapter(getContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_movie_list, container, false);
ButterKnife.bind(this,view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onStart() {
super.onStart();
getPopularMovies();
}
private void getPopularMovies() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
service.getPopularMovies(new Callback<Movie.MovieResult>() {
#Override
public void success(Movie.MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) { error.printStackTrace(); }
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
which calls the RecyclerView.Adapter:
public class MoviesAdapter extends RecyclerView.Adapter<MovieViewHolder> {
private List<Movie> mMovieList;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context) {
this.mContext = context;
this.mInflater = LayoutInflater.from(context); //
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
View view = mInflater.inflate(R.layout.movie_row_item, parent, false);
final MovieViewHolder viewHolder = new MovieViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = viewHolder.getAdapterPosition();
Intent intent = new Intent(mContext, MovieDetailActivity.class);
intent.putExtra(MovieDetailActivity.MOVIE_EXTRA, mMovieList.get(position));
mContext.startActivity(intent);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movie movie = mMovieList.get(position);
Picasso.with(mContext)
.load(movie.getPoster())
.placeholder(R.color.colorAccent)
.into(holder.thumbnail);
holder.movieTitle.setText(movie.getTitle());
holder.rating.setText(movie.getRating());
}
#Override
public int getItemCount() {
return (mMovieList == null) ? 0 : mMovieList.size();
}
public void setMovieList(List<Movie> movieList) {
this.mMovieList = new ArrayList<>();
this.mMovieList.addAll(movieList);
notifyDataSetChanged();
}
}
Here in onClick I need to decide whether to start a new Activity (like in my code) or update content of detail Fragment (in my tablet landscape layout).
According to this link, you should decide based on fact if your DetailFragment is != null in activity like this:
public void onItemSelected(int position) {
DisplayFragment displayFrag = (DisplayFragment) getFragmentManager()
.findFragmentById(R.id.display_frag);
if (displayFrag == null) {
// DisplayFragment (Fragment B) is not in the layout (handset layout),
// so start DisplayActivity (Activity B)
// and pass it the info about the selected item
Intent intent = new Intent(this, DisplayActivity.class);
intent.putExtra("position", position);
startActivity(intent);
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
displayFrag.updateContent(position);
}
}
But I'm not able to check this in Adapter. Any help would be highly appreciated!
Thank you.
Created the custom interface click action to get the control in fragment class
i hope it will works for you
public class MoviesAdapter extends RecyclerView.Adapter {
MoviesAdapterCallback moviesAdapterCallback;
private List<Movie> mMovieList;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context,MoviesAdapterCallback moviesAdapterCallback) {
this.mContext = context;
this.moviesAdapterCallback =moviesAdapterCallback;
this.mInflater = LayoutInflater.from(context); //
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
View view = mInflater.inflate(R.layout.movie_row_item, parent, false);
final MovieViewHolder viewHolder = new MovieViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* int position = viewHolder.getAdapterPosition();
Intent intent = new Intent(mContext, MovieDetailActivity.class);
intent.putExtra(MovieDetailActivity.MOVIE_EXTRA, mMovieList.get(position));
mContext.startActivity(intent);
*/ moviesAdapterCallback.MovieClicked(view);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movie movie = mMovieList.get(position);
Picasso.with(mContext)
.load(movie.getPoster())
.placeholder(R.color.colorAccent)
.into(holder.thumbnail);
holder.movieTitle.setText(movie.getTitle());
holder.rating.setText(movie.getRating());
}
#Override
public int getItemCount() {
return (mMovieList == null) ? 0 : mMovieList.size();
}
public void setMovieList(List<Movie> movieList) {
this.mMovieList = new ArrayList<>();
this.mMovieList.addAll(movieList);
notifyDataSetChanged();
}
public interface MoviesAdapterCallback {
void MovieClicked(View view);
}
}
in Fragment Class
public class MovieListFragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
public MovieListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_movie_list, container, false);
ButterKnife.bind(this,view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mAdapter = new MoviesAdapter(getContext(), new MoviesAdapter.MoviesAdapterCallback(){
#Override
public void MovieClicked(View view) {
DisplayFragment displayFrag = (DisplayFragment) getFragmentManager()
.findFragmentById(R.id.display_frag);
if (displayFrag == null) {
// DisplayFragment (Fragment B) is not in the layout (handset layout),
// so start DisplayActivity (Activity B)
// and pass it the info about the selected item
Intent intent = new Intent(this, DisplayActivity.class);
intent.putExtra("position", position);
startActivity(intent);
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
displayFrag.updateContent(position);
}
}
});
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onStart() {
super.onStart();
getPopularMovies();
}
private void getPopularMovies() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
service.getPopularMovies(new Callback<Movie.MovieResult>() {
#Override
public void success(Movie.MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) { error.printStackTrace(); }
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
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);
}
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.