FragmentPagerAdapter didn't work with BaseActitvty - android

I got a simple FragmentPageAdapter in my Activity and it works fine. Now I would like to extend from a BaseActivity because I implemented a navigation drawer inside of the BaseActivity. Therefore I cannot extend of the FragmentActivity Class and I tried to declare a FragmentActivity object but I always get the error java.lang.IllegalStateException: Activity has been destroyed. How can I handle this problem?
public class MainActivity extends BaseActivity {
FragmentPagerAdapter adapterViewPager;
FragmentActivity fa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentActivity fa = new FragmentActivity();
adapterViewPager = new MyPagerAdapter(fa.getSupportFragmentManager());
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(adapterViewPager);
pager.setAdapter(new MyPagerAdapter(fa.getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: // Fragment # 0 - This will show FirstFragment
return SlideFragment.newInstance(0, "Page # 1");
case 1: // Fragment # 0 - This will show FirstFragment different title
return SlideFragment.newInstance(1, "Page # 2");
case 2: // Fragment # 1 - This will show SecondFragment
return SlideFragment.newInstance(2, "Page # 3");
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
}
#Override
protected int getLayoutResourceId() {
// TODO Auto-generated method stub
return R.layout.activity_main;
}
}

You don't need to use a FragmentActivity object in MainActivity. Just extend FragmentActivity in your BaseActivity class.

Never create manually activity objects. You are always inside some activity class(properly instantiated).
What you need is your BaseActivity to extends FragmentActivity.

Related

getSupportFragmentManager() cannot resolve method

Below is my main Activity class:
public class MainActivity extends Activity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//GETTING THE ERROR HERE
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Master mView = new Master();
return mView;
case 1:
Device dView = new Device();
return dView;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Master";
case 1:
return "Device";
}
return null;
}
}
}
I am getting an error at the line saying mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); saying that cannot resolve method getSupportFragmentManager.
I changed the base class of MainActivity from Activity to FragmentActivity since getSupportFragmentManager is a method of FragmentActivity but is that Ok if I don't have a class that doesn't extend the Activity class? I am new to Android and not sure if it's ok to do that?
but is that Ok if I don't have a class that doesn't the main Activity class?
FragmentActivity extends Activity. Hence, you are extending the main Activity class, just indirectly.
Your class must extend AppCompatActivity instead of Activity to access getSupportFragmentManager() .

Send data from Activity to fragment with ViewPager

I have got aplication with three screens(3 fragments and viewPager), and now I want to send for example String from Activity to FragmentA but I don't know how.
This is my Activity class with pager Adapter
public class MainActivity extends FragmentActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager= (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
}
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment=null;
if(arg0==0){
fragment=new FragmentA();
}
if(arg0==1){
fragment=new FragmentB();
}
if(arg0==2){
fragment=new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
You can use the EventBus library or write something similar yourself, but the best option is to learn the correct and accepted methods of communication between components.
If you want to pass the data (String in your case) before the ViewPager initialized you can pass it via argumnents, here you can find a good example.

Reload or refresh list fragment when swiped or when tab is selected?

i am unable to reload/refresh Listfragment (CfFragment(),PfFragment(),IfFragment() in my below code) when tab is selected or swiped, can any one tell me where i am going wrong.My code is working well when it is created for the first time but it doesn't reload/refresh when swiped or selected.If i change anything in the 1st listfragment it should affect in the 2nd list fragment and so on...
Please can any one help me out.it would be much appreciated.
Thank you.
public class busy extends FragmentActivity implements
ActionBar.TabListener {
SessionManager session;
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
static ServiceURL URL;
static AlertDialogManager alert = new AlertDialogManager();
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.busy);
session = new SessionManager(getApplicationContext());
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(mAppSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
//mViewPager.setAdapter(mAppSectionsPagerAdapter);
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new CfFragment();
case 1:
return new PfFragment();
case 2:
return new IfFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Confy";
case 1:
return "Peny";
case 2:
return "Incy";
default:
break;
}
return null;
}
}
}
Derive your AppSectionsPagerAdapter class as
public static class AppSectionsPagerAdapter extends FragmentStatePagerAdapter
instead of
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter
Basically, FragmentPagerAdapter keeps the created Fragments in memory, while FragmentStatePagerAdapter destroys and creates them anew as they are shifted in and out of view.
Two more things:
1. Make sure you are not calling setRetainInstance(true) in any of your Fragments, else they won't be recreated.
2. Add
viewPager.setOffscreenPageLimit(0);
to your code.
EDIT:
Instead of
Activity -> ViewPager -> Fragments
create the structure as
Activity -> Fragment -> ViewPager -> Nested Fragments
This will ensure that each Fragment is refreshed on tab change. See this post for the implementation.

