2013-01-17 16 views
0

考慮這種情況:我製作了兩個Android應用程序,例如A & B. B掃描一個NFC標籤,存儲一個字符串「nfcservice」,並將該字符串存儲在一個字節數組中,比如說TEMP_MSG。之後,我將該數組轉換爲String並將其發送給App-A。在App-A中,我嘗試去匹配它,但每次都失敗。問題是什麼?你能提出一些建議嗎?意圖內發送的字符串不匹配?

的App-B碼:

//nfcservice 
byte[] TEMP_MSG = {(byte)0x6E, (byte)0x66, (byte)0x63, (byte)0x73, (byte)0x65, 
        (byte)0x72, (byte)0x76, (byte)0x69, (byte)0x63, (byte)0x65}; 

String nfcservicestring = new String(TEMP_MSG); 
Intent intent = new Intent("com.android.apps.metromanager.MetroManagerActivity"); 
intent.putExtra("keyword", nfcservicestring); 
startActivity(intent); 

應用-A代碼:

public class MetroManagerActivity extends Activity 
{ 
    TextView myText; 
    String myString;  
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_metro_manager); 
     Bundle bundle = getIntent().getExtras(); 
     if(bundle!=null) { 
      myString = bundle.getString("keyword"); 
      Toast.makeText(getApplicationContext(), myString, Toast.LENGTH_LONG).show(); 
      if(myString.equals("nfcservice")) { 
       LinearLayout lView = new LinearLayout(this); 
       myText = new TextView(this); 
       myText.setText("Welcome"); 
       lView.addView(myText); 
       setContentView(lView); 
      } else { 
       LinearLayout lView = new LinearLayout(this); 
       myText = new TextView(this); 
       myText.setText("Bye Bye"); 
       lView.addView(myText); 
       setContentView(lView); 
      } 
     } 
    } 
} 
+0

您是否嘗試過在應用程序A和B的意圖中記錄字符串以查看實際上有什麼不同? –

+0

nfcservice是String的名稱而不是它的值。 –

回答

0

你字節初始化有故障,在第5個字節您有:

, byte)0x65, 

相反的:

,(byte)0x65, 

但是,爲什麼不嘗試從捆綁對象中獲取其他屬性,並通過調試和觀察來檢查它們?

+0

感謝您的意見...我解決了問題... –

0

我不知道這是你的打字錯誤,但字節數組表達是錯誤的:

byte[] TEMP_MSG = { (byte)0x,(byte)0x6E, ...}; 

有一個在第一個表達式(字節)0X的一個錯誤,

Appart酒店,如果你不能得到包裏面的字符串,你將不得不在代碼中的NPE:

if(myString.equals("nfcservice")) 
{ 
... 
} 

這是更好地檢查平等這樣的:

if ("nfcservice".equals(myString)) { 

} 
+0

請詳細說明爲什麼檢查像你所建議的平等更好 –

+0

如果myString爲null,myString.equals(「nfcservice」)拋出一個NullPointerException,導致myString爲null。但是如果你在一個字符串對象「nfcservice」(「nfcservice」,一個存在的字符串)上調用equals方法,你不會有NPE,只是比較返回false,因爲nfcservice!= null。 –