【问题标题】:Sending data from Activity to Fragment from internet从互联网将数据从 Activity 发送到 Fragment
【发布时间】:2023-03-10 19:50:01
【问题描述】:

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

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

在我在 Fragment 本身中调用 Async 类之前一切正常,但现在又添加了两个 Fragment 以减少 URL 请求的数量,我从 Activity 类调用 Async 类并将数据分发到我的 3 Fragment 类。

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

【问题讨论】:

  • 需要更多代码才能找到问题
  • @MuhammadMuzammil 问题在概念上不是程序化的。
  • 您应该掌握自己的片段,为什么不在数据可用时对其调用方法? PS:你可以通过FragmentManager找到你的片段。
  • @guness 在加载第一个片段后将数据​​从第一个片段膨胀到休息两个怎么样?
  • @phpdroid 你仍然需要从你的活动中访问你的片段。

标签: java android android-fragments asynchronous android-fragmentactivity


【解决方案1】:

在 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 类在片段中接收捆绑包

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-09-27
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 2019-07-17
相关资源
最近更新 更多