2012-04-15 53 views
4

我正在爲Android創建基於GPS的應用程序,並且有2個活動Main和LocNames。 Main顯示我的地圖,LocNames是獲取用戶想要的源和目的地。當用戶從菜單中選擇它時,我想啓動LocNames,用戶在框中輸入名稱,並且希望結果被髮送回Main。但我這樣做的例外。Android:使用意圖來回傳遞數據setResults

這裏是我的主要是如何調用LocNames:

public boolean onOptionsItemSelected(MenuItem item) 
{ 
    switch (item.getItemId()) 
    { 
     case R.id.showMyLocation: 
      showCurrentLocation(); 
      break; 
     case R.id.showRoute: 
      Intent getLocationsIntent = new Intent(Main.this, LocNames.class); 
      startActivityForResult(getLocationsIntent, 1); 
      break; 
    } 

下面是我想設置導致的onClick LocNames的:

public void onClick(View v) 
{ 
    // TODO Auto-generated method stub 
    source = sourceText.getText().toString(); 
    destination = destinationText.getText().toString();  
    Intent result = new Intent(LocNames.this, Main.class); 
    result.putExtra("src", source); 
    result.putExtra("dest", destination); 
    setResult(RESULT_OK, result); 
} 

但是當我嘗試使用結果我的應用程序崩潰通過LocNames

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
if(requestCode == 1 && resultCode == RESULT_OK) 
    { 
     source = data.getStringExtra("src"); 
     destination = data.getStringExtra("destination");   
    } 
} 

我有沒有現成的經驗,使用setResults但確實返回cumentation說它需要一個int和一個intent作爲參數,所以我創建了這個意圖,但是我在LocNames的OnClick中得到了NullPointerException。

Regards

回答

7

您不需要特定組件的意圖。你只需要一個空的意圖。因此,與

Intent intent = new Intent(); 
+0

謝謝您的回覆更換

Intent result = new Intent(LocNames.this, Main.class); 

。但是,我將如何捕獲結果變量源和目的地。我在OnClick中設置了正確的方式嗎? – Yogesh 2012-04-15 00:41:52

+0

正如我可以看到你從'EditText'中捕獲它們......你是什麼意思?試試吧。你的代碼看起來沒問題,所以它應該可以工作(除了你在'onCreate'中創建'Intent'的行,如答案中所述) – 207 2012-04-15 00:51:53

+0

謝謝。發現這個bug,我應該使用這個語法來獲取返回值:source = data.getExtras()。getString(「src」); \t \t \t destination = data.getExtras()。getString(「dest」); – Yogesh 2012-04-15 00:54:54