Marek Counts
Marek Counts

Reputation: 126

Communication with Fragments

I have a class that does not extend Activity (and can't because it extends CursorAdapter) The CursorAdapter needs to communicate back with the fragment that it populates, more specifically in each list item there is a button, whenever that button is clicked I need it to refresh the list and to do this I need to call getFragmentManager().

My Problem: because I am extending CursorAdapter I can't call getFragmentManager() (it must be called from a fragment or an activity.)

What I have tried. The first thing I thought to do (and it might be right and I just botched the implementation due to my lack of java skills) is to create a class that extends Activity that would interface with my fragment for the cursor adapter. CODE:

public class FragManager extends Activity {

   public FragManager() {
   }

    public void refreshList() {

        QCListFragment fragmentB = (QCListFragment) getFragmentManager().findFragmentById(R.id.listFragment);
        fragmentB.requeryList();
    }


}

this was called inside my cursor adapter like this. CODE:

FragManager fragment = new FragManager();
            fragment.refreshList();

Anyhow, I think this is the right line of thought but was unable to find tutorials (maybe because I did not know what words to use to search for it)

Any help would be wonderful! Marek

Upvotes: 0

Views: 220

Answers (2)

Jared Burrows
Jared Burrows

Reputation: 55527

You want to call requeryList() from that Activity?

First, I your Activity should extend FragmentActivity.

Here is how you call that method in all situations:

((QCListFragment) getSupportFragmentManager().findFragmentById(R.id.listFragment)).requeryList();

Call method from Fragment in a Fragment:

((QCListFragment) getFragmentManager().findFragmentById(R.id.listFragment)).requeryList();

Call method from FragmentActivity in a Fragment:

((QCLisActivity) getActivity()).requeryList();

Upvotes: 0

j__m
j__m

Reputation: 9625

I don't know your code structure right now, but if any of your classes are nested, you can access the containing class, like so:

public class MyActivity extends Activity {

    private MyAdapter adapter = new MyAdapter();

    public class MyAdapter extends CursorAdapter {

        public MyAdapter() {
            FragmentManager fm = MyActivity.this.getFragmentManager();
        }
    }
}

If nesting is not in use, then you can pass an instance of a class directly to the class that needs to access it.

public class MyActivity extends Activity {

    private MyAdapter adapter = new MyAdapter(this);
}

public class MyAdapter extends CursorAdapter {

    public MyAdapter(Activity activity, Cursor c, int flags) {
        super(activity, c, flags);
        FragmentManager fm = activity.getFragmentManager();
    }
}

Upvotes: 1

Related Questions