0

I have two fragments, lets call them Fragment A and Fragment B, which are a part of a NavigationDrawer (this is the activity they a bound to). In Fragment A I have a button. When this button is pressed, I would like another item added to the ListView in Fragment B.

What is the best way to do this? Use Intents, SavedPreferences, making something public(?) or something else?

EDIT 5: 20/7/13 This is with srains latest code

This is the NavigationDrawer that I use to start the fragments:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Navigation_Drawer extends FragmentActivity {

    public DrawerLayout mDrawerLayout; // Creates a DrawerLayout called_.
    public ListView mDrawerList;
    public ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mNoterActivities; // This creates a string array called _.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

// Just setting up the navigation drawer

    } // End of onCreate

// Removed the menu


        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) { 

        FragmentManager fragmentManager = getSupportFragmentManager();

        if (position == 0) {
            Fragment qnfragment = new QuickNoteFragment(); 
            ((FragmentBase) qnfragment).setContext(this);
            Bundle args = new Bundle(); // Creates a bundle called args
            args.putInt(QuickNoteFragment.ARG_nOTERACTIVITY_NUMBER, position); 

            qnfragment.setArguments(args);

            fragmentManager.beginTransaction()
                    .replace(R.id.content_frame, qnfragment).commit();



        } else if (position == 3) {
            Fragment pendViewPager = new PendViewPager(); // This is a ViewPager that includes HistoryFragment
            ((FragmentBase) pendViewPager).setContext(this);
            Bundle args = new Bundle();

            pendViewPager.setArguments(args);
            fragmentManager.beginTransaction()
                    .replace(R.id.content_frame, pendViewPager).commit();
        }

    // Update title etc
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) { // Used for the NavDrawer toggle
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) { // Used for the NavDrawer toggle
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

This is QuickNoteFragment:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class QuickNoteFragment extends FragmentBase implements OnClickListener {

    public static final String ARG_nOTERACTIVITY_NUMBER = "noter_activity";

    Button b_create;
// removed other defining stuff

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.quicknote, container, false);
        int i = getArguments().getInt(ARG_nOTERACTIVITY_NUMBER);
        String noter_activity = getResources().getStringArray(
                R.array.noter_array)[i];
        FragmentManager fm = getFragmentManager();
        setRetainInstance(true);

        b_create = (Button) rootView.findViewById(R.id.qn_b_create);

        // Removed other stuff

        getActivity().setTitle(noter_activity);
        return rootView;
    }

    @Override
    public void onClick(View v) {

        // TODO Auto-generated method stub

        switch (v.getId()) {

        case R.id.qn_b_create:

                              String data = "String data";
                DataModel.getInstance().addItem(data);

            break;
        }
    }

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection

        }
    }

    public interface OnItemAddedHandler { // Srains code
        public void onItemAdded(Object data);
    }
}

This is HistoryFragment (Remember it is part of a ViewPager):

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.RiThBo.noter.QuickNoteFragment.OnItemAddedHandler;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class HistoryFragment extends FragmentBase implements OnItemAddedHandler {

    ListView lv;
    List<Map<String, String>> planetsList = new ArrayList<Map<String, String>>();
    SimpleAdapter simpleAdpt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.history, container, false);
        initList();


        ListView lv = (ListView) view.findViewById(R.id.listView);
        simpleAdpt = new SimpleAdapter(getActivity(), planetsList,
                android.R.layout.simple_list_item_1, new String[] { "planet" },
                new int[] { android.R.id.text1 });

        lv.setAdapter(simpleAdpt);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parentAdapter, View view,
                    int position, long id) {

                // We know the View is a TextView so we can cast it

                TextView clickedView = (TextView) view;

                Toast.makeText(
                        getActivity(),
                        "Item with id [" + id + "]  - Position [" + position
                                + "] - Planet [" + clickedView.getText() + "]",
                        Toast.LENGTH_SHORT).show();
            }

        });
        registerForContextMenu(lv);

        return view;

    }

    private void initList() {

        // We populate the planets

        planetsList.add(createPlanet("planet", "Mercury"));
        planetsList.add(createPlanet("planet", "Venus"));
        planetsList.add(createPlanet("planet", "Mars"));
        planetsList.add(createPlanet("planet", "Jupiter"));
        planetsList.add(createPlanet("planet", "Saturn"));
        planetsList.add(createPlanet("planet", "Uranus"));
        planetsList.add(createPlanet("planet", "Neptune"));

    }

    private HashMap<String, String> createPlanet(String key, String name) {

        HashMap<String, String> planet = new HashMap<String, String>();

        planet.put(key, name);

        return planet;

    }

    // We want to create a context Menu when the user long click on an item

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,

    ContextMenuInfo menuInfo) {

        super.onCreateContextMenu(menu, v, menuInfo);

        AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;

        // We know that each row in the adapter is a Map

        HashMap map = (HashMap) simpleAdpt.getItem(aInfo.position);

        menu.setHeaderTitle("Options for " + map.get("planet"));
        menu.add(1, 1, 1, "Details");
        menu.add(1, 2, 2, "Delete");

    }
     @Override
      public void onItemAdded(Object data) {
          // to add item
          String string = String.valueOf(data);
          Toast.makeText(getContext(), "Data: " + string, Toast.LENGTH_SHORT).show();
          planetsList.add(createPlanet("planet", string));
      }
      @Override
    public void onStart() {
          super.onStart();

          DataModel.getInstance().setOnItemAddedHandler(this);
      }
}

