I have implemented one app where I have 7 tabs and I used addOnScrollListener to fetch the data when user will scroll the list. My issue is when I move one fragment or tab to another fragment and then come back on the privious tab, the data is not coming on second time on that tab.
Below is my fragment class
public class EI_Pending_Fragment extends Fragment{
SessionManager session;
private List<SuperHero> listSuperHeroes;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public ProgressBar progressBar;
private RequestQueue requestQueue;
private int requestCount1 = 1;
private Boolean isStarted = false;
private Boolean isVisible = false;
public String email;
public EI_Pending_Fragment() {}
#Override
public void onStart() {
super.onStart();
isStarted = true;
if (isVisible && isStarted){
getData();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
isVisible = isVisibleToUser;
if (isStarted && isVisible) {
getData();
}
}
#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.activity_main_test, container, false);
session = new SessionManager(getActivity());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
return view;
}
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
listSuperHeroes = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getContext());
// getData();
adapter = new CardAdapter(listSuperHeroes, getActivity());
recyclerView.setAdapter(adapter);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int
newState) {
super.onScrollStateChanged(recyclerView, newState);
if (isLastItemDisplaying(recyclerView)) {
if(requestCount1==1){
exit();
}
else {
getData();
}
}
}
});
}
private JsonArrayRequest getDataFromServer(int requestCount) {
Log.e("email",email);
final String DATA_URL = "http://192.168.2.110/xp/ei_pending_received.php?matri_id="+email+"&page=";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response",response.toString());
if(response.length()==0){
requestCount1 = 1;
}
else {
parseData(response);
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
return jsonArrayRequest;
}
private void getData() {
requestQueue.add(getDataFromServer(requestCount1));
requestCount1++;
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Log.e("array",array.toString().trim());
SuperHero superHero = new SuperHero();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setImageUrl(json.getString(Config_Test.TAG_IMAGE_URL));
superHero.setMglId(json.getString(Config_Test.TAG_MGLID));
superHero.setAge(json.getString(Config_Test.TAG_AGE));
superHero.setAgeHeight(json.getString(Config_Test.TAG_HEIGHT));
superHero.setCommunity(json.getString(Config_Test.TAG_COMMUNITY));
superHero.setCaste(json.getString(Config_Test.TAG_CASTE));
superHero.setOccupation(json.getString(Config_Test.TAG_OCCUPATION));
superHero.setIncome(json.getString(Config_Test.TAG_INCOME));
superHero.setStatus(json.getString(Config_Test.TAG_STATUS));
superHero.setRequested_On(json.getString(Config_Test.TAG_REQUESTED_ON));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(superHero);
}
adapter.notifyDataSetChanged();
}
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
void exit(){
Toast.makeText(getContext(),"no more data avilable",Toast.LENGTH_SHORT).show();
}
}
Below is my Activity class where I add all the tab
private void setupViewPager(ViewPager viewPager) {
int numberOfPages=7;
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new NewMatches_Tab(), "New matches");
adapter.addFragment(new Broader_Match_Tab(), "Broader Matches");
adapter.addFragment(new Similar_Matchs_Tab(), "Similar Matches");
adapter.addFragment(new ShortlistTab(), "ShortListed");
adapter.addFragment(new Viewed_My_Profile(), "View My Profile");
adapter.addFragment(new ShortListedMeTab(), "ShortListed Me");
adapter.addFragment(new Photo_Request_Received(), "Photo Request Received");
//viewPager.setOffscreenPageLimit(numberOfPages);
viewPager.setAdapter(adapter);
}
You can add an OnPageChangeListener in the activity and register it to your view pager and do all necessary "setting" within the OnPageChangeListener instance.
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//Do your fragment refreshing here
mCurrentPage = position;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
#Override
public void setFragmentsForContents(List<Content> contents) { //bundle data for your different fragments
if(contents!=null){
NUM_PAGES = contents.size();
mContentPager.addOnPageChangeListener(viewPagerPageChangeListener);
mContentPager.setAdapter(mScreenSlidePagerAdapter);
mContentPager.setCurrentItem(mCurrentPage);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ContentFragment.newInstance(mContents.get(position).getContent());
}
#Override
public int getCount() {
return NUM_PAGES;
}
#NonNull
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
#Override
public float getPageWidth(int position) {
return 1.0f;
}
}
Related
I add to my app ViewPager to display a set of images I get the image from database.It works fine but I need to work (Intent) to image.So where user click on image he should go to a new activity and see that picture in it.I searched for a solution and could not find the solution.
If anyone Knew the solution help me please.
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private List<SliderUtils> sliderImg;
private ImageLoader imageLoader;
public ViewPagerAdapter(List sliderImg,Context context) {
this.sliderImg = sliderImg;
this.context = context;
}
#Override
public int getCount() {
return sliderImg.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.custom_layout, null);
SliderUtils utils = sliderImg.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(utils.getSliderImageUrl(), ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher_round, android.R.drawable.ic_dialog_alert));
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == 0){
Toast.makeText(context, "Slide 1 Clicked", Toast.LENGTH_SHORT).show();
} else if(position == 1){
Toast.makeText(context, "Slide 2 Clicked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Slide 3 Clicked", Toast.LENGTH_SHORT).show();
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
public class FoodFregmaent extends Fragment {
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
RequestQueue rq;
List<SliderUtils> sliderImg;
ViewPagerAdapter viewPagerAdapter;
String request_url = "http://===========sliedshow.php";
public FoodFregmaent() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food_fregmaent, container, false);
rq = CustomVolleyRequest.getInstance(getContext()).getRequestQueue();
sliderImg = new ArrayList<>();
viewPager = (ViewPager) view.findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout)view. findViewById(R.id.SliderDots);
sendRequest();
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return view;
}
public void sendRequest(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
SliderUtils sliderUtils = new SliderUtils();
try {
JSONObject jsonObject = response.getJSONObject(i);
sliderUtils.setSliderImageUrl(jsonObject.getString("imageurl"));
} catch (JSONException e) {
e.printStackTrace();
}
sliderImg.add(sliderUtils);
}
viewPagerAdapter = new ViewPagerAdapter(sliderImg, getActivity());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.ic_launcher_background));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
CustomVolleyRequest.getInstance(getContext()).addToRequestQueue(jsonArrayRequest);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);
}
public class MyTimerTask extends TimerTask {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(viewPager.getCurrentItem() == 0){
viewPager.setCurrentItem(1);
} else if(viewPager.getCurrentItem() == 1){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
public class SliderUtils {
String imageurl;
public String getSliderImageUrl() {
return imageurl;
}
public void setSliderImageUrl(String imageurl) {
this.imageurl = imageurl;
}
}
Still I search about solution to it
You can add an Intent with a String that contains the image URL into your view.setOnClickListener within the instantiateItem() of the ViewPager
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// ... Other code is omitted
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Activity2.class); // Change the name of the other activity
intent.putExtra("url", sliderImg.get(position).getSliderImageUrl()); // add the image URL to the other activity
}
});
And at the target activity, receive the url with
String url = getIntent().getStringExtra("url")
There is a question similar to me, but that solution didn't work for my case.
The question I have referred is
this
I have a fragment named "HomeFragment" which consists of a VieWPager and TabLayout. I am adding tabs dynamically from the backend. So I am using another Fragment named "SecondFragment" for all tabs since all tabs contain a RecyclerView only. I am populating the RecyclerView onCreate() of the SecondFragment. My issue comes here that when I swipe or change the tab, the RecyclerView not updating correctly. On continuing swiping, the data changes but it does not correspond to the selected tab. I have logged the flow and I am getting correct data from backend on swiping, but it does not updating the RrecyclerView.
My HomeFragment class is
public class HomeFragment extends Fragment implements HTTPCallback {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private CardView cardview;
private boolean isShow;
View rootview;
private Toolbar toolbar;
private ImageView imageView, tabBg;
private CollapsingToolbarLayout collapsingToolbar;
private TabLayout mTabLayout;
Context context;
private ViewPager mViewPager, mViewPager1;
AppBarLayout appBarLayout;
Integer url_size;
int i;
boolean stopSliding = false;
String url, url2;
String message, version;
private ArrayList<HomeModel> planList;
JSONObject jsonObject, jsonObject2;
JSONArray jsonArray, jsonArray2;
ViewPagerAdapter adapter;
List<Product> products;
int numTab = 0;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_home, container, false);
appBarLayout = (AppBarLayout) rootview.findViewById(R.id.appbar);
mViewPager1 = (ViewPager) rootview.findViewById(R.id.view_pager);
collapsingToolbar = (CollapsingToolbarLayout) rootview.findViewById(R.id.collapsing_toolbar);
sharedPreferences = getContext().getSharedPreferences("spade", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
mViewPager = (ViewPager) rootview.findViewById(R.id.viewpager);
mTabLayout = (TabLayout) rootview.findViewById(R.id.tabs);
mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
mTabLayout.setSelectedTabIndicatorHeight((int) (5 * getResources().getDisplayMetrics().density));
mTabLayout.setTabTextColors(Color.parseColor("#727272"), Color.parseColor("#FF0000"));
new HTTPRequest(getContext(), null, null, HTTPRequest.METHOD.GET, this).execute(url2);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 0) {
appBarLayout.setExpanded(true);
} else {
appBarLayout.setExpanded(false);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
try {
} catch (Exception e) {
e.printStackTrace();
}
mTabLayout.setOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
mViewPager.setCurrentItem(tab.getPosition());
numTab = tab.getPosition();
HomeModel browsePlan = planList.get(numTab);
editor.putString("tab", browsePlan.getName()).commit();
}
});
return rootview;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onConnectionStarted() {
}
#Override
public void onConnectionFailed() {
}
#Override
public void onCompleted(JSONObject resultData) {
HomeModel model;
planList = new ArrayList<>();
adapter = new ViewPagerAdapter(getChildFragmentManager());
try {
jsonArray = resultData.getJSONArray("details");
editor.putString("tab", jsonArray.getJSONObject(0).getString("name"));
editor.commit();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject2 = jsonArray.getJSONObject(i);
model = new HomeModel();
model.setCatid(jsonObject2.getString("id"));
model.setImage(jsonObject2.getString("image"));
model.setName(jsonObject2.getString("name"));
planList.add(model);
setupViewPager(mViewPager, jsonObject2.getString("name"));
}
setAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void setAdapter() {
appBarLayout.setExpanded(false);
mViewPager.setAdapter(adapter);
mTabLayout.setupWithViewPager(mViewPager);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void setupViewPager(ViewPager mViewPager, String name) {
adapter.addFragment(new SecondFragment(), name);
mViewPager.setOffscreenPageLimit(1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
SecondFragment class is
public class SecondFragment extends Fragment implements HTTPCallback {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
String mParam1;
String mParam2;
Button solo, grp;
View rootview;
Fragment fragment;
String url;
JSONObject jsonObject, jsonObject2;
JSONArray jsonArray, jsonArray2;
private ArrayList<Spaceship> planList;
RecyclerView rv;
private RecyclerHomeAdapter adapter = new RecyclerHomeAdapter(getContext(), planList);
;
private SharedPreferences sharedPreferences;
String tab_name;
private OnFragmentInteractionListener mListener;
public SecondFragment() {
}
public static SecondFragment newInstance(String s, String s1) {
SecondFragment fragment = new SecondFragment();
Bundle args = new Bundle();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_second, container, false);
sharedPreferences = getContext().getSharedPreferences("spade", Context.MODE_PRIVATE);
tab_name = sharedPreferences.getString("tab", "onnumilla");
rv = (RecyclerView) rootview.findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
url = "My_url_here";
HashMap<String, String> data = new HashMap<String, String>();
data.put("name", tab_name);
new HTTPRequest2(getContext(), data, null, HTTPRequest2.METHOD.POST, this).execute(url);
return rootview;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
adapter.notifyDataSetChanged();
// getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onConnectionStarted() {
}
#Override
public void onConnectionFailed() {
}
#Override
public void onCompleted(JSONObject resultData) {
Spaceship model;
planList = new ArrayList<>();
planList.clear();
try {
jsonArray = resultData.getJSONArray("products");
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject2 = jsonArray.getJSONObject(i);
model = new Spaceship();
model.setName(jsonObject2.getString("package_name"));
model.setImage(jsonObject2.getString("images"));
planList.add(model);
}
setAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void setAdapter() {
adapter = new RecyclerHomeAdapter(getContext(), planList);
adapter.notifyDataSetChanged();
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
This doesn't work for me. But in the setUserVisibleHint(boolean isVisibleToUser) method when i add getFragmentManager().beginTransaction().detach(this).attach(this).commit();
instead of adapter.notifyDataSetChanged(); it works but it takes some time to hide previous data on swiping tab.
Anyone, please suggest me a solution. I have referred many questions but nothing works for me. All your response is appreciated.
This seems to be ViewPager page cashing issue. pls call below code from onCreateView()
of HomeFragment.
mViewPager.setOffscreenPageLimit(1);
I have 4 fragments in my app, which managed in NavActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
fab = (FloatingActionButton) findViewById(R.id.fab);
// Fab for fragments
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
switch (state) {
case ViewPager.SCROLL_STATE_DRAGGING:
case ViewPager.SCROLL_STATE_SETTLING:
fab.hide(); // Hide animation
break;
case ViewPager.SCROLL_STATE_IDLE:
switch (viewPager.getCurrentItem()) {
case 0:
fragment1.shareFab(fab);
case 1:
fragment2.shareFab(fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(NavActivity.this, MapsActivity.class));
}
});
break;
default:
fragment1.shareFab(null);
break;
}
if(viewPager.getCurrentItem() == 0 || viewPager.getCurrentItem() == 1)
fab.show(); // Show animation
break;
}
}
});
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new MainFragment(), "Main");
adapter.addFragment(new AboutFragment(), "About");
adapter.addFragment(new CartFragment(), "Cart");
adapter.addFragment(new CatalogFragment(), "Catalog");
viewPager.setAdapter(adapter);
}
///////////new class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
}
I face one problem, items disappear after switching between fragments i think the implement with RecyclerView And the viewHolder has something to do with it.
Im trying to fetch data with volley from my server, into fragment C (frag num 3), the data streams well everything show correctly.
If i swap to frag B(frag num 2) or D(frag num 4), still everything works.
But if ill swap to frag A(frag num 1) and back to frag 3(where is my list item),
everything goes away, i get blank screen, even if i swap up and down still the items wont download again.
Here is Frag num 3 with my RecyclerView:
private FloatingActionButton mSharedFab;
private List<MyProducts> productsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//Volley Request Queue
private RequestQueue requestQueue;
private int requestCount = 1;
private static final String URL_INDEX = "http://myserverip/android/product.php?page=";
//Tag values to read from json
public static final String TAG_IMAGE_URL = "product_img";
public static final String TAG_PRODUCT_SN = "product_serial_num";
public static final String TAG_PRODUCT_TITLE = "product_title";
public static final String TAG_PRODUCT_PRICE = "product_price";
public static final String TAG_PRODUCT_DESCRIPTION = "product_description";
public CartFragment() {
// Required empty public constructor
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cart, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(getActivity().getApplicationContext(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
//Initializing our superheroes list
productsList = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
//Calling method to get data to fetch data
getData();
//Adding an scroll change listener to recyclerview
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP)
{
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (isLastItemDisplaying(recyclerView)) {
getData();
}
}
});
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
recyclerView.setOnScrollChangeListener( new RecyclerView.OnScrollChangeListener()
{
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (isLastItemDisplaying(recyclerView)) {
getData();
}
}
});
}
}
//initializing our adapter
adapter = new CustomAdapter(productsList, getActivity());
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
return view ;
}
and the customAdapter class:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
//Imageloader to load image
private ImageLoader imageLoader;
private Context context;
List<MyProducts> myProducts;
public CustomAdapter(List<MyProducts> myProducts, Context context)
{
super();
this.myProducts = myProducts;
this.context = context;
}
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomAdapter.ViewHolder holder, int position) {
if( myProducts != null) {
MyProducts myProducts1 = myProducts.get(position);
imageLoader = ImageVolley.getInstance(context).getImageLoader();
imageLoader.get(myProducts1.getProductImage(), ImageLoader.getImageListener(holder.imageView, R.drawable.android_store_log, android.R.drawable.ic_dialog_alert));
//Showing data to the views
holder.imageView.setImageUrl(myProducts1.getProductImage(), imageLoader);
holder.textViewProductTitle.setText(myProducts1.getProductTitle());
holder.textViewProductDescription.setText(myProducts1.getProductDescription());
holder.textViewProductSerialNumber.setText(myProducts1.getProductSn());
holder.textViewProductPrice.setText(myProducts1.getProductPrice());
}
}
#Override
public int getItemCount() {
return myProducts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
//Views
public NetworkImageView imageView;
public TextView textViewProductTitle;
public TextView textViewProductDescription;
public TextView textViewProductSerialNumber;
public TextView textViewProductPrice;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
textViewProductTitle = (TextView) itemView.findViewById(R.id.textViewProductTitle);
textViewProductDescription = (TextView) itemView.findViewById(R.id.textViewProductDescription);
textViewProductSerialNumber = (TextView) itemView.findViewById(R.id.textViewProductSerialNumber);
textViewProductPrice = (TextView) itemView.findViewById(R.id.textViewProductPrice);
}
}
Try this:
viewPager.setOffscreenPageLimit(3);
Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.
setOffscreenPageLimit
I have the following ViewPagerAdapter:
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(((AppCompatActivity)getActivity()).getSupportFragmentManager());
adapter.addFrag(new OwnerPendingBookingsFragment(), "Pendientes");
adapter.addFrag(new OwnerConfirmedBookingsFragment(), "Confirmados");
adapter.addFrag(new OwnerFinishedBookingsFragment(), "Finalizados");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
And one of the fragments that I use is like that:
public class OwnerConfirmedBookingsFragment extends Fragment {
private View myView;
private ListView booking_list;
private ArrayAdapter adapter;
private SharedPreferences preferences;
private Toast toast;
private ProgressDialog progressDialog;
private BookingList bookings;
private boolean isFirstTime;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (isFirstTime) {
myView = inflater.inflate(R.layout.owner_confirmed_bookings_layout, container, false);
isFirstTime = false;
}
return myView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFirstTime = true;
//Getting out sharedpreferences
preferences = getActivity().getSharedPreferences(Config.SHARED_PREF_LOGIN, Context.MODE_PRIVATE);
new FindBookings().execute("");
}
private void setUpAdapter(){
booking_list = (ListView) myView.findViewById(R.id.owner_confirmed_bookings);
getActivity().setTitle("Nuevas solicitudes");
if(bookings.getBookings().size() == 0){
booking_list.setVisibility(View.GONE);
LinearLayout no_vehicles = (LinearLayout) myView.findViewById(R.id.no_confirmed_bookings_layout);
no_vehicles.setVisibility(View.VISIBLE);
}else {
for (int i = 0; i < bookings.getBookings().size(); i++){
try {
new setImageTask(i).execute(bookings.getBookings().get(i).getDriver_image()).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
adapter = new OwnerFinishedBookingsAdapter(myView.getContext(), bookings.getBookings());
booking_list.setAdapter(adapter);
booking_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booking_line = bookings.getBookings().get(position).getBooking_line_id();
Fragment booking_info = new OwnerPendingBookingInfoFragment();
Bundle args = new Bundle();
args.putInt("bookingLine", booking_line);
booking_info.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, booking_info);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
}
private class FindBookings extends AsyncTask<String, Void, String> {
String token = preferences.getString(Config.TOKEN, "");
#Override
protected void onPreExecute() {
toast = Toast.makeText(getActivity().getApplicationContext(), "", Toast.LENGTH_LONG);
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage(getActivity().getString(R.string.finding_bookings));
progressDialog.show();
}
#Override
protected void onPostExecute(String s){
if(bookings.getError() != 0){
if(bookings.getError() == Config.JWT_EXPIRED){
logout();
Toast.makeText(getActivity().getApplicationContext(),
getActivity().getString(R.string.session_expired),
Toast.LENGTH_LONG).show();
}else {
toast.setText(getActivity().getString(R.string.find_pendings_errror));
toast.show();
}
}else {
setUpAdapter();
}
progressDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
bookings = DBConnect.getPendingBookingList(preferences.getInt(Config.IDUSER, 0), token);
return "done";
}
}
The first time I use it, all the fragments loads without any problem. But when I go to another activity and then return it doesn't update the data. I debug it and onCreate and onCreateView are not firing?
I tried to remove the fragment when going to another activity but nothing worked for me.
One of the problems I am currently facing is that if a user adds something to their timetable, it should be refreshed in the recyclerview in the second tab Current Timetable. However, it never updates and the user has to go back to the main menu, back onto the Timetables activity and then select Current Timetable. I believe it is something to do with my ViewPager and its adapter. I just can't see where I am going wrong and I am sure it is something simple that I am missing. Please could you modify my code such that it will work
Here is my code:
The viewpager class
public class Timetables extends AppCompatActivity{
TabLayout tabLayout;
ViewPager viewPager;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timetables);
viewPager = (ViewPager) findViewById(R.id.viewPager);
TimetablesAdapter timetablesAdapter = new TimetablesAdapter(getSupportFragmentManager(), Timetables.this);
viewPager.setAdapter(timetablesAdapter);
viewPager.setOffscreenPageLimit(2);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
//viewPager.setCurrentItem(tab.getPosition());
}
});
}
}
The fragmentpageradapter class:
public class TimestableAdapter extends FragmentPagerAdapter{
String tabNames[] = new String[] {"All timetables", "Current Timetable", "Expired"};
Context context;
public TimestableAdapter(FragmentManager fragmentManager, Context context){
super(fragmentManager);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new AllTimetables();
case 1:
return new CurrentTimetables();
case 2:
return new ExpiredTimetables();
default:
return null;
}
}
#Override
public int getCount() {
return tabNames.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabNames[position];
}
}
This is the CurrentTimetable class:
public class CurrentTimetables extends Fragment {
RecyclerView recyclerView;
static MusicRecyclerAdapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Timetables> list;
public CurrentTimetables(){
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currenttimetable, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.timetablerecyclerView);
recyclerView.setHasFixedSize(true);
list = new ArrayList<Timetables>();
adapter = new MusicRecyclerAdapter(list, CurrentTimetables.this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
tabBackground = new TabBackground(CurrentTimetables.this, list, spinnerItems, adapter, spinnerAdapter);
tabBackground.populateConditionsList();
inputs = new ArrayList<>();
populate();
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
}
#Override
public void onStart() {
super.onStart();
}
public void populate(){
String dbURL = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
RequestQueue requestQueue = Volley.newRequestQueue(fragment.getActivity());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(dbURL, new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray jsonArray) {
if(!list.isEmpty()){
list.clear();
}
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int timetableID = Integer.parseInt(jsonObject.getString("timetableID"));
String timetableName = jsonObject.getString("timetableName");
String subjectName = jsonObject.getString("subjectName");
Timetables timetables = new Timetables(timetableID, timetableName, subjectName);
list.add(timetables);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}
);
requestQueue.add(jsonArrayRequest);
}
}
Would really mean a lot of someone could help me out
Thanks
There are some changes needed in your code. If you check Fragment's LifeCycle you will understand how it works with Tabular View.
Check out Code I have made from above code.
public class CurrentTimetables extends Fragment {
RecyclerView recyclerView;
static MusicRecyclerAdapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Timetables> list;
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.currenttimetable, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = (RecyclerView) view.findViewById(R.id.timetablerecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
tabBackground = new TabBackground(CurrentTimetables.this, list, spinnerItems, adapter, spinnerAdapter);
tabBackground.populateConditionsList();
// If you have another Component add here using finViewById() and also you can do
// other process here. I just used setUserVisibleHint because it will execute when
// fragment will be visible to user and it will stop over calling to web service.
/**
* Populate Recyclerview data if setUserVisibleHint do not work.
*/
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
populate();
}
}
public void populate() {
String dbURL = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(dbURL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
if (!list.isEmpty()) {
list.clear();
}
try {
list = new ArrayList<Timetables>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int timetableID = Integer.parseInt(jsonObject.getString("timetableID"));
String timetableName = jsonObject.getString("timetableName");
String subjectName = jsonObject.getString("subjectName");
Timetables timetables = new Timetables(timetableID, timetableName, subjectName);
list.add(timetables);
adapter = new MusicRecyclerAdapter(list, context);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(5 * 1000, 1, 1.0F));
jsonArrayRequest.setShouldCache(false);
requestQueue.add(jsonArrayRequest);
}
#Override
public void onResume() {
super.onResume();
populate();
}
}
I might have forgot something from your code and you might have to add it.
You have to create an interface in mainActivity. Reference it in your fragments. Its is the best way to communicate from one fragment to another. Please refer the link below.
http://developer.android.com/training/basics/fragments/communicating.html
Have a look and if any doubts am here to help.