【问题标题】:On Android 2.3.5, NullPointerException when enableForegroundDispatch(...)在 Android 2.3.5 上,enableForegroundDispatch(...) 时出现 NullPointerException
【发布时间】:2013-06-14 09:01:54
【问题描述】:

我已经在我的 Activity 中实现了 NFC 前台调度。当我在 Android 4.2.1 设备(Samsung Galaxy Nexus)上运行时,代码运行良好。 但是当我在 Android 2.3.5 设备 (HTC Desire S) 上运行时,会出现 NullPointerException。这是我的 Activity 的一些代码,在onResume() 部分引发了异常:

public class MainActivity extends Activity{
   private NfcAdapter mAdapter; 
   private IntentFilter[] intentFilterArray;
   private PendingIntent pendingIntent;
   private String[][] techArray;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

      mAdapter = NfcAdapter.getDefaultAdapter(this);

      pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);

    intentFilterArray = new IntentFilter[]{intentFilter};
    techArray = new String[][]{new String[]{NdefFormatable.class.getName(), NfcA.class.getName()}};
   }

   @Override
   protected void onResume(){
    super.onResume();
      //NullPointerException here,because mAdapter is Null, why?    
    mAdapter.enableForegroundDispatch(this, pendingIntent, intentFilterArray, techArray);   
   }

   @Override
   public void onPause() {
     super.onPause();
     mAdapter.disableForegroundDispatch(this);
   }
   ...

}

Android 2.3.5 设备上,(LogCat 向我展示)NullPointerException 在调用 mAdapter.enableForegroundDispatch(…) 时发生在 onResume()。我查了一下,是因为mAdapternull。为什么?

【问题讨论】:

    标签: android android-layout android-intent android-activity nfc


    【解决方案1】:

    这是因为如果您的手机上没有 NFC,getDefaultAdapter 方法会返回 null,就像在 http://developer.android.com/reference/android/nfc/NfcAdapter.html#getDefaultAdapter(android.content.Context) 上解释的那样

    【讨论】:

      猜你喜欢
      • 2012-06-23
      • 1970-01-01
      • 2013-11-09
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      相关资源
      最近更新 更多