2017-01-02 47 views
1

我已經看到了幾個有關此問題,但我找不到與我自己的問題有關的問題。在意圖活動之間傳遞int []數組時發生NULL

我想通過意圖傳遞服務和其他活動之間的幾個整數數組。我也傳遞了其他不是數組的int值。收到時我所有的數組都是「空」,我不明白爲什麼

遞送服務:

Intent intent = new Intent(UPDATE_ALL); 
intent.putExtra(RAW_CELLS, rawCells); 
intent.putExtra(RAW_CELLVL, rawCellsLevel); 
intent.putExtra(RAW_CELASU, rawCellsAsuLevel); 
intent.putExtra(RAW_CELDBM, rawCellsDbm); 

捕撈活動:

Log.d("MainActivity", "intent.getExtras()="+intent.getExtras()); 
int rawCellsTotal = intent.getIntExtra(SensorService.RAW_CELLS, 0); 
int[] rawCelLvl = intent.getExtras().getIntArray(SensorService.RAW_CELLVL); 
int[] rawCelAsu = intent.getExtras().getIntArray(SensorService.RAW_CELASU); 
int[] rawCelDbm = intent.getExtras().getIntArray(SensorService.RAW_CELDBM); 

從Log.d線,我可以看到這在logcat中:

Bundle[{com.myapp.MyService.RAW_CELASL=[29, 7], com.myapp.MyService.RAW_CELDBM=[-111, -133], com.myapp.MyService.RAW_CELLVL=[2, 1], com.myapp.MyService.RAW_CELLS=2}] 

然後,當我調試的代碼,我可以在rawCellsT值總數這不是一個數組,而是一個簡單的整數(例如2),但我總是有'空'在rawCelLvl,rawCelAsu,rawCelDbm它們應該是logcat中顯示的具有2個值的整數數組。

任何提示解決此問題?

編輯:

我試圖改變我的代碼在服務如下:

Intent intent = new Intent(UPDATE_ALL); 
    Bundle extras = new Bundle(); 
    extras.putIntegerArrayList(RAW_CELLVL, rawCellsLevel); 
    intent.putExtras(extras); 

,並保持在追趕活動相同的代碼,但還是同樣的結果。你能否以正確的方式幫助我使用Bundle?

回答

1

你的問題就在這裏:

intent.getExtras()getIntArray() - >嘗試檢索從演員束的陣列。

您不添加額外套件。你必須使用:

intent.getByteArrayExtra() - >從意圖演員

0

檢查數組,你想細胞streight正確初始化。

int[] ints = new int[SIZE]; 

int[] ints = new int[]{1, 2, 3}; 

NPE意味着沒有數組

1

我建議你把DATAS成束,然後把束引入意圖,因爲包創建的,是容器數據的。您可以更輕鬆地管理它們。

在你的情況下,你從空的包中得到getIntArray(SensorService.RAW_CELLVL);

P.S:當你調用方法getExtras()時,你會得到一個Bundle obj。

+0

我添加了一些我在問題中嘗試過的更改,你能幫我準備正確的Bundle語法嗎? – ceyquem

+0

當然,如果你想把一個數據放入一個Bundle,你可以使用:'bundle.putString(「VarName」,strYouWantToPass)'如果它是一個字符串,bundle.putInt(「VarName1」,5)如果它是整數。 要從Bundle獲取數據,可以使用get方法, Like: String str = bundle.getString(「varName」), int number = bundle.getInt(「VarName1」)。 –

1

使用getIntArrayExtra(字符串名稱)

int[] rawCelLvl = intent.getIntArrayExtra(SensorService.RAW_CELLVL); 
int[] rawCelAsu = intent.getIntArrayExtra(SensorService.RAW_CELASU); 
int[] rawCelDbm = intent.getIntArrayExtra(SensorService.RAW_CELDBM); 
+0

非常感謝,我今天上午解決了這個問題,與您的提議非常相似,但是使用ArrayList ceyquem

0

如果您正在使用自定義類,那麼你必須序列化類。即使用Serializable類的實現類。如果這樣做,你可以通過只

intent.putExtra(); 

從意圖傳遞數組或者你可以設置數組類並把類的對象

,你還可以創建靜態類,並設置類與數據,以便您可以直接接收數據而無需傳遞該類的對象。

0

這是我如何解決這個問題:

intent.putExtra(RAW_CELLVL, rawCellsAsuLevel); 
intent.putExtra(RAW_CELASU, rawCellsAsuLevel); 
intent.putExtra(RAW_CELDBM, rawCellsDbm); 
在接收活動

ArrayList<Integer> rawCelLvl = intent.getIntegerArrayListExtra(SensorService.RAW_CELLVL); 
ArrayList<Integer> rawCelAsu = intent.getIntegerArrayListExtra(SensorService.RAW_CELASU); 
ArrayList<Integer> rawCelDbm = intent.getIntegerArrayListExtra(SensorService.RAW_CELDBM); 

感謝所有的答覆,對捆綁的線索和事實,即「其他」 < >「額外」讓我走上正軌!