如何将数据从 AsyncTask 发送到 Fragment

How to send data from AsyncTask to Fragment

如何将数据从 activity 传递到片段。它有据可查,但不幸的是没有解决方案适合我。

我想将数据从主 activity 内的内部 AsyncTask class 发送到另一个片段。

最受欢迎的答案是使用 Bundle,所以我尝试了以下方法:

异步任务:

Bundle bundle = new Bundle();
bundle.putString("test", "From AsyncTask");

MyFragmentClass fragobj = new MyFragmentClass();
fragobj.setArguments(bundle);

片段:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

rootView = inflater.inflate(R.layout.fragment_one, container, false);

String value = getArguments().getString("test");
Log.i("valueTest", value);

return rootView;

}

字符串没有传递给片段,因为我收到以下内容:

"java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference"

如有任何帮助,我将不胜感激。

在你的 onCreateView 中试试这个

Bundle b = getActivity().getIntent().getExtras();
    if(b != null) {
        String test = b.getString("test");
    }

这也有助于解决空指针错误

当然你不能获取 bundle ,因为创建片段并从 AsyncTask 获取是异步的)。所以当 asyncTask 完成时你可以使用 BroadCastReceiver 来接收数据; 片段:

 @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.layout_demo, container, false);
    //to register br
    initBroadCastReceiver();
    return view;
}

private void initBroadCastReceiver() {
    manager = LocalBroadcastManager.getInstance(getContext());
    MyBroadCastReceiver receiver = new MyBroadCastReceiver();
    IntentFilter filter = new IntentFilter();
    //whatever
    filter.addAction("com.action.test");
    manager.registerReceiver(receiver,filter);
}

class MyBroadCastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        //e.g
        String key = intent.getStringExtra("key");
    }
}

asyncTask->onPostExcute()

Intent intent = new Intent("com.action.test");
    intent.putExtra("key","123");
    manager.sendBroadcast(intent);