Not calling before fragment is shown - java

I'm showing fragments in viewpager, and each fragment contains data connection.
I don't want to do something, before selected fragment is shown.
How can I do?
I mean, I don't want to initiate fragments when the activity calls oncreate.(because there's data connection, and I don't want it)
I just want to initiate each fragment, when fragment is selected.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewPager = (ViewPager) findViewById(R.id.view_pager);
List<Fragment> listFragments = new ArrayList<>();
listFragments.add(new Fg_1());
listFragments.add(new Fg_2());
listFragments.add(new Fg_3());
listFragments.add(new Fg_4());
listFragments.add(new Fg_5());
listFragments.add(new Fg_6());
a_pagerAdapter = new A_PagerAdapter(getSupportFragmentManager(), listFragments);
viewPager.setAdapter(a_pagerAdapter);
viewPager.addOnPageChangeListener(this);
}

Instead of creating all of your fragments in your activity onCreate, have your viewPager create them when requested, so for a simple example:
in your implementation of A_PagerAdapter, override getCount() and getItem(int) to be something like:
public class A_PagerAdapter extends FragmentPagerAdapter {
...
private final static int NUM_PAGES = 6;
private final Fragment[] listFragment = new Fragment[NUM_PAGES];
...
public int getCount() {
return NUM_PAGES;
}
...
public Fragment getItem(int index) {
Fragment itemFragment = null;
if (listFragment[index] == null) {
// Hard-coded class factory.. yuck.
switch(index) {
case 0:
itemFragment = new Fg_1();
break;
case 1:
itemFragment = new Fg_2();
break;
case 2:
itemFragment = new Fg_3();
break;
case 3:
itemFragment = new Fg_4();
break;
case 4:
itemFragment = new Fg_5();
break;
case 5:
itemFragment = new Fg_6();
break;
}
// Save this instance in case it is asked for again later..
listFragment[index] = itemFragment;
} else {
// get the fragment we created earlier to avoid re-initializing
itemFragment = listFragment[index];
}
return itemFragment;
}
...
This is a fairly simple/horrible implementation.. in reality it sounds more like you need a caching/lazy loading strategy, possibly triggered in the onResume of the fragments in your view pager..

public class SampleFragmentPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {
final int PAGE_COUNT = 5;
private String tabTitles[] = new String[] { "Chats", "Groups", "Contacts","Profile" ,"Settings"};
public SampleFragmentPagerAdapter() {
super(getSupportFragmentManager());
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public Fragment getItem(int position) {
// return PageFragment.create(position + 1);
switch (position) {
case 0:
ChatScreenActivity chatScreenActivity = new ChatScreenActivity();
return chatScreenActivity;
case 1:
GroupChatActivity groupChatActivity = new GroupChatActivity();
return groupChatActivity;
case 2:
ContactsActivity contactsActivity = new ContactsActivity();
return contactsActivity;
case 3:
ProfileActivity profileActivity= new ProfileActivity();
return profileActivity;
case 4:
SettingActivity settingActivity = new SettingActivity();
return settingActivity;
default:
return null;
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}*use this code and do setadapter for your viewpager*
}

Related

Multiple Tabs with FragmentStatePageAdapter and ViewPager

Good Afternoon, I have an activity that contains 4 Fragments using tab layout, when I initialize the Activity only two fragments are initialized at a time, for example while I am in the first fragment, Fragment 1 and 2 are initialized, when I slide to 2 it initializes the third and then 2 and 3 are initialized and the first is destroyed, is it possible for everyone to be initialized together?
this is my Adapter:
public class TabManualAdapter extends FragmentStatePagerAdapter {
private String[] tituloTabsManual = {"TAB1","TAB2","TAB3","TAB4"};
public TabManualAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0 :
fragment = new Fragment1();
break;
case 1 :
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3:
fragment = new Fragment4();
break;
}
return fragment;
}
#Override
public int getCount() {
return tituloTabsManual.length;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return tituloTabsManual[position];
}
}
and Activity Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual);
SlidingTabLayout slidingTabLayout = findViewById(R.id.stl_tabs_manual);
viewPager = findViewById(R.id.vp_pagina_manual);
viewPager.setPageTransformer(true,new ZoomOutPageTransformer());
slidingTabLayout.setSelectedIndicatorColors(ContextCompat.getColor(this,R.color.colorPrimary));
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setBackgroundColor( ContextCompat.getColor( this, R.color.black ) );
TabManualAdapter tabManualAdapter = new TabManualAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabManualAdapter);
CircleIndicator indicator = findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
slidingTabLayout.setViewPager(viewPager);

