将数据从Activity发送到Fragments

时间:2016-02-01 20:40:29

标签: android android-fragments

我查看了其他主题,他们都展示了如何在创建片段时这样做,而不是异步。

我有3个活动,每个活动都执行异步okhttp3.HttpUrl get,以便从第三方JSON API接收数据。然后,当完成时,它将使用数据填充活动。

我已经将这3个活动转换为片段并将它们放在父活动中。但是,这意味着每次加载新的父活动时,它都会执行三次okhttp3.HttpUrl提取以填充3个碎片。

所有三个提取都转到相同的URL,因此我想将okhttp3.HttpUrl请求放在父活动中,一旦完成,将整个JSON包发送到碎片。这是在片段创建之后...所以我不知道如何做到这一点......

有什么想法吗?

我的父母活动:

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

4 个答案:

答案 0 :(得分:2)

  

请尝试此代码

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

在代码

下获取价值
String value= getIntent().getExtras().getString("value");

Object object = getIntent().getExtras().getSerializable("value");

答案 1 :(得分:1)

您还可以使用LocalBroadcastManager将数据发送到所有三个片段。这里有关于如何使用它的tutorial。关于这一点的好处是你可以发送数据,即使没有人正在收听,也可以轻松地添加另一个接收者,而无需改变发送者的任何内容。

答案 2 :(得分:0)

在每个片段中制作一个方法:

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
}

然后在主要活动中:

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

OR 在异步任务的onPostExecute()上调用fragment.setData(bundle)

答案 3 :(得分:0)

我自己解决了...在我的AsyncFetch调用中,我把:

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

这将解析活动中的所有可能片段,并将数据发送到特定操作。