This is FragmentBase:

   import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;

      public class FragmentBase extends Fragment {

            private FragmentActivity mActivity; // I changed it to FragmentActivity because Activity was not working, and my `NavDrawer` is a FragmentActivity.

            public void setContext(FragmentActivity activity) {
                mActivity = mActivity;
            }

            public FragmentActivity getContext() {
                return mActivity;
            }
    }

This is DataModel:

  import android.util.Log;
    import com.xxx.xxx.QuickNoteFragment.OnItemAddedHandler;

public class DataModel {

    private static DataModel instance;
    private static OnItemAddedHandler mOnItemAddHandler;

    public static DataModel getInstance() {
        if (null == instance) {
            instance = new DataModel();
        }
        return instance;
    }

    public void setOnItemAddedHandler(OnItemAddedHandler handler) {
        mOnItemAddHandler = handler;
    }

    public void addItem(Object data) {
        if (null != mOnItemAddHandler)
            mOnItemAddHandler.onItemAdded(data);
        else {
            Log.i("is context null?", "yes!");
        }  
    }
}

Thank you

  • Since fragments belonging to the same Activity come together, you can safely use static fields. Something like `FragmentB.adapter.add(x); FragmentBadapter.notifyDataSetChanges();` – Archie.bpgc Jul 19 '13 at 10:12
  • @Archie.bpgc Please could you expand a bit more - don't really understand –  Jul 19 '13 at 10:49
  • Just make the `ListView Adapter` of **FragmentB** `static` and use it like `FragmentB.adapter.add(new item);` in **FragmentA's** Button click. – Archie.bpgc Jul 19 '13 at 10:54

3 Answers3

1

I suggest you to use interface and MVC, that will make your code much more maintainable.

First you need an interface:

    public interface OnItemAddedHandler {
        public void onItemAdded(Object data);
    }

Then, you will need a data model:

    public class DataModel {

        private static DataModel instance;
        private static OnItemAddedHandler mOnItemAddHandler;

        public static DataModel getInstance() {
            if (null == instance) {
                instance = new DataModel();
            }
            return instance;
        }

        public void setOnItemAddedHandler(OnItemAddedHandler handler) {
            mOnItemAddHandler = handler;
        }

        public void addItem(Object data) {
            if (null != mOnItemAddHandler)
                mOnItemAddHandler.onItemAdded(data);
        }
    }

When you click the button, you can add data into the datamodel:

    Object data = null;
    DataModel.getInstance().addItem(data);

Then, the FragmentB implements the interface OnItemAddedHandler to add item

    public class FragmentB implements OnItemAddedHandler {

        @Override
        public void onItemAdded(Object data) {
            // to add item
        }
    }

also, When the FragmentB start, you should register itself to DataModel:

    public class FragmentB implements OnItemAddedHandler {

        @Override
        public void onItemAdded(Object data) {
            // to add item
        }

        @Override
        protected void onStart() {
            super.onStart();

            DataModel.getInstance().setOnItemAddedHandler(this);
        }
    }

You also can add DataModel.getInstance().setOnItemAddedHandler(this); to the onCreate method of FragmentB

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DataModel.getInstance().setOnItemAddedHandler(this);

    // do other things
}

update

you can send string simply:

    String data = "some string";
    DataModel.getInstance().addItem(data);

then on FragementB

    public class FragmentB implements OnItemAddedHandler {

        @Override
        public void onItemAdded(Object data) {
            // get what you send into method DataModel.getInstance().addItem(data);
            String string = String.valueOf(data);
        }
    }