Refresh fragment in ViewPager

I have ViewPager that has 3 tabs. Tab(3), beside stock fragment, includes 2 more fragments (B) --> (C).
Tab(1)
Tab(2)
Tab(3) --> (B) --> (C)
By pressing a button in (C) I want to refresh/recreate Tab(2).
What's the best way to do it? Thank you.
public class ViewPageAdapter extends FragmentStatePagerAdapter {
private static int NUM_ITEMS = 3;
private FragmentManager mFragmentManager;
private Context mContext;
public ViewPageAdapter(#NonNull FragmentManager fm, Context context) {
super(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mFragmentManager = fm;
mContext = context;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new FragmentInsta();
case 1: return new FragmentListUnlogged();
case 2: return new FragmentHostUnlogged();
default:
return new FragmentListLogged();
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
}
Thanks to user named "Andrew" I found the solution.
I override the onPause method in this way.
#Override
public void onResume() {
if(preferenceUtils.getBoolean("isLogged")){
FragmentTransaction trans = getChildFragmentManager().beginTransaction();
trans.replace(R.id.listUnlogged_container, new FragmentListLogged(), "ListUnlogged-ListLogged");
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(FRAGMENT_TAG);
trans.commit();
}
super.onResume();
}

How to hide fragment from activity - Android Studio

I have two fragment in one activity, and I need to know how to just hide the second fragment and leave the firs one
So, i want to hide PerfilDatosFragmen();, but i also need to keep "2" in return statement. how can i do that?
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
String[] encabezado = {"Tarjeta", "Datos"};
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new PerfilTarjetaFragment();
case 1:
return new PerfilDatosFragmen();
}
return null;
}
#Override
public int getCount() {
System.out.println(vacio);
// int vacio = getIntent().getExtras().getInt("AcompaƱante");
/* if(vacio.equals("1")){
a= 1;
}else{
a= 2;
}*/
return 2;
}
It's very simple. PagerAdapter.getCount() is defined the count of your fragments. You always return 2. The best solution is:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> fragments = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
fragments.add(new PerfilTarjetaFragment());
fragments.add(new PerfilDatosFragmen());
}
String[] encabezado = {"Tarjeta", "Datos"};
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}

How to refresh fragment in FragmentPagerAdapter