How to handle AsyncTask's in ActionBarActivity Fragments when ViewPager is used?

I'm using ActionBarActivity to create 5 tabs. I have used ViewPager to swipe between the 5 tabs using SectionsPagerAdapter which extends FragmentPagerAdapter. Each tab has a fragment with an asynctask called in oncreateview method. When I'm in one fragment, asynctask in other fragment is being called.
I tried using toast messages in oncreateview method is each fragment instead of asynctask. But wrong toast messages are being fired in wrong fragment.
Oncreate method code:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager_exp);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
actionBar.setSelectedNavigationItem(position);
actionBar.setTitle(getHomePageTitle(position));
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
{
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setIcon(getPagedrawable(i))
.setTabListener(this));
}
// Adapter class code:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
Fragment1 f1 = new Fragment1();
return f1;
case 1:
Fragment2 f2 = new Fragment2();
return f2;
case 2:
Fragment3 f3 = new Fragment3();
return f3;
case 3:
Fragment4 f4 = new Fragment4();
return f4;
case 4:
Fragment5 f5 = new Fragment5();
return f5;
}
return null;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
Fragemnt class code :
public class F1 extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.f1,container, false);
Toast.makeText(getActivity(), "F1", Toast.LENGTH_SHORT).show();
return view;
}
}
The FragmentPagerAdapter keeps additional fragments, besides the one shown, in resumed state. The solution is to implement a custom OnPageChangeListener and create a new method for when the fragment is shown.
1) Create LifecycleManager Interface
The interface will have two methods and each ViewPager’s Fragment will implement it. These methods Are as follows:
public interface FragmentLifecycle {
public void onPauseFragment();
public void onResumeFragment();
}
2) Let each Fragment implement the interface
Add iplements statement for each class declaration:
public class FragmentBlue extends Fragment implements FragmentLifecycle
public class FragmentGreen extends Fragment implements FragmentLifecycle
public class FragmentPink extends Fragment implements FragmentLifecycle
3) Implement interface methods in each fragment
In order to check that it really works as expected, I will just log the method call and show Toast:
#Override
public void onPauseFragment() {
Log.i(TAG, "onPauseFragment()");
Toast.makeText(getActivity(), "onPauseFragment():" + TAG, Toast.LENGTH_SHORT).show();
}
#Override
public void onResumeFragment() {
Log.i(TAG, "onResumeFragment()");
Toast.makeText(getActivity(), "onResumeFragment():" + TAG, Toast.LENGTH_SHORT).show();
}
4) Call interface methods on ViewPager page change
You can set OnPageChangeListener on ViewPager and get callback each time when ViewPager shows another page:
pager.setOnPageChangeListener(pageChangeListener);
5) Implement OnPageChangeListener to call your custom Lifecycle methods
Listener knows the new position and can call the interface method on new Fragment with the help of PagerAdapter. I can here call onResumeFragment() for new fragment and onPauseFragment() on the current one.
I need to store also the current fragment’s position (initially the current position is equal to 0), since I don’t know whether the user scrolled from left to right or from right to left. See what I mean in code:
private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
int currentPosition = 0;
#Override
public void onPageSelected(int newPosition) {
FragmentLifecycle fragmentToShow = (FragmentLifecycle)pageAdapter.getItem(newPosition);
fragmentToShow.onResumeFragment();
FragmentLifecycle fragmentToHide = (FragmentLifecycle)pageAdapter.getItem(currentPosition);
fragmentToHide.onPauseFragment();
currentPosition = newPosition;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
};
I didn't write the code. Full tutorial here: http://looksok.wordpress.com/2013/11/02/viewpager-with-detailed-fragment-lifecycle-onresumefragment-including-source-code/
Use this
viewPager.setOffscreenPageLimit(1); // the number of pages you want to load in background
and also a ProgressDialogue.
ViewPager creates views for fragments adjacent to your current page. This also gives you an opportunity to load any data required for the adjacent fragments. If you are using AsyncTasks to load data, using this feature will result in a better user experience. But if you need an event when a particular page is opened by the viewpager, LordRaydenMK's solution will work.
See my post on the following thread for using AsyncTasks in a ViewPager:
AsyncTask runs on each page of the ViewPager
Hi You can try by using tag of each fragment and call method of each fragment on Page Changed
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
actionBar.setTitle(getHomePageTitle(position));
Fragment f = getFragrmentManager().findFragmentByTag(
"" + position);
if (f != null)
f.refresh();
}
});
and on
#Override
public Fragment getItem(int position) {
Fragment f=null;
switch (position)
{
case 0:
f = new Fragment1();
break;
case 1:
f = new Fragment2();
break;
case 2:
f = new Fragment3();
break;
case 3:
f = new Fragment4();
break;
case 4:
f = new Fragment5();
break;
}
f.setTag(""+position);
return f;
}

