7

I know there are many topics about this here. I have also read documentation many times but I can't find the best way to pass data from activity to fragment.

I want to be able to show the results of my Searchable activity in two differents layouts (list and map) using swipe Views with tabs. I have to pass 2 data to the fragments: "currentLocation" which is the current user location and "result" which is a list of objects.

I have omited some parts of my code to make it more understandable.

SearchableActivity.java

public class SearchableActivity extends ActionBarActivity implements TabListener {

    List<PlaceModel> result = new ArrayList<PlaceModel>();
    private SearchView mSearchView;
    private String currentLocation;

    AppSectionsPagerAdapter mAppSectionsPagerAdapter;
        ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_searchable);

    final ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    actionBar.addTab(actionBar.newTab().setText("List").setTabListener(this));
    actionBar.addTab(actionBar.newTab().setText("Map").setTabListener(this));

    // get currentLocation here

    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    handleIntent(intent);
}

private void handleIntent(Intent intent) {

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {

        final String query = intent.getStringExtra(SearchManager.QUERY);

        // get result here
    }
}

@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

}

PlaceListFragment.java

public class PlaceListFragment extends Fragment {
    ListView listViewData;
    PlaceAdapter placeAdapter;
    List<PlaceModel> result = new ArrayList<PlaceModel>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_list, container, false);
        Bundle args = getArguments();
        listViewData = (ListView) rootView.findViewById(android.R.id.list);
        // I will pass result and currentLocation here
        placeAdapter = new PlaceAdapter(getActivity(), R.layout.fragment_list_item, result, currentLocation);
        listViewData.setAdapter(placeAdapter);
        return rootView;
    }
}

AppSectionsPagerAdapter.java

public class AppSectionsPagerAdapter extends FragmentPagerAdapter {

final int PAGE_COUNT = 2;

public AppSectionsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int arg0) {
    Bundle data = new Bundle();
    switch(arg0) {
        case 0:
            PlaceListFragment fragment1 = new PlaceListFragment();
            fragment1.setArguments(data);
            return fragment1;
        default:
            PlaceListFragment fragment2 = new PlaceListFragment();
            fragment2.setArguments(data);
            return fragment2;
    }
}

@Override
public int getCount() {
    return PAGE_COUNT;
}
}
tsil
  • 2,069
  • 7
  • 29
  • 43
  • I had the same problem i found my solution from here http://stackoverflow.com/questions/20673956/custom-array-adapter-in-fragment/20673965?noredirect=1#comment30957952_20673965 http://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android – rupesh Dec 19 '13 at 06:57

5 Answers5

7

Find fragment in Activity onCreate and set data to a method you write in your fragment:

        ExampleFragment rf =  (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.exampleFragment);

    if(rf!=null){
    rf.setExample(currentExample);
    }

"CurrentExample" is whatever you want to send in to your "setExample" method in your fragment.

public void setExample(ExampleObject currentExample){

    currentExampleInFragment = currentExample;

}

You can use the data in onActivityCreated method of Fragment.

Not sure is this is a good solution or not, but I found it the easiest one for passing objects.

Karl
  • 332
  • 2
  • 10
6

Usually the activities will have a reference to their fragments. In your SearchableActivity.java are you also loading PlaceListFragment.java either in setContentView(activity_searchable.xml); or you need to create a instance of the fragment and add/replace a fragment using FragmentTransaction.

you can find a good example here on how to communicated between fragments or between activity & fragment.

Training link

Garg
  • 2,731
  • 2
  • 36
  • 47
