i am suffering for 3 days. I'm using the View Pager from the compatibility library. I have successfully got it displaying several views .My Problem is that when i swap view then do not update data by fragment in its recycler view .But when i closed my application then opened fragments display update content by recycler view.i use all method like setnotifydatachanged() and many more but Fragment in viewpager does not update content.Thankx For any help
this is my main activity
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new MainAdapter(getSupportFragmentManager(),MainActivity.this));
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
addIconsToTab();
}
private void addIconsToTab() {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
int drwableId = -1;
switch (i) {
case 0:
drwableId = R.drawable.home;
break;
case 1:
drwableId = R.drawable.favourite;
break;
case 2:
drwableId = R.drawable.watchlater;
break;
}
tabLayout.getTabAt(i).setIcon(drwableId);
}
}
}
this is my main adapter
public class MainAdapter extends FragmentPagerAdapter {
Context mContext;
public MainAdapter(FragmentManager fm, Context context) {
super(fm);
mContext=context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new AllVideos();
case 1:
return new Favourite();
case 2:
return new WatchLater();
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return mContext.getString(R.string.All_Videos);
case 1:
return mContext.getString(R.string.Favourite);
case 2:
return mContext.getString(R.string.Wtach_Later);
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
And this is my Fragment
public class Favourite extends Fragment {
private RecyclerView mRecyclerView;
private FavouriteAdapter favouriteAdapter;
RecyclerView.LayoutManager layoutManager;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recyclerview_carpaccio, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(getActivity());
DatabaseHandler db = new DatabaseHandler(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
List<VideoInformationDataModel> videoinfo = db.getAllFavourite();
favouriteAdapter = new FavouriteAdapter(getActivity(),videoinfo);
mRecyclerView.setAdapter(favouriteAdapter);
favouriteAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(),videoinfo.size()+"",Toast.LENGTH_SHORT).show();
}
}
And this is fragmentAdapter
public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.MyViewHolder>
{
private int[] maid = {R.id.deleteoption};
Context context;
private List<VideoInformationDataModel> videoInformationDataModels;
String videoid1;
private FavouriteAdapter favouriteAdapter;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
View root;
protected ImageLoader img_uni_imageLoader;
DatabaseHandler db = new DatabaseHandler(context);
ImageView networkImage,options;
TextView Duration,Videoname;
public MyViewHolder(View view) {
super(view);
root = itemView.findViewById(R.id.videoImage);
Duration= (TextView) itemView.findViewById(R.id.duration);
Videoname= (TextView) itemView.findViewById(R.id.VideoName);
networkImage= (ImageView) itemView. findViewById(R.id.imgNetwork);
options= (ImageView) itemView.findViewById(R.id.deleteoption);
options.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (maid[0] == view.getId()) {
PopupMenu popup = new PopupMenu(context, options);
popup.getMenuInflater().inflate(R.menu.deleteoption, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.delete:
int pos = getAdapterPosition () ;
videoid1= videoInformationDataModels.get(pos).getVideoid();
db.deleteFavourite(videoid1);
videoInformationDataModels.remove(pos);
notifyItemRemoved(pos);
notifyItemRangeChanged(pos, getItemCount());
return true;
}
return false;
}
});
popup.show();
}
}
}
public FavouriteAdapter(Context context, List<VideoInformationDataModel> videoinformation) {
this.videoInformationDataModels = videoinformation;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favouritesingleitem, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.Duration.setText(videoInformationDataModels.get(position).getVideoduratio n());
holder.Videoname.setText(videoInformationDataModels.get(position).getVideoinfo() );
holder.img_uni_imageLoader = ImageLoader.getInstance();
.img_uni_imageLoader.init(ImageLoaderConfiguration.createDefault(context));
holder.img_uni_imageLoader.displayImage(videoInformationDataModels.get(position) .getVideoimg(), holder.networkImage);
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, YouTube.class);
Bundle extras = new Bundle();
String Videtittle = videoInformationDataModels.get(position).getVideoinfo();
String videodes = videoInformationDataModels.get(position).getFld_description();
String duration = videoInformationDataModels.get(position).getVideoduration();
String videoid = videoInformationDataModels.get(position).getVideoid();
extras.putString("Videtittle", Videtittle);
extras.putString("videodes", videodes);
extras.putString("duration", duration);
extras.putString("videoid", videoid);
intent.putExtras(extras);
context.startActivity(intent);
}
});
}
#Override
public int getItemViewType(int position)
{
return position;
}
public int getItemCount() {
return videoInformationDataModels.size();
}
}
I am not very sure what issue you are facing, but can you try once by replacing the FragmentPagerAdapter by FragmentStatePagerAdapter (extending by MainAdapter).
I don't clearly understand exactly what your issue is, It might be a result of wrong implementation. But if you have tried favouriteAdapter.notifyDataSetChanged(); and it still doesn't refresh.
You might as well remove the view, refresh it and add the view back and see if that works.
ViewGroup parent = (ViewGroup) viewPager.getParent(); // get the view parent
if (parent != null) {
parent.removeView(viewPager); // remove the view
viewPager.getAdapter().notifyDataSetChanged(); // notify that the data has changed
parent.addView(viewPager); // then, re-add the view
}
Related
I am building an Android Application which have Tab Layout in which there are Fragments and in Fragment I am displaying some value.
I have just only added hardcoded values to test the layout, but even these are not visible in the fragment.
Here is the code for ViewPagerAdapter:
public class FavouriteViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> favouriteFragmentList = new ArrayList<>(); // this line can cause crashes
private final List<String> favouriteFragmentListTitles = new ArrayList<>();
public FavouriteViewPagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
return favouriteFragmentList.get(position);
}
#Override
public int getCount() {
return favouriteFragmentListTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return favouriteFragmentListTitles.get(position);
}
public void AddFragment(Fragment fragment, String title) {
favouriteFragmentList.add(fragment); // this line can cause crashes
favouriteFragmentListTitles.add(title);
}
}
I have tried the answers available already none of them solves my problem.
I debugged the application and my RecyclerViewAdapter is not even called, very strange. I have done this many time but this never happened.
Here is my code for RecyclerViewAdapter :
public class ProductsRecyclerAdapter extends RecyclerView.Adapter<ProductsRecyclerAdapter.viewHolder> {
Context context;
private List<FavouriteProducts> favouriteProductsData;
public ProductsRecyclerAdapter(Context context, List<FavouriteProducts> favouriteProductsData) {
this.context = context;
this.favouriteProductsData = favouriteProductsData;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_favourite_product_item, parent, false);
viewHolder vHolder = new viewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
holder.product_name.setText(favouriteProductsData.get(position).getProduct_name());
holder.product_price.setText(favouriteProductsData.get(position).getProduct_price());
holder.product_image.setImageResource(favouriteProductsData.get(position).getProduct_image());
Toast.makeText(context,favouriteProductsData.get(position).getProduct_price() , Toast.LENGTH_SHORT).show();
/*holder.heart_button.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
showSuccessToast(context,"Liked");
}
#Override
public void unLiked(LikeButton likeButton) {
showSuccessToast(context,"Unliked");
}
});*/
}
#Override
public int getItemCount() {
return favouriteProductsData.size();
}
static class viewHolder extends RecyclerView.ViewHolder {
MaterialTextView product_name, product_price;
ImageView product_image;
LikeButton heart_button;
public viewHolder(#NonNull View itemView) {
super(itemView);
product_name = itemView.findViewById(R.id.product_name);
product_price = itemView.findViewById(R.id.product_price);
product_image = itemView.findViewById(R.id.product_image);
heart_button = itemView.findViewById(R.id.heart_button);
}
}
}
I am not getting any errors but after I check adapter is not even called. Some help will be really helpful.
Fragment Code:
public class FavouriteProductsFragment extends Fragment {
View v;
private List<FavouriteProducts> productList;
public FavouriteProductsFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
productList = new ArrayList<>();
productList.add(new FavouriteProducts("All Weather", "200/Ltr", R.drawable.all_weather));
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.products_favourite_fragment, container, false);
RecyclerView productRecyclerView = v.findViewById(R.id.favourite_products_rv);
ProductsRecyclerAdapter recyclerAdapter = new ProductsRecyclerAdapter(getContext(), productList);
productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productRecyclerView.hasFixedSize();
productRecyclerView.setAdapter(recyclerAdapter);
return v;
}
}
productList = new ArrayList<>();
productList.add(new FavouriteProducts("All Weather", "200/Ltr",R.drawable.all_weather));
recyclerAdapter.notifyDataSetChanged()
RecyclerView productRecyclerView = v.findViewById(R.id.favourite_products_rv);
ProductsRecyclerAdapter recyclerAdapter = new ProductsRecyclerAdapter(getContext(), productList);
productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productRecyclerView.hasFixedSize();
productRecyclerView.setAdapter(recyclerAdapter);
You need to add
RecyclerView productRecyclerView = v.findViewById(R.id.favourite_products_rv);
ProductsRecyclerAdapter recyclerAdapter = new ProductsRecyclerAdapter(getContext(), productList);
productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productRecyclerView.hasFixedSize();
productRecyclerView.setAdapter(recyclerAdapter);
productList = new ArrayList<>();
productList.add(new FavouriteProducts("All Weather", "200/Ltr",R.drawable.all_weather));recyclerAdapter.notifyDataSetChanged()
and Remove oncreate() method
try productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); befor setting adapter in recyclerview.
Step1: First Create one or MoreFragment For Your ViewPager and in This Fragment Add your Recyclerview Code as per Your Requirement.
Like Below Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_whatsapp_image, container, false);
context = getActivity();
((HomeActivity) getActivity()).toolbar.setVisibility(View.VISIBLE);
setupView(root);
return root;
}
private void setupView(ViewGroup root) {
recyclerView = (RecyclerView) root.findViewById(R.id.recyclerViewImage);
progressBar=root.findViewById(R.id.simpleProgressBar);
txtinfo=root.findViewById(R.id.txtinfo);
setUPList();
}
Step2: Then Create ViewPager Adapter for Your TabLayout
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new AudioFragment();
if(position == 1) return new VideoFragment();
if(position == 2) return new ImageFragment();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "Audio";
if(position == 1) return "Video";
if(position == 2) return "Image";
throw new IllegalStateException("Unexpected position " + position);
}
}
Step3 : Then Call Your SetupViewpager Method in Your Oncreate method of your Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=findViewById(R.id.toolbar);
viewPager=findViewById(R.id.viewpager);
tabLayout=findViewById(R.id.tabs);
//add toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
setTabIcons();
}
NOTE: You Can Download ViewPager Code from Below Link.Click Here to View and Download
Hi I am using Tablayout in my
TAB1 TAB2 TAB3
When I open the app, by default TAB1 is selected. All the TABs have recyclerview. Now I have one FAB button for all the fragments. I am using FAB button for changing language.
Whenever user change language data will display as per language selection. Now issue is When I am on TAB3 and changing language instead of staying on TAB3 it goes to TAB1.
Can any one help me to solve this issue.
public class LibraryFragment extends Fragment {
private static final String TAG = LibraryFragment.class.getSimpleName();
private TabLayout tabLayout;
private ViewPager viewPager;
private String catid;
private FragmentManager fragmentManager;
private String SELECTED_ACTION;
private String SELECTED_LANGUAGE,SELECTED_LANGUAGENM,sel_cat;
private int VID_CODE;
private FloatingActionButton fab;
private ArrayList<LanguageModel> langList;
public LibraryFragment() {
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_library, container, false);
langList = (ArrayList<LanguageModel>) getArguments().getSerializable("langlist");
catid = getArguments().getString("frommusic");
SELECTED_ACTION = getArguments().getString("action");
SELECTED_LANGUAGE = getArguments().getString("sel_lang");
SELECTED_LANGUAGENM = getArguments().getString("sel_langnm");
sel_cat = getArguments().getString("sel_cat");
System.out.println("in library" + SELECTED_LANGUAGE);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
viewPager = (ViewPager) view.findViewById(R.id.view_pager);
viewPager.setAdapter(new CustomFragmentPageAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
fab = (FloatingActionButton) view.findViewById(R.id.fabChat);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setdailog();
}
});
return view;
}
public void setdailog()
{
final Dialog cpDialog = new Dialog(getActivity());
cpDialog.setTitle("Select Language");
cpDialog.setContentView(R.layout.alert_list);
ListView listView = (ListView) cpDialog.findViewById(R.id.listiview_lang);
AlertListAdapter mAdapter = new AlertListAdapter(langList, getActivity());
listView.setAdapter(mAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SELECTED_LANGUAGE = langList.get(position).getLangid();
System.out.println("JO JO"+SELECTED_LANGUAGE);
Intent intent=new Intent(getActivity(),MusicActivity.class);
intent.putExtra("langlist",langList);
intent.putExtra("selid",catid);
intent.putExtra("langid",SELECTED_LANGUAGE);
intent.putExtra("langname",langList.get(position).getLangname());
intent.putExtra("selcat",sel_cat);
startActivity(intent);
cpDialog.dismiss();
}
});
cpDialog.show();
}
public class AlertListAdapter extends BaseAdapter {
ArrayList<LanguageModel> mData;
Context mContext;
LayoutInflater inflater;
public AlertListAdapter(ArrayList<LanguageModel> data, Context context) {
mData = data;
mContext = context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.item_alert_list, null);
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.textView_languge);
tvTitle.setText(mData.get(position).getLangname());
return convertView;
}
}
public class CustomFragmentPageAdapter extends FragmentPagerAdapter {
private final String TAG = CustomFragmentPageAdapter.class.getSimpleName();
private static final int FRAGMENT_COUNT = 3;
public CustomFragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment f1 = new SongFragment();
Bundle args1 = new Bundle();
args1.putString("fromlibfrag", catid);
args1.putString("action", SELECTED_ACTION);
args1.putString("sel_lang", SELECTED_LANGUAGE);
args1.putSerializable("langlist",langList);
f1.setArguments(args1);
return f1;
case 1:
Fragment f2 = new PhotoFragment();
Bundle args2 = new Bundle();
args2.putString("fromlibfrag", catid);
args2.putString("action", SELECTED_ACTION);
args2.putString("sel_lang", SELECTED_LANGUAGE);
args2.putSerializable("langlist",langList);
f2.setArguments(args2);
return f2;
case 2:
Fragment f3 = new SmsFragment();
Bundle args3 = new Bundle();
args3.putString("fromlibfrag", catid);
args3.putString("action", SELECTED_ACTION);
args3.putString("sel_lang", SELECTED_LANGUAGE);
args3.putSerializable("langlist",langList);
f3.setArguments(args3);
return f3;
}
return null;
}
#Override
public int getCount() {
return FRAGMENT_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Videos";
case 1:
return "Photos";
case 2:
return "SMS";
}
return null;
}
}
}
int position=0;
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override public void onTabSelected(TabLayout.Tab tab){
position = tab.getPosition();
} });
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setdailog(position);
}
});
Now
public void setdailog(int currentTab)
{
final Dialog cpDialog = new Dialog(getActivity());
cpDialog.setTitle("Select Language");
cpDialog.setContentView(R.layout.alert_list);
ListView listView = (ListView) cpDialog.findViewById(R.id.listiview_lang);
AlertListAdapter mAdapter = new AlertListAdapter(langList, getActivity());
listView.setAdapter(mAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SELECTED_LANGUAGE = langList.get(position).getLangid();
System.out.println("JO JO"+SELECTED_LANGUAGE);
Intent intent=new Intent(getActivity(),MusicActivity.class);
intent.putExtra("langlist",langList);
intent.putExtra("selid",catid);
intent.putExtra("langid",SELECTED_LANGUAGE);
intent.putExtra("langname",langList.get(position).getLangname());
intent.putExtra("selcat",sel_cat);
intent.putExtra("currentTab" , currentTab);
startActivity(intent);
finish();
cpDialog.dismiss();
}
});
cpDialog.show();
}
Now In MusicActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int currentTab = intent.getIntExtra("currenttab", 0);
//here you can check if you get 1, 2 or 3 in currentTab then you have to set current tab to 1, 2 or 3 respectively.
}
My app has a fragment that host a nested viewPager (One fragment added every time) all views are linked to the same layout.
Each fragment has a fixed button + recylerview that retrieve its data from firebase adapter.
When I click on the button, it show the correct viewPager position. But if I click on the listview item (viewHolder) it show the next pre-loaded position in the viewPager.
here's the viewpager and the pager adapter of the root fragment
Explore.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_explore, container, false);
array = controller.SELECTED_CATEGORIES;
viewPager = (ViewPager) root.findViewById(R.id.viewPager);
tabLayout = (TabLayout) root.findViewById(R.id.categories_tablayout);
tabLayout.setupWithViewPager(viewPager);
mAdapter = new MyAdapter(getFragmentManager());
viewPager.setAdapter(mAdapter);
return root;
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return controller.SELECTED_CATEGORIES.length;
}
#Override
public Fragment getItem(int position) {
return CategoriesFragment.newInstance(position);
}
#Override
public CharSequence getPageTitle(final int position) {
return controller.SELECTED_CATEGORIES[position];
}
}
CategoriesFragment.java
static CategoriesFragment newInstance(int num) {
CategoriesFragment f = new CategoriesFragment();
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_categories, container, false);
initialize();
listCategoriesFeed = (RecyclerView) rootView.findViewById(R.id.listCategoriesFeeds);
categoriesFeedAdapter = new CategoriesFeedAdapter(CategoriesFeedItem.class, R.layout.categoriesfeed_list_item, CategoriesFeedHolder.class, myref);
llm = new LinearLayoutManager(rootView.getContext());
llm.setOrientation(LinearLayoutManager.VERTICAL);
listCategoriesFeed.setLayoutManager(llm);
listCategoriesFeed.setAdapter(categoriesFeedAdapter);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
//Holder itemClickListener
CategoriesFeedHolder.registerOnItemClickListener(this);
//TextView onclick listener
View tv = rootView.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("position",mNum + "");
}
});
return rootView;
}
#Override
public void onItemClick(View view, int position) {
super.onItemClick(view, position);
switch (view.getId()) {
case R.id.firstId:
Log.e("position",mNum+ "");
break;
case R.id.secondId:
secondAction....
.....
.....
.....
break;
}
}
private void initialize() {
controller.showProgressDialog();
list = controller.getIniCategoriesDetailsList();
list.clear();
controller.categoriesDetailsList.put(controller.SELECTED_CATEGORIES[mNum],list);
reference = FirebaseDatabase.getInstance().getReference("firebase-path/" + controller.SELECTED_CATEGORIES[mNum]);
myref = reference.orderByChild("order-by").limitToFirst(i);
myref.addChildEventListener(this);
}
CategoriesFeedHolder.java
private CategoriesFeedItem model;
private final ImageView mImage;
private static OnItemClickListener onItemClickListener;
public CategoriesFeedHolder(View itemView) {
super(itemView);
this.context = itemView.getContext();
mImage = (ImageView) itemView.findViewById(R.id.m_image);
mImage.setOnClickListener(this);
}
public static void registerOnItemClickListener(OnItemClickListener onItemClickListener) {
CategoriesFeedHolder.onItemClickListener = onItemClickListener;
}
public void setModel(CategoriesFeedItem model) {
this.model = model;
}
#Override
public void onClick(View view) {
onItemClickListener.onItemClick(view, getAdapterPosition());
}
Does anyone know why this happens?
The problem was with the viewholder class, there was no data binding inside it. So when i clicked on any item inside the viewholder, it performed the action on the current adapter's data (preloaded data).
the viewholder class should be something like this:
public ViewHolder(View itemView) {
super(itemView);
share = (ImageView) itemView.findViewById(R.id.share);
}
public void bindToPost(Post post, View.OnClickListener onClickListener) {
share.setOnClickListener(onClickListener);
}
This is very simplified problem that I have regarding to Fragments and calling methods between fragments. I have put in the code place where I think calling method should be. Correct me if I'm wrong or if you have right solution for my problem. MainFragment extends Fragment because it is not activity... I have navigation drawer so that is how it suppose to be... :)
public class MainFragment extends Fragment{
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pager, container, false);
adapter = new CategoriesPagerAdapter(getChildFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// ...here I need to call method "writeText()" in both fragments to update both TextViews also in both fragments (tabs)
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Tab1Class tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
Tab2Class tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
Tab2Class:
public class Tab1Class extends Fragment {
TextView tv1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tv1 = (TextView) rootView.findViewById(R.id.tv1);
writeText();
}
public void writeText(){
tv1.setText("TV1 text");
}
}
Tab1Class:
public class Tab2Class extends Fragment {
TextView tv2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab2, container, false);
tv2 = (TextView) rootView.findViewById(R.id.tv2);
writeText();
}
public void writeText(){
tv2.setText("TV2 text");
}
}
.
.
.
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/////////////////////////Added////////////
adapter.callWrite();
////////////////////////////////////////
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
/////////////////////Added///////////////////
Tab1Class tab1;
Tab2Class tab2;
//////////////////////////////
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
////////////////////////////Added////////////////////
public void callWrite(){
if(tab1 != null)
tab1.writeText();
if(tab2 != null)
tab2.writeText();
}
/////////////
.
.
.
Here's an alternative:
public class BlankFragment extends Fragment {
public static final String ACTION_SOME_STUFF_HAPPENED = "stuff_happened_yo";
public static final String EXTRA_STUFF = "this_is_stuff";
public static void notifyStuffHappening(Context context, String stuff){
Intent intent = new Intent(ACTION_SOME_STUFF_HAPPENED);
intent.putExtra(EXTRA_STUFF, stuff);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
private StuffHappenedReceiver mStuffListener;
public static class StuffHappenedReceiver extends BroadcastReceiver {
final BlankFragment mFragment;
public StuffHappenedReceiver(BlankFragment fragment) {
this.mFragment = fragment;
// listen for changes to the account we're using
IntentFilter filter = new IntentFilter(ACTION_SOME_STUFF_HAPPENED);
LocalBroadcastManager.getInstance(fragment.getContext()).registerReceiver(this, filter);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_SOME_STUFF_HAPPENED.equals(action)) {
mFragment.someStuffHappened(intent.getStringExtra(EXTRA_STUFF));
}
}
}
private void someStuffHappened(String stringExtra) {
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mStuffListener = new StuffHappenedReceiver(this);
}
#Override
public void onDetach() {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mStuffListener);
mStuffListener = null;
super.onDetach();
}
}
This shows the basics of a fragment that will register a broadcast receiver automatically as it attaches / detaches from the activity.
If the fragment is not attached, it won't be updated.
To update this fragment, call the static method "notifyStuffHappening"
I am using this library: https://github.com/florent37/MaterialViewPager
I am using View Pager fragment to display timetable of my college in different tabs as from Monday to Friday.
My View Pager is in a fragment when opens when a item is clicked in list of NavDrawer. So I get data from database(sql) and create 5 List<> and get their corresponding data and at the time fragment is loaded as:
Error that I am getting is that when I open the fragment, I get timetable of friday in all tabs.
FragmentClass:
public class MaterialVPFrag extends Fragment {
private MaterialViewPager mViewPager;
List<Model_Daywise> todayslist_m;
List<Model_Daywise> todayslist_t;
List<Model_Daywise> todayslist_w;
List<Model_Daywise> todayslist_th;
List<Model_Daywise> todayslist_fr;
public static MaterialVPFrag newInstance() {
return new MaterialVPFrag();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.mvp_layout, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
todayslist_m = new MTWTHgetset(getActivity(), "monday").getAllCredentials();
todayslist_t = new MTWTHgetset(getActivity(), "tuesday").getAllCredentials();
todayslist_w = new MTWTHgetset(getActivity(), "wednesday").getAllCredentials();
todayslist_th = new MTWTHgetset(getActivity(), "thursday").getAllCredentials();
todayslist_fr = new MTWTHgetset(getActivity(), "friday").getAllCredentials();
mViewPager = (MaterialViewPager) view.findViewById(R.id.materialViewPager);
mViewPager.getViewPager().setAdapter(new FragmentStatePagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Log.d("c0", "");
return new RecyclerViewFragment(todayslist_t);
case 1:
Log.d("c1", "");
return new RecyclerViewFragment(todayslist_t);
case 2:
Log.d("c2", "");
return new RecyclerViewFragment(todayslist_w);
case 3:
Log.d("c3", "");
return new RecyclerViewFragment(todayslist_th);
case 4:
Log.d("c4", "");
return new RecyclerViewFragment(todayslist_fr);
default:
Log.d("cdef", "");
return new RecyclerViewFragment(todayslist_m);
}
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Monday";
case 1:
return "Tuesday";
case 2:
return "Wednesday";
case 3:
return "Thursday";
case 4:
return "Friday";
}
return "";
}
});
mViewPager.setMaterialViewPagerListener(new MaterialViewPager.Listener() {
#Override
public HeaderDesign getHeaderDesign(int page) {
switch (page) {
case 0:
return HeaderDesign.fromColorResAndUrl(
R.color.green,
"https://fs01.androidpit.info/a/63/0e/android-l-wallpapers-630ea6-h900.jpg");
case 1:
return HeaderDesign.fromColorResAndUrl(
R.color.blue,
"http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/files/2014/06/wallpaper_51.jpg");
case 2:
return HeaderDesign.fromColorResAndUrl(
R.color.cyan,
"http://www.droid-life.com/wp-content/uploads/2014/10/lollipop-wallpapers10.jpg");
case 3:
return HeaderDesign.fromColorResAndUrl(
R.color.red,
"http://www.tothemobile.com/wp-content/uploads/2014/07/original.jpg");
}
//execute others actions if needed (ex : modify your header logo)
return null;
}
});
mViewPager.getViewPager().setOffscreenPageLimit(mViewPager.getViewPager().getAdapter().getCount()); //it works without it don't know why!
mViewPager.getPagerTitleStrip().setViewPager(mViewPager.getViewPager());
View logo = view.findViewById(R.id.logo_white);
if (logo != null)
logo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mViewPager.notifyHeaderChanged();
Toast.makeText(getActivity(), "Yes, the title is clickable", Toast.LENGTH_SHORT).show();
}
});
}
}
RecyclerViewFragment.java
public class RecyclerViewFragment extends Fragment {
private RecyclerView mRecyclerView;
public static RecyclerView.Adapter mAdapter;
List<Model_Daywise> list;
public RecyclerViewFragment() {
}
public RecyclerViewFragment(List<Model_Daywise> lis) {
list = lis;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recyclerview, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mAdapter = new RecyclerViewMaterialAdapter(new CardAdapter_Daywise(list, getActivity()));
mRecyclerView.setAdapter(mAdapter);
MaterialViewPagerHelper.registerRecyclerView(getActivity(), mRecyclerView, null);
}
}
CardAdapter_Daywise.java
public class CardAdapter_Daywise extends RecyclerView.Adapter<CardAdapter_Daywise.CardViewHolderDaywise> {
private static List<Model_Daywise> cardList;
private Context context = null;
public CardAdapter_Daywise(List<Model_Daywise> list, Context context) {
this.cardList = list;
this.context = context;
}
#Override
public CardViewHolderDaywise onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_layout_daywise, viewGroup, false);
return (new CardViewHolderDaywise(itemView));
}
#Override
public void onBindViewHolder(final CardAdapter_Daywise.CardViewHolderDaywise cardViewHolder, int i) {
final Model_Daywise cl = cardList.get(i);
cardViewHolder.subname.setText(cl.getSubname());
cardViewHolder.subcode.setText(cl.getSubcode());
cardViewHolder.slot.setText(cl.getSubslot());
cardViewHolder.timings.setText(cl.getSubtimings());
cardViewHolder.teacher.setText(cl.getSubteacher());
cardViewHolder.venue.setText(cl.getVenue());
}
#Override
public int getItemCount() {
return cardList.size();
}
public class CardViewHolderDaywise extends RecyclerView.ViewHolder {
TextView subname, subcode, slot, venue, teacher, timings;
public CardViewHolderDaywise(View v) {
super(v);
subname = (TextView) v.findViewById(R.id.subject_name_daywise);
subcode = (TextView) v.findViewById(R.id.sub_code_daywise);
slot = (TextView) v.findViewById(R.id.slot_daywise);
venue = (TextView) v.findViewById(R.id.venue_daywise);
teacher = (TextView) v.findViewById(R.id.teacher_daywise);
timings = (TextView) v.findViewById(R.id.timings_daywise);
}
}
}
In RecyclerViewFragment you've declared the list field as static which means that every RecyclerViewFragment instance will share the data that was last put in it.
For example, if you first show the RecyclerViewFragment for monday it will load the todayslist_m list in the 'list' reference. But, the ViewPager will also build the fragment for the next page(tuesday in your case) to improve performance which means a new RecyclerViewFragment will be created, this time the static list reference pointing to todayslist_m. This way you'll end up having the RecyclerViewFragment for both monday and tuesday pointing the same list of data(the last one set on the RecyclerViewFragment).
The solution is to make the list reference in RecyclerViewFragment to not be static and rethink your approach if you used static as a mean to reference the list from outside the RecyclerViewFragment fragment.