View pager different results - java

I am using view pager with 3 tabs in MainActivity of my app to show grid images. I have one MovieFragment for all 3 tabs and I am using FragmentsPagerAdapter to create new instance of MovieFragment everytime tab is changed.
//FragmentsPagerAdapter method
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return MoviesFragment.newInstance(buildUrl(Utility.POPULAR_URL));
case 1: return MoviesFragment.newInstance(buildUrl(Utility.RATED_URL));
case 2: return MoviesFragment.newInstance("favorite");
default: return null;
}
}
//Fragment method
public static MoviesFragment newInstance(String uri){
MoviesFragment fragment = new MoviesFragment();
Bundle bundle = new Bundle();
bundle.putString("fragment", uri);
fragment.setArguments(bundle);
return fragment;
}
Now I was getting different results in my app so I debugged this method and I found it calls methods before tab is selected i.e when I open app it creates instances for case 0 and case 1 and when I go to second tab it creates instance for case 2.
Now in my second tab when I make changes to database and try to get them in third tab changes are not reflected as it already created instance of third tab when second tab was selected.
How do I solve this problem?

#Sahil This is because in android ViewPager keeps track of previous and next pages only. So when you initialize the viewPager it automatically create first 2 page and call MoviesFragment for 1st two tab. And once you start scrolling through, it starts keeping the track of only previous and next page.
Read this

Related

Fragment Pager Adapter only displaying last fragment created

I have a similar problem to the one described here: ViewPager only displaying last fragment, but after attempting the solution there I'm still having the same issue.
I have an app with a TabLayout, which displays 3 fragments. The 3 fragments have the same layout, but the content (text, etc...) of said layouts change depending on the position in the TabLayout. Tab 1 displays one thing, tab 2 another, etc. I do this by passing one class or another to the fragment to be displayed depending on the position passed to getItem() in the pager adapter.
What I'm seeing is that no matter what fragments I attempt to load, my tab layout will always display 3 instances of the same fragment, in this case the last one that gets instantiated. I've stepped through the code and sure enough 3 different fragments get instantiated and returned in getItem() the 3 times its called, but only the one that is returned last is set onto the TabLayout, 3 times.
How can I get it to display the 3 distinct fragments, and not the same one 3 times?
Code used:
#Override
public Fragment getItem(int position) {
MyFragment fragment = new MyFragment();
if (position == 0) {
fragment = MyFragment.newInstance(MyClass1, position); // this gets returned first
} else if (position == 1){
fragment = MyFragment.newInstance(MyClass2, position); // this gets returned second
} else if (position == 2){
fragment = MyFragment.newInstance(MyClass3, position); // this gets returned third and is the only fragment displayed in the 3 tabs
}
return fragment;
}
I believe the issue must be somewhere there, but tell me if I need to share/change other parts of code
EDIT: This is my newInstance() function in my fragment class
public static MarkStudentFragment newInstance(MyClass inputClass, int inputPosition) {
MyFragment fragment = new MyFragment();
dataClass = inputClass;
position = inputPosition;
return fragment;
}
dataClass then gets used to set up the layout of the fragment, etc
public static MarkStudentFragment newInstance(MyClass inputClass, int inputPosition) {
MyFragment fragment = new MyFragment();
dataClass = inputClass;
position = inputPosition
return fragment;
}
If this actually compiles, it is because you have declared dataClass and position as static. So, each time you call newInstance(), you overwrite the previous dataClass and position values. And each of your fragments will use the one-and-only value of dataClass and position.
To fix this, get rid of the dataClass and position fields, and use the arguments Bundle. Note that you will need to switch from passing an instance of MyClass to passing some identifier that will allow the fragment to get the proper data (e.g., an enum).
We have a method in fragment called getUsetVisibleHint().. by using this when the fragment is visible we can call the api or fetch details and attach to layout..
you can put code like this
public Fragment getItem(int i)
{
switch (i)
{
case 0:
Fragment fragment1=new Fragment();
return fragment1;
case 1:
Fragment fragment2=new Fragment();
return fragment2;
case 2:
Fragment fragment3=new Fragment();
return fragment3;
default:
return null;
}
}

Fragment in Viewpager only refreshing when it's open from fragments next to it

So basically i have 4 fragments I'm currently working on second. I have some weird situation here. When app started it open fragment on position 1 then if I navigate to fragment 2 via tabs on top fragment 2 will update, then if I open fragment 3 from fragment 2 and return to fragment 2 from fragment 3 it will also update. But if I choose to open fragment 4 and then return to fragment 2 it won't refresh. This is method that I'm calling to refresh fragment
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
loadEvents();
}
Log.d("TAG", "VISIBLE");
}
in LoadEvents there are few recyclerview setting their adapters. Nothing speciall
I think it is because when you call fragment 3 and when you return to the fragment 2 you use .replace , instead when you go to the fragment 4 you use .add and to return to the fragment 2 .show.
looks at the differences between:
add
replace
show
https://developer.android.com/reference/android/app/FragmentTransaction.html

Android layout getting wrapped when keyboard appears

