如何将数据从AsyncTask发送到Fragment

时间:2016-07-07 12:17:12

标签: android android-fragments android-asynctask android-bundle

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

我想将主活动中内部AsyncTask类的数据发送到另一个片段。

最流行的答案是使用Bundle,所以我尝试了以下内容:

的AsyncTask:

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:尝试调用虚方法' java.lang.String android.os.Bundle.getString(java.lang.String)'在null对象引用"

我将不胜感激任何帮助。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

在onCreateView

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

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