ViewPager along with FragmentList in Fragment Activity

This is my 1st question so i will try to b as precise as possible. I am trying the create an application using Fragment Activity, Fragment List and View Pager. When the activity loads by default the fragment list should be shown to the left and view pager is shown to the right (the detail view). When i click one of the fragment list buttons i want to load a webview in the detail view (right side).
I have implemented the Fragment Activity with Fragment List. Now how to add View Pager to this so that it shows up when the application loads up ..
public class MainActivity extends FragmentActivity implements McDonaldsListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
McDonaldsFragment countries
=(McDonaldsFragment)getSupportFragmentManager()
.findFragmentById(R.id.countries);
countries.setCountryListener(this);
Fragment f=getSupportFragmentManager().findFragmentById(R.id.details);
countries.enablePersistentSelection();
}
#Override
public void onCountrySelected(McDonalds c) {
String url=getString(c.url);
((DetailsFragment)getSupportFragmentManager()
.findFragmentById(R.id.details))
.loadUrl(url);
}
}
There are other supporting classes which if there is need i will post it.
Hope some one can suggest me some solutions.
Edit:
This is what i tried to implement but dosent work....Gives Instantiation Exception :(
public class ViewPagerExample extends android.support.v4.app.FragmentActivity implements McDonaldsListener {
private MyAdapter mAdapter;
private ViewPager mPager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
McDonaldsFragment mc
=(McDonaldsFragment)getSupportFragmentManager()
.findFragmentById(R.id.countries);
mc.setCountryListener(this);
Fragment f=getSupportFragmentManager().findFragmentById(R.id.details);
mc.enablePersistentSelection();
}
public void onCountrySelected(McDonalds c) {
String url=getString(c.url);
((DetailsFragment)getSupportFragmentManager()
.findFragmentById(R.id.details))
.loadUrl(url);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new DetailFragment();
case 1:
return new ImageFragment(R.drawable.ic_launcher);
case 2:
return new ImageFragment(R.drawable.ic_launcher);
default:
return null;
}
}
}
}
lets try this peter kuterna view pager
http://blog.peterkuterna.net/2011/09/viewpager-meets-swipey-tabs.html

Categories

Resources