prijupaul
  • 2,076
  • 2
  • 15
  • 17
  • activity_searchable.xml contains ViewPager only. I create another layout (fragment_list.xml and fragment_list_item.xml) for PlaceListFragment. – tsil Sep 22 '13 at 23:37
  • 1
    From your code, What i understand is you are not populating the fragments to the mAppSectionsPagerAdapter. Once you have added the PageListFragment you would get a reference of it from getItem. No need to create a new instance of PAgeListFragment. Check this example on how it works. http://thepseudocoder.wordpress.com/2011/10/13/android-tabs-viewpager-swipe-able-tabs-ftw/ – prijupaul Sep 22 '13 at 23:58
  • Pls update your latest code. Did you add the fragment instance to your viewpager adapter? This is also a good example to take a look. http://developer.android.com/reference/android/support/v4/view/ViewPager.html – prijupaul Sep 23 '13 at 00:49
  • I'm now able to pass data to my fragments. But I have noticed it's possible only via FragmentPagerAdapter. Like this in getItem method Bundle data = new Bundle(); data.putString("my_key", "test"); But it doesn't solve my problem. I search a way to pass objects from Activity to the FragmentPagerAdapter. – tsil Sep 23 '13 at 16:40
5
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

see detail answer here..

Community
  • 1
  • 1
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
1

"send data from Activity to Fragment"

Activity:

        Bundle bundle = new Bundle();
        bundle.putString("message", "Alo Stackoverflow!");
        FragmentClass fragInfo = new FragmentClass();
        fragInfo.setArguments(bundle);
        transaction.replace(R.id.fragment_single, fragInfo);
        transaction.commit();

Fragment:

Reading the value in the fragment

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle bundle = this.getArguments();
        String myValue = bundle.getString("message");
        ...
        ...
        ...
        }

or

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        String myValue = this.getArguments().getString("message");
        ...
        ...
        ...
        }
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
  • Can you please have a look at my issue.. http://stackoverflow.com/questions/30303488/how-to-update-fragments-data-used-in-viewpager-view-is-not-showing-the-updated – Arun Badole May 20 '15 at 11:07
  • @Jorgesys Is there a benefit to using "transaction.replace(R.id.fragment_single, fragInfo); transaction.commit();" on the fragment you show in the Activity? I have just been using "fragment.show(getSupportFragmentManager(), "fragmentname");" – AJW Jan 08 '21 at 17:48
1

Create one Session model class and in Activity set the values you want to data needs to be send then in Fragment you can get that values from Session model class

eg. from your activity u can set like this.

 AllEventDetails.getInstance().setEvent_description(event_Description);
AllEventDetails.getInstance().setDj_name(dj_name);
AllEventDetails.getInstance().setMusic_theme(music_theme);
AllEventDetails.getInstance().setClub_name(club_name);
AllEventDetails.getInstance().setDate(event_date);
AllEventDetails.getInstance().setBanner_image_path(banner_image_path);
AllEventDetails.getInstance().setEvent_title(event_title);  

and from your Fragment u can retrive like this.

AllEventDetails.getInstance().getClub_name()
.........

Creating Session model class is like this.

public class AllEventDetails {
    private static AllEventDetails mySession ;
    private String event_description;
    private String dj_name;
    private String music_theme;
    private String club_name;
    private String date;
    private String banner_image_path;
    private String event_title;

    private AllEventDetails() {     
        event_description = null;
        dj_name = null;
        music_theme = null;
        club_name = null;
        date = null;
        banner_image_path = null;
        event_title = null;

    }

    public static AllEventDetails getInstance() {
        if( mySession == null ) {
            mySession = new AllEventDetails() ;
        }
        return mySession ;
    }

    public void resetSession() {
        mySession=null;
    }
    public String getEvent_description() {
        return event_description;
    }
    public void setEvent_description(String event_description) {
        this.event_description = event_description;
    }
    public String getDj_name() {
        return dj_name;
    }
    public void setDj_name(String dj_name) {
        this.dj_name = dj_name;
    }
    public String getMusic_theme() {
        return music_theme;
    }
    public void setMusic_theme(String music_theme) {
        this.music_theme = music_theme;
    }
    public String getClub_name() {
        return club_name;
    }
    public void setClub_name(String club_name) {
        this.club_name = club_name;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getBanner_image_path() {
        return banner_image_path;
    }
    public void setBanner_image_path(String banner_image_path) {
        this.banner_image_path = banner_image_path;
    }
    public String getEvent_title() {
        return event_title;
    }
    public void setEvent_title(String event_title) {
        this.event_title = event_title;
    }

}
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
Prasad P
  • 1,042
  • 8
  • 5