I Have 4 Fragments in 1 Activity. I need to make sure that on every fragment change the fragment is refreshed because I load JSON Data in every fragment. I use FragmentPager Adapter and RecyclerView to Show Data
This is my Adapter ( SickAdapter.java ) the code :
public class SickAdapter extends FragmentPagerAdapter{
private static final String TAG = SickAdapter.class.getSimpleName();
private static final int FRAGMENT_COUNT = 4;
public SickAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new SickFragmentToAll();
case 1:
return new SickFragmentToPending();
case 2:
return new SickFragmentToApproved();
case 3:
return new SickFragmentToDenied();
}
return null;
}
#Override
public int getCount() {
return FRAGMENT_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "All";
case 1:
return "Pending";
case 2:
return "Approved";
case 3:
return "Denied";
}
return null;
}
}
In my Class ( SickClass.java ) I create SickClass and I Call SickAdapter, I explode them, and this is my Code :
public class SickClass extends Fragment {
private static final String TAG = SickClass.class.getSimpleName();
private SickAdapter mAdapter;
private TabLayout tabLayout;
private ViewPager viewPager;
public SickClass() {
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.employee_leave_class, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
viewPager = (ViewPager)view.findViewById(R.id.view_pager);
if(mAdapter == null) {
mAdapter = new SickAdapter(getChildFragmentManager());
}
viewPager.setAdapter(new SickAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1, true);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
}
Try below code for reload your fragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(YOUR_FRAGMENT_NAME.this).attach(YOUR_FRAGMENT_NAME.this).commit();
You can use startActivityForResult() to get the result from the activity.
References:
ViewPager PagerAdapter not updating the View
How to refresh a Fragment of a FragmentPagerAdapter?

getting NullPointerException error view pager while fetching fragment method in view pager Activity

I know this is very general question but can't able to figure out what is wrong.
Fragment java class
// newInstance constructor for creating fragment with arguments
public static BpDetails newInstance(int page) {
BpDetails fragmentFirst = new BpDetails();
Bundle args = new Bundle();
args.putInt("someInt", page);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
}
public String getSystolic(){
return this.systolic.getText().toString();
}
/* public String getDiastolic(){
return this.diastolic.getText().toString();
}*/
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.bp_details, container, false);
Log.i("View ",view.toString());
Log.i("DOB is ",Long.toString(Constants.dob));
systolic =(EditText) view.findViewById(R.id.systolic);
diastolic =(EditText) view.findViewById(R.id.diastolic);
return view;
}
ViewPager Activity
vpPager = (ViewPager) findViewById(R.id.view_pager);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
findViewById(R.id.btn_prev).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(-1);
if (current!=0)
prevPage=current-1;
if (current < 4) {
// move to next screen
vpPager.setCurrentItem(current);
} else {
//final reached.
}
}
});
findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current!=0)
prevPage=current-1;
System.out.println("Prev page "+prevPage);
if (current < 4) {
// move to next screen
Fragment bpFragment=adapterViewPager.getItem(vpPager.getCurrentItem());
if (bpFragment instanceof BpDetails){
System.out.println("Current item is "+vpPager.getCurrentItem());
BpDetails fr = (BpDetails)adapterViewPager.getItem(vpPager.getCurrentItem());
**String systolicString = fr.getSystolic();** //error point
Log.i("Systolic is ",systolicString);
}
} else {
//final reached.
}
}
});
}
private int getItem(int i) {
return vpPager.getCurrentItem() + i;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 4;
private static int mSelectedPosition;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
//mSelectedPosition=selectedPosition;
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return BasicDetails.newInstance(0);
case 1:
return BpDetails.newInstance(1);
case 2:
return BslDetails.newInstance(2);
case 3:
return Summary.newInstance(3);
default:
return null;
}
}
}
Why I am getting the nullpointerException since I am accessing the public method of fragment before going to the next fragment.
Before down voting please leave the reason of down voting so that I can improve the question.
EDit:
I got to know since I am calling the getitem() method thats why all the variable of fragment to null that why I am getting the nullpointerException. Is there any way I solve this problem.
you should rewrite your ViewPagerAdapter and store the retuened fragment
this is because every time you call getItem() function you return a new fragment,but only invoked by the viewpager itself the fragment will invoke oncreateView ,so the second time you call getItem did not initialize the systolic and thus lead to NUllPointerException
for reference:
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 4;
private static int mSelectedPosition;
Map<Integer,Fragment> map= new HashMap<>();
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
//mSelectedPosition=selectedPosition;
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
Fragment f = map.get(position)
if(f!=null){
return f;
}
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
f = BasicDetails.newInstance(0);
case 1:
f = return BpDetails.newInstance(1);
case 2:
f = return BslDetails.newInstance(2);
case 3:
f = return Summary.newInstance(3);
default:
return null;
}
map.put(postion,f);
return f;
}
}

Categories

Resources