Savita
Savita

Reputation: 747

Calling Fragment Method in Activity

I want to call Fragment Method in my MainActivity. The Fragment is attached to ViewPager in my MainActivity

I have called the method in my MainActivity

mViewPager = (ViewPager) findViewById(R.id.pager);
        setupViewPager(mViewPager);

 private void setupViewPager(ViewPager mViewPager) {
        mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        mSectionsPagerAdapter.addFragment(new FeedsFragment(), "Around You");
        mSectionsPagerAdapter.addFragment(new InboxFragment(), "Shares");
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }      

 @Override
    public void onLocationChanged(Location location) {
       currentLocation = location;
        if (lastLocation != null
                && geoPointFromLocation(location)
                .distanceInKilometersTo(geoPointFromLocation(lastLocation)) < 0.01) {
            // If the location hasn't changed by more than 10 meters, ignore it.
            return;
        }
        lastLocation = location;
        if (!hasSetUpInitialLocation) {
            // Zoom to the current location.
            hasSetUpInitialLocation = true;
        }
                FeedsFragment fragment = (FeedsFragment) getSupportFragmentManager().findFragmentById(R.id.feeds_fragment);
        if(fragment != null) {
            fragment.doFeedsQuery();
        }

    }

This my SectionsPagerAdapter

    protected Context mContext;
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public SectionsPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.

        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);
    }

}

This is the method I am calling from my Fragment

   public void doFeedsQuery() {
           Location myLoc = (MainActivity.currentLocation == null) ? MainActivity.lastLocation : MainActivity.currentLocation;
        // If location info is available, load the data
         if (myLoc != null) {
        // Refreshes the list view with new data based
        // usually on updated location data.
            feedsQueryAdapter.loadObjects();
         }
    }

This is the resource id I am calling the fragment with

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:id="@+id/feeds_fragment"
    android:background="@color/white">

Here is my LogCat

java.lang.NullPointerException: Attempt to invoke virtual method 'void io.wyntr.peepster.Fragments.FeedsFragment.doFeedsQuery()' on a null object reference
                                                       at io.wyntr.peepster.Activities.MainActivity.onLocationChanged(MainActivity.java:687)
                                                       at com.google.android.gms.location.internal.zzk$zzb.handleMessage(Unknown Source)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:168)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5845)
                                                       at java.lang.reflect.Method.invoke(Native Method)

I don't know where I have gone wrong.

Upvotes: 0

Views: 3461

Answers (3)

Zar E Ahmer
Zar E Ahmer

Reputation: 34380

Two solutions for your problem. create Instance of your fragment as class Member and the other already told by Hiren Dabhi.

private FeedsFragment feedFragment;//Use as class instance.

private void setupViewPager(ViewPager mViewPager) {
        mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        mSectionsPagerAdapter.addFragment(feedFragment, "Around You");
        mSectionsPagerAdapter.addFragment(new InboxFragment(), "Shares");
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }  

and simply check it's not null and isVisibleToUser then call your method

if(feedFragment != null && feedFragment.isVisible())
  feedFragment.doFeedsQuery();

Upvotes: 0

Hiren Dabhi
Hiren Dabhi

Reputation: 3713

Please use below code get fragment object of FeedsFragment fragment.

    int size = mSectionsPagerAdapter.getCount();
    for (int i = 0; i < size; i++) {
        Fragment fragment = mSectionsPagerAdapter.getItem(i);
        if (fragment != null && fragment instanceof FeedsFragment) {
            ((FeedsFragment)fragment).doFeedsQuery();
        }
    }

Upvotes: 1

vinitius
vinitius

Reputation: 3274

Your problem seems to be here:

   FeedsFragment fragment = (FeedsFragment) getSupportFragmentManager().findFragmentById(R.id.feeds_fragment);

findFragmentById() will try to find the id specified in XML and you don't have one since you're using a dynamic approach. What you should use instead is findFragmentByTag like this:

 FeedsFragment fragment = (FeedsFragment) getSupportFragmentManager().findFragmentByTag("Around You");

Upvotes: 0

Related Questions