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.
Related
i have two Tabs as Tab1 and Tab2. On button click i want send list row data to send Tab , Following is my code.
PagerAdapter.java
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs = 2;
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentOne tab1 = new FragmentOne();
return tab1;
case 1:
FragmentTwo tab2 = new FragmentTwo();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
TAB 1 :
TAB 2 :
FragmentOne.java
public class FragmentOne extends Fragment implements
FirstAdapter.MyClickListner {
private RecyclerView rvMovieList;
MovieModel movieModel;
private FirstAdapter firstAdapter;
private List<MovieModel> movieList = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
rvMovieList = (RecyclerView) view.findViewById(R.id.rvMovieList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
rvMovieList.setLayoutManager(mLayoutManager);
rvMovieList.setItemAnimator(new DefaultItemAnimator());
new asyncGetMovie().execute();
return view;
}
#Override
public void onButtonClick(int position) {
Toast.makeText(getActivity(), "Clicked Item "+position, Toast.LENGTH_SHORT).show();
}
class asyncGetMovie extends AsyncTask<String, String, String> {
String jsonString;
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading");
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
try {
// here we get movieList
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
firstAdapter = new FirstAdapter(movieList , FragmentOne.this);
rvMovieList.setAdapter(firstAdapter);
}
}
}
FragmentTwo.java
public class FragmentTwo extends Fragment {
private TextView tvTitle;
public FragmentTwo() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
MovieModel movieModel = null;
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
if (movieModel != null){
movieModel = getArguments().getParcelable("data");
System.out.println(" movieModel title "+movieModel.getTitle());
tvTitle.setText(movieModel.getTitle());
}
return view;
}
}
FirstAdapter.java
public class FirstAdapter extends
RecyclerView.Adapter<FirstAdapter.MyViewHolder> {
private MyClickListner clickListner;
private List<MovieModel> moviesList;
FragmentOne fragament ;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
Button btnDetails;
MyClickListner clickListner;
public MyViewHolder(View view) {
super(view);
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
btnDetails = (Button)view.findViewById(R.id.btnDetails);
}
}
public FirstAdapter(List<MovieModel> moviesList, FragmentOne fragmentOne) {
this.moviesList = moviesList;
this.fragament = fragmentOne;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_movie_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
MovieModel movie = moviesList.get(position);
holder.tvTitle.setText(movie.getTitle());
holder.btnDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragament.onButtonClick(position);
}
});
}
#Override
public int getItemCount() {
return moviesList.size();
}
public interface MyClickListner{
public void onButtonClick(int position);
}
}
Change you getItem()
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentOne tab1 = new FragmentOne();
return tab1;
case 1:
FragmentTwo tab2 = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putExtra("KEY_OF_WHATEVER_YOU_WANT_TO_SEND","VALUE");
tab2.setArguments(bundle);
return tab2;
default:
return null;
}
}
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
}
I have a project that needs to have two viewpager, each in a different fragment of the activity.
The architecture something like this
The problem is that when a pager view is inflated, the other isn't.
For example, the fragments 1, 2 and 3 can be accessed by clicking. When I click on the first fragment, it inflates the view pager with its two fragments perfectly, but if I click on the fragment 3, the view pager does not inflate the fragments and also the tabs get slower.
Opening the application process again, by clicking on the fragment 3 first, it works perfectly, but clicking on the first after, this problem happens again.
Already debugged the processes and there is nothing different.
My Activity
public class HomeActivity extends AppCompatActivity implements NavigationFragment.OnNavigationListener{
public NavigationFragment mNavigation;
private String mTagFragmentShowing = "";
private int currentNavigation = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
mNavigation = (NavigationFragment) getFragmentManager().findFragmentById(R.id.manager_navigation);
onNavigationSelected(currentNavigation);
}
#Override
public void onNavigationSelected(int position) {
if (mTagFragmentShowing.equals(String.valueOf(position)))
return;
currentNavigation = position;
mNavigation.setNavigationSelected(position);
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(mTagFragmentShowing);
// Hide last fragment
if (fragment != null && fragment.isVisible()) {
fragmentManager.beginTransaction().hide(fragment).commit();
}
// Show new fragment
mTagFragmentShowing = String.valueOf(position);
fragment = fragmentManager.findFragmentByTag(mTagFragmentShowing);
if (fragment != null && fragment.isHidden()) {
fragmentManager.beginTransaction().show(fragment).commit();
} else if (fragment == null) {
fragmentManager.beginTransaction().add(R.id.manager_content, getFragmentByPosition(position), mTagFragmentShowing)
.setTransition(FragmentTransaction.TRANSIT_NONE).commit();
}
}
private Fragment getFragmentByPosition(int position) {
switch (position) {
case 0:
return new DiscoverFragment();
case 1:
return new UpcomingFragment();
case 2:
return new FeaturesFragment();
case 3:
return new VideosFragment();
case 4:
return new MySongsFragment();
}
return null;
}
My Navigation Fragment. It control the other fragments
public class NavigationFragment extends Fragment implements View.OnClickListener {
public ViewHolder mHolder;
public View mButtonSelected;
public OnNavigationListener mCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.component_navigation, container, false);
ButterKnife.bind(this, view);
initView(view);
return view;
}
public void initView(View view) {
mHolder = new ViewHolder();
mHolder.discover = view.findViewById(R.id.component_navigation_discover);
mHolder.upcoming = view.findViewById(R.id.component_navigation_upcoming);
mHolder.features = view.findViewById(R.id.component_navigation_features);
mHolder.videos = view.findViewById(R.id.component_navigation_videos);
mHolder.mymusic = view.findViewById(R.id.component_navigation_mymusic);
mHolder.discover.setTag(0);
mHolder.upcoming.setTag(1);
mHolder.features.setTag(2);
mHolder.videos.setTag(3);
mHolder.mymusic.setTag(4);
mHolder.discover.setOnClickListener(this);
mHolder.upcoming.setOnClickListener(this);
mHolder.features.setOnClickListener(this);
mHolder.videos.setOnClickListener(this);
mHolder.mymusic.setOnClickListener(this);
mButtonSelected = mHolder.features;
}
public void setNavigationSelected(int position) {
setNavigationButtonSelected(false);
switch (position) {
case 0:
mButtonSelected = mHolder.discover;
break;
case 1:
mButtonSelected = mHolder.upcoming;
break;
case 2:
mButtonSelected = mHolder.features;
break;
case 3:
mButtonSelected = mHolder.videos;
break;
case 4:
mButtonSelected = mHolder.mymusic;
break;
}
setNavigationButtonSelected(true);
}
public void setNavigationButtonSelected(boolean enabled) {
mButtonSelected.setBackgroundColor(enabled ? getResources().getColor(R.color.color_red) : Color.TRANSPARENT);
}
#Override
public void onClick(View view) {
if (view != mButtonSelected) {
mCallback.onNavigationSelected((Integer) view.getTag());
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnNavigationListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnNavigationSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallback = null;
}
static class ViewHolder {
View discover;
View upcoming;
View features;
View videos;
View mymusic;
}
public interface OnNavigationListener {
public void onNavigationSelected(int position);
}
My Fragments with View Pager
public class MySongsFragment extends Fragment {
private OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.mysongs_fragment_container, MySongsViewPagerFragment.newInstance(0)).commit();
return inflater.inflate(R.layout.fragment_my_songs, container, false);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
My View Pager
public class MySongsViewPagerFragment extends Fragment {
private static final int NUM_PAGES = 4;
private String[] tab_names;
private List<String> mTabNames;
private PagerAdapter mPagerAdapter;
public #Bind(R.id.pager)
ViewPager mPager;
public static MySongsViewPagerFragment newInstance(int index) {
MySongsViewPagerFragment fragment = new MySongsViewPagerFragment();
Bundle args = new Bundle();
args.putInt("index", index);
fragment.setArguments(args);
return fragment;
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = initView(inflater, container);
return view;
}
#NonNull private View initView(LayoutInflater inflater, ViewGroup container) {
View view = inflater.inflate(R.layout.fragment_view_pager_my_songs, container, false);
ButterKnife.bind(this, view);
tab_names = getResources().getStringArray(R.array.tabs_mysongs);
mTabNames = Arrays.asList(tab_names);
mPagerAdapter = new ScreenSlidePagerAdapter(getActivity().getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mPager.onTouchEvent(event);
return false;
}
});
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mPager);
return view;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override public Fragment getItem(int position) {
switch (position) {
case 0:
return new PlaylistsFragment();
case 1:
return new SongsFragment();
case 2:
return new AlbumsFragment();
case 3:
return new ArtistsFragment();
default:
return new PlaylistsFragment();
}
}
#Override public int getCount() {
return NUM_PAGES;
}
#Override public CharSequence getPageTitle(int position) {
return mTabNames.get(position);
}
}
The problem was activity context in viewpager
In My View Pagers. I change
mPagerAdapter = new ScreenSlidePagerAdapter(getActivity().getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
to
mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
mPager.setAdapter(mPagerAdapter);
The two viewpager used the same context. So when I inflated the first, the other was not inflated because interpreted that already existed an inflated viewpager.
Thanks for the help mcwise for show me the method getChildFragmentManager().
I have an application that has a scrollable tab view in which each tab is a fragment. Now i want each tab to have a custom list view. But according to code I came up with there is a problem in the fragment in passing its instance as it wants an Activity's instance.
Here is the fragment that has the error at the 11th line where the adapter is asking for an instance to be passed.
public class Department extends Fragment {
public Department(){}
private String TAG = Department.class.getSimpleName();
private static final String url = "http://api.androidhive.info/json/movies.json";
private List<Socs> socList = new ArrayList<>();
private ListView listView;
private CustomListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dept,container,false);
listView = (ListView) rootView.findViewById(R.id.lvDept);
adapter = new CustomListAdapter(Department.this,socList);
listView.setAdapter(adapter);
JsonArrayRequest socRequest = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length() ; i++){
try {
JSONObject obj = response.getJSONObject(i);
Socs socs = new Socs();
socs.setDesc(obj.getString("title"));
socs.setName(obj.getString("title"));
socList.add(socs);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ERROR" + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(socRequest);
return rootView;
}
}
The error that Android Studio is giving is
CustomListAdapter (Android.app.Activity, List<socs>) can not be applied to CustomListAdapter(com..Department, List<socs>)
Here is the adapter for CustomList
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Socs> socItems;
public CustomListAdapter(Activity activity, List<Socs> socItems){
this.activity = activity;
this.socItems = socItems;
}
#Override
public int getCount() {
return socItems.size();
}
#Override
public Object getItem(int position) {
return socItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater==null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView==null)
convertView = inflater.inflate(R.layout.list_row,null);
TextView nameL = (TextView) convertView.findViewById(R.id.socName);
TextView descL = (TextView) convertView.findViewById(R.id.socDesc);
Socs socs = socItems.get(position);
nameL.setText(socs.getName());
descL.setText(socs.getDesc());
return convertView;
}
}
And the Scrollable tabs adapter
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new Department();
break;
case 1:
fragment = new Technical();
break;
case 2:
fragment = new Cultural();
break;
case 3:
fragment = new StudentChapters();
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
String title = new String();
switch (position){
case 0:
title="Department";
break;
case 1:
title="Technical";
break;
case 2:
title="Cultural";
break;
case 3:
title="Student Chapters";
break;
default:
title=null;
break;
}
return title;
}
}
I tried changing the department to Activity but then the scrollable tabs adapter gives an error. I tried using getActivity() in CustomListAdapter but it gives an error at runtime that I am giving a null feed to the fragment as I have not yet assigned any value to the fragment. Just for checking, I then gave a temporary value to fragment so it could inflate the default view. It still gave a null error.
The error comes from the fact you are calling CustomListAdapter(); with the fragment as the first parameter and this object's constructor is expecting an activity. Instead you could do something like this:
new CustomListAdapter(Department.this.getActivity(),socList);
For your second problem, could you update your question with the error you get?
I use the example of a pager enter link description here
I have everything worked out but there is one problem. I have 4 different fragments. One of them contains ListView. When I click on an item in the ListView, change the global variable guestId. If then return to other fragments, these they should be changed. Because they use this variable as a parameter. But they do not change.
public class Guest extends Fragment {
...
private ViewPager pager;
private MyPagerAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.guest, null);
...
if (InternetResiver.isOnline(getActivity())) {
setData();
} else {
AlertDialog alert = InternetResiver.getAlertDialog(getActivity());
alert.show();
}
return v;
}
public void startNewTread(String newId) {
guestId = newId;
Log.d("usernewid",newId);
setData();
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return Folio.newInstance(guestId,hotel,room);
case 1: return BalanceDetail.newInstance(guestId,hotel);
case 2: return History.newInstance(guestId,hotel);
case 3: return Record.newInstance(guestId,hotel,room);
default: return Folio.newInstance(guestId,hotel,room);
}
}
#Override
public int getCount() {
return 4;
}
}
public void setData() {
String link = String.format(......., guestId, hotel);
new MyAsincTask(getActivity()){........}.execute(link);
}
}
my fragment
public class Folio extends Fragment {
private ArrayList<FolioBean> folioBeans;
private TableLayout tableFolio;
private String guestId;
private String hotel;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.folio, null);
guestId = getArguments().getString("guestid");
hotel = getArguments().getString("hotel");
folioBeans = new ArrayList<>();
tableFolio = (TableLayout) v.findViewById(R.id.tableFolio);
if (InternetResiver.isOnline(getActivity())) {
setData();
} else {
AlertDialog alert = InternetResiver.getAlertDialog(getActivity());
alert.show();
}
return v;
}
public static Folio newInstance(String guestid,String hotel,String room) {
Folio f = new Folio();
Bundle b = new Bundle();
b.putString("guestid", guestid);
b.putString("hotel", hotel);
b.putString("room", room);
f.setArguments(b);
return f;
}
public void setData() {
String link = String.format(........., guestId, hotel);
new MyAsincTask(getActivity()){........}.execute(link);
}
}
other fragments are loaded using the same guestId
It is because ViewPager cached fragments. You need use FragmentStatePagerAdapter instead FragmentPagerAdapter, and call notifydatasetchanged() after changing guestId, and override
Override getItemPosition in your PagerAdapter like this:
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
see similar questions
Refresh images on FragmentStatePagerAdapter on resuming activity