Java 将活动中的数据发送到internet中的片段

Java 将活动中的数据发送到internet中的片段,java,android,android-fragments,asynchronous,android-fragmentactivity,Java,Android,Android Fragments,Asynchronous,Android Fragmentactivity,我有一个类,它包含3个片段所有数据都需要从同一个URL收集。 我运行一个嵌套的异步类(在活动中)从URL获取数据,然后将该数据存储在每个片段的包中,如 Bundle bundle = new Bundle(); bundle.putString("edttext", json.toString()); InfoFragment fragobj = new InfoFragment(); fragobj.setArguments(bundle);

我有一个类,它包含3个
片段
所有数据都需要从同一个URL收集。 我运行一个嵌套的异步类(在活动中)从URL获取数据,然后将该数据存储在每个片段的包中,如

 Bundle bundle = new Bundle();
        bundle.putString("edttext", json.toString());
        InfoFragment fragobj = new InfoFragment();
        fragobj.setArguments(bundle);
在我调用片段本身中的异步类之前,一切正常,但现在又添加了两个片段,以减少URL请求的数量,我从Activity类调用异步类,并将数据分发到我的3片段类

问题:在异步设置捆绑包之前调用片段,并且 在片段中显示空束


在AsyncTask的onPostExecute()中获得响应后,可以从父活动广播意图

@Override
protected void onPostExecute(Object o) {
    super.onPostExecute(o);
    Intent intent = new Intent("key_to_identify_the_broadcast");
    Bundle bundle = new Bundle();
    bundle.putString("edttext", json.toString());
    intent.putExtra("bundle_key_for_intent", bundle);
    context.sendBroadcast(intent);
}
然后,您可以使用BroadcastReceiver类在片段中接收捆绑包

private final BroadcastReceiver mHandleMessageReceiver = new 
BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = 
            intent.getExtras().getBundle("bundle_key_for_intent");
            if(bundle!=null){
                String edttext = bundle.getString("edttext");
            }
            //you can call any of your methods for using this bundle for your use case
    }
};
在片段的onCreateView()中,需要首先注册广播接收器,否则不会触发此广播接收器

IntentFilter filter = new IntentFilter("key_to_identify_the_broadcast");
getActivity().getApplicationContext().
               registerReceiver(mHandleMessageReceiver, filter);
最后,您可以注销接收器以避免任何异常

@Override
public void onDestroy() {
    try {

         getActivity().getApplicationContext().
             unregisterReceiver(mHandleMessageReceiver);

    } catch (Exception e) {
        Log.e("UnRegister Error", "> " + e.getMessage());
    }
    super.onDestroy();
}

您可以在所有片段中创建单独的广播接收器,并使用相同的广播将数据广播到所有片段。您还可以对不同片段使用不同的键,然后对特定片段使用特定键进行广播。

需要更多代码才能找到problem@MuhammadMuzammil这个问题在概念上并不是以编程的方式出现的。您应该掌握好您的片段,为什么不在数据可用后就调用一个方法呢?PS:您可以通过
FragmentManager
@guness找到您的片段在加载第一个片段后,如何将数据从第一个片段膨胀到第二个片段?@phpdroid您仍然需要从活动中访问您的片段。您能帮我解决这个问题吗?