I store information if user is logged in SharedPreferences.
In my ViewPager adapter I want to check if userIsLoggedIn. Depending on that I will display different fragments.
My question is: in order to get data from sharedPreferences I need a context. How do I get it from my ViewPager adapter class?
Thank you.
public class ViewPageAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
private FragmentManager mFragmentManager;
public ViewPageAdapter(#NonNull FragmentManager fm) {
super(fm);
mFragmentManager = fm;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new FragmentInsta();
case 1: return new FragmentList();
case 2: return new FragmentHostUnlogged();
default:
return new FragmentList();
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public int getItemPosition(#NonNull Object object) {
if (object instanceof FragmentHostUnlogged)
return POSITION_NONE;
return POSITION_UNCHANGED;
}
}
You should use FragmentStatePagerAdapter . FragmentPagerAdapter is deprecated.
class ViewPageAdapter extends FragmentStatePagerAdapter {
Context context;
ViewPagerAdapter(FragmentManager manager,Context c) {
super(manager,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
context=c;
}
Read Context from official guideline.
Interface to global information about an application environment. This
is an abstract class whose implementation is provided by the Android
system.
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), getApplicationContext());
Related
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();
}
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();
}
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?
I have an Activity that contains a Fragment with a ViewPager. Then I call a method of a Fragment within the ViewPager. But if that Fragment then calls getParentFragment(), it returns null.
Why is getParentFragment() null?
The main Fragment that contains a ViewPager:
public class MyFragment extends Fragment {
private TabLayout mTabLayout;
private ViewPager mViewPager;
private ViewPagerAdapter mAdapter;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
// Setup the ViewPager
mViewPager = (ViewPager) view.findViewById(R.id.container);
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager(), getActivity());
mViewPager.setAdapter(adapter);
//setupViewPager(mViewPager);
// Setup the TabLayout
mTabLayout = (TabLayout) view.findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
// This method is called from Activity.
public void callNestedFragment() {
if (isDetached()) {
return;
}
// This fragment cannot be null, because it doesn't crash here. (this is just a sample).
((Fragment0) mViewPager.getItem(0)).testMethod();
}
}
The nested Fragment (inside mViewPager):
public class Fragment0 extends Fragment {
...
public void testMethod() {
if (isDetached()) {
return;
}
// Why is getParentFragment() null? This is the log: "Parent fragment: null"
Log.i(TAG, "Parent fragment: " + getParentFragment());
return;
}
}
The ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
public ViewPagerAdapter(FragmentManager manager, Context context) {
super(manager);
mContext = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment0();
case 1:
return new Fragment1();
case 2:
return new Fragment2();
case 3:
return new Fragment3();
case 4:
return new Fragment4();
}
return null;
}
#Override
public int getCount() {
return 5;
}
}
If more code is needed, please let me know. Thanks for your help.
In my case , I was using FragmentManager instead of ChildFragmentManager which was causing this issue.
I found the answer. If isDetached() is true, it doesn't mean getParentFragment() is not null.
So instead of the previous check in testMethod(), this is the new code:
public void testMethod() {
if (isDetached() && getParentFragment() != null) {
return;
}
...
}
I also now call the same method again in the onStart() method within Fragment0, where getParentFragment() should not be null.
I try to create dynamic ViewPager content output. I complete this with hardcoded data, but can't with variable.
First I create activity and get data from previous activity and resources.
public class result extends FragmentActivity {
private MyAdapter mAdapter;
private ViewPager mPager;
int[] uan;
String [] categoryQuest;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
mAdapter = new MyAdapter (getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
Resources testCat = getResources();
categoryQuest = testCat.getStringArray(R.array.category);
Bundle bndResult = this.getIntent().getExtras();
uan = bndResult.getIntArray("strDef");
}
Secondary, I try to get uan array data and put it into fragment.
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter (FragmentManager fm) {
super (fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new detail(R.string.A1, uan[0]);
case 1:
return new detail(R.string.B1, uan[1]);
default:
return null;
}
}
Explain me, how to get access to UAN array from public void onCreate from public static class MyAdapter.
Create a method on your adapter and pass the data into it:
private int[] mUan;
public void setUan(int[] uan) {
mUan = uan;
}
Then change getItem to use mUan and populate the data in your activity's onCreate.