update

OK. You have add DataModel.getInstance().setOnItemAddedHandler(this) in onCreateView method, so there is no need to add it in onStart() method. You can remove the whole onStart method.

onStart will be called on the fragment start, we do not need to call it in onCreateView. And on onItemAdded will be call when call the method DataModel.getInstance().addItem(data), we do not need to call it in onCreateView neither.

so, you can remove the code below from onCreateView method:

   DataModel.getInstance().setOnItemAddedHandler(this);
   // remove the methods below
   // onItemAdded(getView());
   // onStart();

You have another fragment where there is a button, you can add the codes below in the clickhandler function:

String data = "some string";
DataModel.getInstance().addItem(data);

update3

I think the HistoryFragment has been detached after you when to QuickNoteFragment You can add code to HistoryFragment to check:

@Override
public void onDetach() {
    super.onDetach();
    Log.i("test", String.format("onDetach! %s", getActivity() == null));
}

update4

I think HistoryFragment and QuickNoteFragment should has an parent class, named FragmentBase:

    public class FragmentBase extends Fragment {

        private Activity mActivity;

        public void setContext(Activity activity) {
            mActivity = mActivity;
        }

        public Activity getContext() {
            return mActivity;
        }
    }

HistoryFragment and QuickNoteFragment extends FragmentBase. Then when you switch between them, you can call setContext to set a Activity, like:

private void selectItem(int position) {

    FragmentManager fragmentManager = getSupportFragmentManager();

    if (position == 0) {
        Fragment qnfragment = new QuickNoteFragment();
        qnfragment.setContext(this);

        // ...

    } else if (position == 1) {
        Fragment pagerFragment = new RemViewPager();
        pagerFragment.setContext(this);

        // ...
    }
}

now, we can get a non-null activity in HistoryFragment by calling getContext, so we can change onItemAdded method to:

  @Override
  public void onItemAdded(Object data) {
      // to add item
      String string = String.valueOf(data);
      Toast.makeText(getContext(), "Data: " + string, Toast.LENGTH_SHORT).show();
      planetsList.add(createPlanet("planet", string));
  }

I hope this would work.

