在Fragment和Activity之间创建comunication listener中的Android NullPointerException

时间:2015-04-16 16:02:00

标签: android

我想在Fragment和Activity之间创建简单的通信监听器,在Activity中定义监听器并实现了从Fragment我得到NullPointerException当我将String从Activity发送到Fragment时,我想从{{1发送数据}}

我的活动是:

onActivityResult

我为此行获得public class ActivityMain extends FragmentActivity { public IonGetBarcodeFromScannerListener ionGetBarcodeFromScannerListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); G.currentActivity = this; G.context = getBaseContext(); } public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanningResult != null) { String scanContent = scanningResult.getContents(); String scanFormat = scanningResult.getFormatName(); Log.e("barcode is: ", scanContent); doSendBarcode(scanContent); } else{ Log.e("No scan data received! ", ""); doSendBarcode(""); } } public void doSendBarcode(String barcode){ ionGetBarcodeFromScannerListener.getBarcode(barcode); } public void setBarcodeListener(IonGetBarcodeFromScannerListener l){ ionGetBarcodeFromScannerListener = l; } public interface IonGetBarcodeFromScannerListener { public void getBarcode(String barcode); } }

NullPointerException

我的片段:

ionGetBarcodeFromScannerListener.getBarcode(barcode);

2 个答案:

答案 0 :(得分:3)

我猜你正在以相反的方式尝试活动和片段通信,因为我认为接口将在片段中定义,它的实现将在活动中完成。有关详细信息,请参阅http://developer.android.com/training/basics/fragments/communicating.html

答案 1 :(得分:0)

似乎你永远不会打电话给setBarcodeListener()所以永远不会设置字段,因此null

- 更新 -

您可以使用onAttach()的返回值在片段的.getActivity()内调用它。