In my application I have two tabs, for which I am using ViewPager, two fragments are within this view pager. Sometimes when I tap on first tabs fragments EditBox keyboard pops, once I am done with the input keyboard disappears. But layout below keyboard region goes blank (White), this is happening sometimes, specially second launch of application. When application is launched from studio for first time issue doesn't appear. But when I launch it through system application by tapping on its ic_launhcher issue comes again. What are the possible causes of issue ?
The layout on launch looks like :
After I click on edit box & edit some text in address filed, when keyboard disappears, layout looks like :
I am using view pager inside another fragment & using FragmentStatePagerAdapter by passing a getChildFragmentManager()
private void setupViewPager(ViewPager viewPager) {
FragmentStatePagerAdapter fragmentStatePagerAdapter = new FragmentStatePagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new GeneralInfoFragment();
Bundle bundle = new Bundle();
bundle.putString(context.getString(R.string.all_data), new Gson().toJson(profileResponse));
fragment.setArguments(bundle);
break;
case 1:
fragment = new ICEFragment();
break;
default:
return null;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "General Info";
case 1:
return "ICE";
}
return "";
}
};
Note : Images are erased to protect privacy
Edit:
Put this code in your manifest file in your activity tag
android:configChanges="keyboard|keyboardHidden|orientation|
screenLayout|uiMode|screenSize|smallestScreenSize"
android:windowSoftInputMode="stateHidden|adjustPan"
Or
Try this one
setContentView(R.layout.activity_direction_3);
getWindow().getDecorView().setBackgroundColor(
android.R.color.transparent);
Or
if you have are using a custom theme then add this in your theme
<item name="android:windowBackground">Transparent color </item>
Tel me if you still get the issue.

java.lang.NullPointerException: (Fragment)

I'm trying to create a Navigation Menu + Tabs, the code for this is fine.
Now I've implemented some code I had as an Activity in a Fragment in order to add it to the Tabs viewer.
When I run the code the app works just fine..
Until I swipe right to the other Tab and then the App crashed and I get this from the logcat:
java.lang.NullPointerException: Attempt to write to field 'android.support.v4.app.FragmentManagerImpl android.support.v4.app.Fragment.mFragmentManager' on a null object reference
I'm leaving you my Main Activity, 'cause I think there's the issue, if you think you might need some Fragments like the Tabs, please just ask!
CODE: http://pastebin.com/TTcJMR77
You have to add default case on your switch in getItem(int position) method:
default:
return new Fragment();
Instead of
return null;
Like this:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new YourFragment();
default:
return new Fragment();
}
}

How pass fragment arguments while using a view pager with different fragments/layouts?

Objective: To use fragment arguments to pass along the string value from a TextView to a new fragments TextView, BUT while using a ViewPager with different layouts/fragments in the FragmentPagerAdapter.
Problem: The new fragment never receives the fragments arguments from the previous fragment.
My Set up: I have my Activity hosting the ViewPager and FragmentPagerAdapter. I have overridden FragmentPagerAdapters getItem(int position) method to create a new fragment instance depending on the current position of the ViewPager. Right now I only have two Fragments in my adapter, but will be adding more after getting over this obstacle. I am using the newInstance() technique to pass along the Fragment's arguments, but nothing is ever passed.
Pertinent Code:
My FragmentPagerAdapter code:
//this is a variable that I pass in as the newInstanct() methods parameter,
// I update this variable from my fragments constantly
public static String fragmentArgumentsValue = "";
mViewPager.setAdapter(new FragmentPagerAdapter(fm) {
#Override
public int getCount() {
return NUMBER_OF_VIEWS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Log.d(TAG, "---In getPosition(), position 0---");
return Frag1
.newInstance(fragmentArgumentsValue);
case 1:
Log.d(TAG, "---In getPosition(), position 1---");
return frag2
.newInstance(fragmentArgumentsValue);
default:
Log.d(TAG, "---In getPosition(), DEFAULT---");
return frag1
.newInstance(fragmentArgumentsValue);
}
}
});
One of the fragments newInstance() method:
public static Fragment newInstance(String fragmentArgumentsValue) {
Frag1 f = new Frag1();
Bundle bun = new Bundle();
bun.putString(KEY_FRAGMENT_ARGUMENTS_STRING, fragmentArgumentsValue);
f.setArguments(bun);
return f;
}
Getting the fragments arguments:
String argString = getArguments().getString(
KEY_FRAGMENT_ARGUMENTS_STRING);
if (argString.length() != 0) {
Log.d(TAG, "Trying to set the frag args to:" + argString);
mWorkingTextView.setText("" + argString);
} else {
Log.d(TAG, "Couldn't set frag args to: " + argString);
}
What I've Tried: I've tried giving the Activity that hosts the ViewPager and FragmentPagerAdapter a static variable that I constantly update in each one of my fragments, I include the static variable in the fragment.newInstance(staticVariableInActivity) method, but this doesn't seem to work.
I've also tried using the ViewPager callback viewPager.setOnPageChangeListener() I had overridden the onPageSelected(int pos) and tried to pass the fragment arguments there, nevertheless it didn't work... so please help me S.O.!!!
My thoughts: I do not have the different fragments and layouts in an ArrayList or any list for that matter, I just instantiate the Fragments via the newInstance() method depending on the positions of the FragementPagerAdapter, could this be a problem? Should I create a singleton list of the layouts/fragments? So I can change the values of the Fragments TextViews via the singleton list? (excuse me if that's a dumb or not possible thing to do).
Note: I am am saving away the TextViews values via public void onSaveInstanceState(Bundle outState) to handle screen rotations. Could this be a problem?
Alright so I this link will help in the communication between fragments: Communication with other Fragments .
You need to define a interface that the Activity will implement and the fragments will use to send data onward to the activity, and the activity will then find the fragment by tag doing something like this:
frag = (Fragment2) getSupportFragmentManager()
.findFragmentByTag(
"android:switcher:" + R.id.viewPager + ":2");
and then update the fragment by calling a public method implemented within the fragment.
The link provided will help greatly, it is from the Android Development website.
Adds the bundle inside your Adapter.
example in the constructor of the adapter :
public ViewPagerAdapter(Context context, FragmentManager fm) {
super(fm);
fragments.add(TileFragments.newInstance());
Bundle bundleFeatures = new Bundle();
bundleFeatures.putString(ContentName.FEATURES.toString(),ContentName.FEATURES.toString());
fragments.get(0).setArguments(bundleFeatures);
}

Categories