srain
  • 8,944
  • 6
  • 30
  • 42
  • Wow! Thank you very much for the comprehensive guide - I will try this too –  Jul 19 '13 at 10:59
  • 1
    OK, I have everything running without errors, but the object is not being added ( I'm tried a String and TextView) to the listview –  Jul 19 '13 at 11:22
  • add some log to onItemAdded method in FragmentB to show what the data is. – srain Jul 19 '13 at 11:37
  • That method is not being called anywhere in FragmentB –  Jul 19 '13 at 11:42
  • When I call onItemAdded when the data is a string, I get a FC on the button click –  Jul 19 '13 at 11:50
  • You can send FC to `DataModel.getInstance().addItem(FC)`, then the data pass from method `onItemAdded(Object data)` will also be FC – srain Jul 19 '13 at 12:09
  • Sorry I meant Force Close –  Jul 19 '13 at 12:35
  • I've got rid of the ForceClose, but I don't think I calling onItemAdded properly in my onCreateView. I am doing this: onItemAdded(getView()); –  Jul 19 '13 at 12:55
  • http://pastie.org/private/jk4rtpql5eckn9brhibww This is FragmentB - it is actually called HistoryFragment. The problem is that the string returns null. I know that i have not added the string to the listview yet, but I first wanted to get the string –  Jul 19 '13 at 13:02
  • I can not open the link. sure it is right? can you paste the code on you question? – srain Jul 19 '13 at 13:30
  • Done. I think the problem is me calling onItemAdded(getView()); in my oncreate. If I replace getView() with "hi", the Toast test says "hi" NOT what I set as the data in FragmentA –  Jul 19 '13 at 13:35
  • I updated the answer again, change your `fragmentB`, check still have any questions. – srain Jul 19 '13 at 13:47
  • 1
    OK. If there are still any questions, feel free to comment here. Do not forget to remove `onStart` method and do not call `onStart` in the `onCreateView` method. Good luck. – srain Jul 19 '13 at 13:49
  • Thank for sticking with me :-), but that still doesn't work for me :-(. The toast in onItemAdded() does not appear –  Jul 19 '13 at 13:52
  • where you call this `DataModel.getInstance().addItem(data);` ? – srain Jul 19 '13 at 13:54
  • where do you call this `DataModel.getInstance().addItem(data);` – srain Jul 19 '13 at 13:55
  • In my other fragment when the button is pressed. I will add the code of that fragment if necessary –  Jul 19 '13 at 13:57
  • Done. I removed quite a lot from Fragment A that was not necessary (I think :-)) –  Jul 19 '13 at 14:07
  • Your code seems pretty good. Wait for a moment. I am trying this code on my app. – srain Jul 19 '13 at 14:25
  • It works well on my app, does this code `case R.id.qn_b_create:` hitted? Can you add a breakpoint to the code, then debug it, follow the code, see where it will go. – srain Jul 19 '13 at 15:11
  • It always has before I added your code - I've been using it for ages. I will test again –  Jul 19 '13 at 15:11
  • Yes, the button creates a notification and that works fine. Howver, if go to HistoryFragment and then back to QuickNoteFragment I get a nullpointerexception and the app Force Closes –  Jul 19 '13 at 15:14
  • Do I need to move the DataModel bit to my activity rather than fragments? –  Jul 19 '13 at 15:20
  • you can see the exception info in logcat – srain Jul 19 '13 at 15:24
  • I added it to the question –  Jul 19 '13 at 15:27
  • From the exception stack trace, we can see `onItemAdded` has been called. But the method `getActivity()` return null, so the nullpointerexception trigger. How do you switch your fragments? When you go to `HistoryFragment `, is the `QuickNoteFragment` still alive? – srain Jul 19 '13 at 15:37
  • 1
    No, I don't think so. I am using the NavigationDrawer api and every time I click on a fragment, onCreateView is called for that fragment. –  Jul 19 '13 at 15:40
  • I think after you went to `HistoryFragment`, `getActivity()` may return null in `QuickNoteFragment`. Add `Log.i("test", getActivity() == null);` before `Toast.makeText(...` to see what will print out in logcat? – srain Jul 19 '13 at 15:57
  • Because it is true, it means that my QuickNoteFragment has been detached from the activity. Do you know a way around that, or to reattach it from HistoryFragment? –  Jul 19 '13 at 16:23
  • How do you change switch the fragments, would you paste the core code? – srain Jul 19 '13 at 16:27
  • I did some more logcats and got a nullpointerexception at this (which is in QuickNoteFragment): public void addItem(Object data) { if (null != mOnItemAddHandler) mOnItemAddHandler.onItemAdded(data); } –  Jul 19 '13 at 18:01
  • I haven't - I just read the logcat of the force close. But I think I found the issue! I tried to make a Toast in "public static class DataModel" But there was getActivity() for the context had an error because the class was STATIC. If I remove the "static" part, getActivity() is no longer null, so the code should work. However I get errors on "instance", "mOnItemHandler" and "getInstance()" because they are static. –  Jul 19 '13 at 18:09
  • Basically if I just copy and paste the code in your answer I get errors because there are static items in a non-static method. I did an "auto-fix" which changed the DataModel class to static but in doing so, getActivity() doesn't work. Is it possible to change your code to make it work? –  Jul 19 '13 at 18:14
  • that make some sense. you should change `public static class DataModel` to `public class DataModel`, you should put the code in a single file, instead of with `QuickNoteFragment` – srain Jul 19 '13 at 18:17
  • If I remove the static, I get errors on the other things like "instance" which have been made static. If I remove the static from them I get an error on getInstance() becasue that should apparently be static –  Jul 19 '13 at 18:21
  • only change `public static class DataModel` to `public class DataModel`, then put code to a sigle file: `DataModel.java`, do remove the other `static`. – srain Jul 19 '13 at 18:25
  • I think the issue if the `HistoryFragment` may have been detached. I updated the answer, you can add some codes to check. If that is true. I have the solution. – srain Jul 19 '13 at 18:27
  • Sorry - It's getting a bit late for me. I will try again tomorrow. Thank you for your help so far :-) –  Jul 19 '13 at 20:50
  • 1
    I `update` the answer and added **update4**. If it is convenient, you can put your code on github, I can fork you project and do some code to solve this issue. Your also can send your code to my email if you want. – srain Jul 20 '13 at 03:15
  • That still doesn't work. My NavigationDrawer class name is "Navigation_Drawer" and it extends FragmentActivity if that makes any difference... The problem is still the same. At public void addItem(Object data) { if (null != mOnItemAddHandler) mOnItemAddHandler.onItemAdded(data); else { Log.i("Is is happening", "Yes!"); // Therefore we know that something is still wrong } } I will upload my latest code. –  Jul 20 '13 at 08:33
  • OK: I have uploaded the new stuff with your UPDATE4. I think I still have the same problems although ther are no errors about the static stuff this time as DataModel is in its own "file" –  Jul 20 '13 at 09:07
  • Would this answer help? http://stackoverflow.com/a/5114361/2442638 I will try it –  Jul 20 '13 at 09:12
  • I saw your code, I looks like total the same with mine, still FC? – srain Jul 20 '13 at 09:16
  • I saw your code, It looks like total the same with mine, still FC? – srain Jul 20 '13 at 09:17
  • Yes. The way I got it was. Open app -> It automatically starts QuickNoteFragment. I press the button -> I open HistiryFragment (part of ViewPager) via the NavDrawer. I do NOT get the toast with the string data. -> I go back to QuickNoteFragment -> I press the Button -> Force Close every time I repeat this –  Jul 20 '13 at 09:20
  • Is that convenient for you to put your project to `github`? or send it to my email. There might be some other question which we didnot notice. – srain Jul 20 '13 at 09:23
  • yes, or you can make it small but make sure this issue can reproduce. – srain Jul 20 '13 at 09:26
  • OK - I will have a go –  Jul 20 '13 at 09:27
  • `liaohuqiu@gmail.com` – srain Jul 20 '13 at 09:28
  • I shall go for dinner with my friends. If you have posted the code to `github` or my email. please let me know. Have a good weekend. – srain Jul 20 '13 at 10:21
  • Thank you. I will try to post it on GitHub but it might take me a while. I started another question in the meantime and got this answer: http://stackoverflow.com/a/17761012/2442638 But I don't understand where I should call setContext(), as I have already done this (incorrectly?) in the NavigationDrawer –  Jul 20 '13 at 11:38
  • I have sent you an email from rithbo1111@gmail.com Thanks for helping –  Jul 20 '13 at 15:20
  • I found out the problem. The `HistoryFragment` has been detached. do you must `replace` the fragment? – srain Jul 21 '13 at 05:22
  • Great! Than you very much! –  Jul 21 '13 at 07:20
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/33876/discussion-between-srain-and-rithbo) – srain Jul 22 '13 at 01:40
1

