将数据从 Activity 从互联网发送到 Fragment

Sending data from Activity to Fragment from internet

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

 Bundle bundle = new Bundle();
        bundle.putString("edttext", json.toString());
        InfoFragment fragobj = new InfoFragment();
        fragobj.setArguments(bundle);

在我调用片段本身的异步 Class 之前一切正常,但现在又添加了两个片段以减少 URL 请求的数量,我调用异步 class 来自 Activity class 并将数据分发到我的 3 片段 class.

Issue:Fragment is called before the bundle was set asynchronously and showing null bundle in fragment.

在 AsyncTask

的 onPostExeceute() 中获得响应后,您可以从父 activity 广播 Intent
@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 class

在片段中接收捆绑包
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();
}

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