2012-02-03 38 views
0

最近我一直在玩意圖和捆綁。我認爲我讓他們想通了,但是我在意圖之間傳遞數據時總是遇到問題我明白你必須使用bundle,但是當我嘗試實現一個簡單的程序來測試這個時,我總是得到一個空指針異常。我所做的程序只是一個調用服務來創建字符串的活動,然後該活動應該能夠獲取服務創建的字符串並將其烘烤。有沒有人知道我在這裏做錯了什麼,爲任何能夠幫助的人歡呼。這裏是低於傳遞意向數據

Activity類

MyIntent = new Intent(this, GetLocation.class); 
startService(MyIntent); 

bundle = MyIntent.getExtras(); 
test = bundle.getString("location"); 
Context context = getApplicationContext(); 
CharSequence text = test; 
int duration = Toast.LENGTH_LONG; 

Toast toast = Toast.makeText(context, text, duration); 
toast.show(); 

服務類

Intent Int1 =new Intent(this,MapMock.class); 
    Bundle b = new Bundle(); 
    String yeah = new String(); 
    yeah = "hello"; 
    b.putString("location", yeah); 
    Int1.putExtras(b); 
+0

目前還不清楚上述代碼運行的方式和時間以及發生錯誤的位置。 – Kuffs 2012-02-03 12:14:50

+0

http://geekswithblogs.net/bosuch/archive/2011/01/17/android---passing-data-between-activities.aspx – 2012-02-03 12:17:44

+0

檢查此示例.. – 2012-02-03 12:17:56

回答

2

服務不這樣工作。

您通過startService發送給服務的意圖不會更新並返回到啓動服務的活動。

我認爲你需要一個綁定服務。 閱讀here瞭解更多信息。這使您可以調用函數並將值傳遞迴活動。

+0

謝謝mcnicholls我沒有意識到邊界服務這只是我需要的東西,以及再次感謝 – 2012-02-03 12:57:18

0

看起來你正在訪問一個你沒有投入意圖意圖日期,

一樣,如果你的代碼正在從您的服務開始活動,並通過一些數據使用:

Intent myIntent=getIntent(); 
bundle = MyIntent.getExtras(); 
test = bundle.getString("location"); 
Context context = getApplicationContext(); 
CharSequence text = test; 
int duration = Toast.LENGTH_LONG; 

Toast toast = Toast.makeText(context, text, duration); 
toast.show();