Some good design principals:

  • An activity can know everything pubic about any Fragment it contains.
  • A Fragment should not know anything about the specific Activities that contain it.
  • A Fragment should NEVER know about other fragments that may or may not be contained in the Parent activity.

A suggested approach (informal design pattern) based on these principles.

Each fragment should declare an interface to be implemented by its parent activity:

public class MyFragment extends Fragment
{
   public interface Parent
   {
      void onMyFragmentSomeAction();
   }
   private Parent mParent;
   public onAttach(Activity activity)
   {
      mParent = (Parent) activity;
   }

   // This would actually be in a listener.  Simplifying to save typing.
   void onSomeButtonClick(View button)
   {
      mParent.onMyFragmentSomeAction();
   }
}

And the activity should implement the appropriate interfaces for all of its contained fragments.

public class MyActivity extends Activity 
                        implements MyFragment.Parent,
                                   YourFragment.Parent,
                                   HisFragment.Parent
{
   [usual Activity code]
   void onMyFragmentSomeAction()
   {
     if yourFragment is showing
     {
        yourFragment.reactToSomeAction();
     }
     if hisFragment is showing
     {
        hisFragment.observeThatSomeActionHappened();
     }
     [etc]
}

The broadcast approach is good, too, but it's pretty heavyweight and it requires the target Fragment to know what broadcasts will be sent by the source Fragment.

Dale Wilson
  • 9,166
  • 3
  • 34
  • 52
  • Thanks for the code and info :-), I will try this if I can't get srains code to work –  Jul 19 '13 at 16:11
0
  1. Use Broadcast. Send a boradcast from A, and B will receive and handle it.
  2. Add a public method to B, for example, public void addListItem(), which will add data to listview in B. Fragment A try to find the instance of Fragment B using FragmentMananger.findFragmentByTag() and invoke this method.
faylon
  • 7,360
  • 1
  • 30
  • 28
  • Which would you save is "better". The button will be pressed many times, will lots of broadcasts cause the battery to drain? –  Jul 19 '13 at 10:16
  • In FragmentA I have out FragmentManager fm = getFragmentManager(); fm.findFragmentByTag("FragmentB"); How do I call a public method from this. –  Jul 19 '13 at 10:41
  • Use FramgmentManager.findFragmentByTag(), and get a reference to Fragment B instance, write a public method addListItem() in Fragment B, and call it from A. – faylon Jul 19 '13 at 16:12