0

I've looked in other threads, and they all show how to do this on creation of the fragment, not asynchronously.

I had 3 activities, each of these activities did an asynchronous okhttp3.HttpUrl get in order to receive data from a third party JSON API. Then when complete, it would populate the activity with data.

I have since converted these 3 activities to fragments and put them in a parent activity. However, this means every time I load the new parent activity, it does THREE okhttp3.HttpUrl fetches to populate the 3 fragments.

All three fetches go to the same URL, so I was thinking to instead put the okhttp3.HttpUrl request in the parent activity and once its done, send the entire JSON package down to the fragments. This is after creation of the fragments... so I have no idea how to do this...

Any ideas?

My Parent Activity:

public class ChallongeEvent extends AppCompatActivity {
    private TextView tab_text;
    private String EVENT_ID, URL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_challonge_event);

        init();
    }

    private void init() {
        tab_text = (TextView) findViewById(R.id.tab_text);

        Intent intent = getIntent();
        EVENT_ID = intent.getStringExtra("event_id");

        if (Challonge.SUBDOMAIN.isEmpty()) {
            URL = "https://api.challonge.com/v1/tournaments/" + EVENT_ID + ".json";
        } else {
            URL = "https://api.challonge.com/v1/tournaments/" + Challonge.SUBDOMAIN + "-" + EVENT_ID + ".json";
        }

        String titles[] = new String[] { getString(R.string.players), getString(R.string.matches) };
        int numTabs = intent.getIntExtra("num_tabs", 1);

        EventAdapter adapter = new EventAdapter(getSupportFragmentManager(), titles, numTabs);
        ViewPager pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);
        pager.setCurrentItem(intent.getIntExtra("num_tabs", 1) - 1);

        SlidingTabLayout sliding_tabs = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
        sliding_tabs.setDistributeEvenly(true);
        sliding_tabs.setViewPager(pager);
    }

    private void populate() {
        AsyncGet fetch = new AsyncGet(new AsyncResponse() {
            @Override
            public void processFinish(String output) {
            }
        });

        HttpUrl.Builder urlBuilder = HttpUrl.parse(URL).newBuilder();
        urlBuilder.addQueryParameter("api_key", Challonge.API_KEY);
        urlBuilder.addQueryParameter("include_participants", "1");
        urlBuilder.addQueryParameter("include_matches", "1");
        fetch.execute(urlBuilder.build().toString());
    }

    public void setTabText(String text) {
        tab_text.setText(text);
    }
}

class EventAdapter extends FragmentPagerAdapter {
    private final String[] titles;
    private final int numTabs;

    public EventAdapter(FragmentManager fm, String mTitles[], int mNumTabs) {
        super(fm);

        this.titles = mTitles;
        this.numTabs = mNumTabs;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position)
        {
            case 1:
                return new ChallongeMatches();
            default:
                return new ChallongePlayers();
        }
    }

    @Override
    public String getPageTitle(int position) {
        return titles[position];
    }

    @Override
    public int getCount() {
        return numTabs;
    }
}
Jason Axelrod
  • 7,155
  • 10
  • 50
  • 78
  • I think, EventBus can help you here (to communicate between Activity and Fragments or, for example, between different fragments) - check it out: http://stackoverflow.com/questions/34199714/communicate-between-different-instances-of-same-fragment/34241668#34241668 – Konstantin Loginov Feb 01 '16 at 20:52

4 Answers4

2

Please try this code

Bundle bundle = new Bundle();
bundle.putString("key", "value");
// to send object use below code
// bundle.putSerializable("key", object);
Fragment fragment = new Fragment();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();

to get value use below code

String value= getIntent().getExtras().getString("value");

or

Object object = getIntent().getExtras().getSerializable("value");
Kadir altınok
  • 230
  • 2
  • 5
  • Can you explain this in more detail? Where do I put this code? I want the data sent to every fragment. I've updated my first post with my code from my parent activity. – Jason Axelrod Feb 01 '16 at 21:29
  • Where do I put these codes in respect to my code I posted above? I tried to put it in `processFinish`, but it cant resolve "container". – Jason Axelrod Feb 01 '16 at 21:37
  • Basically, in `processFinish` of my parent activity, I need to send the data to ALL the fragments... the fragments have already been created at this point as it's an AsyncTask, so creating a `new Fragment()` probably wouldnt work. – Jason Axelrod Feb 01 '16 at 21:41
1

You can also use a LocalBroadcastManager to send the data to all three fragments. Here's a tutorial on how to use this as well. The nice thing about this is that you can send the data, even if no one is listening, and easily add another receiver without having to change anything from the sender.

Pablo Baxter
  • 2,144
  • 1
  • 17
  • 36
0

make a method in each fragments :

public void setData(Bundle bundle){
//set you data to a local variable,
//and set it to the views on creation, 
//OR
//call this method on Post execute of your async task
}

then in the main activity:

YourFragment fragment = new YourFragment;
fragment.setData(bundle);
getSupportFragmentManager().replace(R.id.frame, fragment).commit;

OR call the fragment.setData(bundle) on the onPostExecute() of your async task

Muhammad Naderi
  • 3,090
  • 3
  • 24
  • 37
  • I'm confused on how this works... how do I put and get data from the bundle? – Jason Axelrod Feb 01 '16 at 21:11
  • Can you please explain in more detail? Where do I put the text in the main activity? How does it know which fragments to go to? – Jason Axelrod Feb 01 '16 at 21:18
  • For this to work, you should make your fragments extend a base fragment with such method, then cast the fragment to the base fragment in order to call the method. The code you propose will fail as the bare Fragment won't contain setData method. – rupps Feb 01 '16 at 21:41
  • Of course, it was kind of obvious that by `Fragment`, I meant user's custom fragment , i have edited it though – Muhammad Naderi Feb 02 '16 at 05:47
0

Solved it myself... in my AsyncFetch call I put:

    AsyncGet fetch = new AsyncGet(new AsyncResponse() {
        @Override
        public void processFinish(String output) {
            for (Fragment fragment : getSupportFragmentManager().getFragments())
            {
                if (fragment instanceof ChallongePlayers) {
                    ((ChallongePlayers) fragment).parsePlayers(output);
                } else if (fragment instanceof ChallongeMatches) {
                    ((ChallongeMatches) fragment).parseMatches(output);
                }
            }
        }
    });

This parses through all the possible fragments in the activity and sends the data to specific actions.

Jason Axelrod
  • 7,155
  • 10
  • 50
  • 78