2012-11-20 62 views
0

我有一個字符串,當有人輸入地址來獲取地址的lat和long時,編輯文本字段將填充該字符串。使用動態填充的字符串異步任務

final String specAddressStr = specAddress.getText().toString() + " " + specCity.getText().toString() + "," + " " + specState.getText().toString() + " " + specZip.getText().toString(); 

我需要在一個異步任務使用這個字符串,但是當我試圖引用它,並設置字符串作爲全局變量在任務中使用它,它會導致應用強行關閉。有沒有一種不同的方式來使用我缺少的異步任務中的動態填充字符串?這是因爲請求的異步任務代碼:

public class LowSignal extends Activity { 

String specAddressStr; 

private class processLatandLong extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... params) { 


     List<Address> foundGeocode = null; 

     // find the addresses by using getFromLocationName() method with the given address 

     try { 

      foundGeocode = new Geocoder(LowSignal.this).getFromLocationName(specAddressStr, 1); 
      foundGeocode.get(0).getLatitude(); // getting latitude 
      foundGeocode.get(0).getLongitude();// getting longitude 



     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     if (foundGeocode !=null) { 
      returnedLat.setText(String.valueOf(foundGeocode.get(0).getLatitude())); 
      returnedLong.setText(String.valueOf(foundGeocode.get(0).getLongitude())); 
     } else { 
      returnedLat.setText("Unable to find Latitude. Please try again."); 
      returnedLong.setText("Unable to find Longitude. Please try again."); 
     } 


     return null; 

    } 

而且這裏是我打電話任務:

public void getLatandLong(View v) { 

    String specAddressStr = specAddress.getText().toString() + " " 
       + specCity.getText().toString() + "," + " " 
       + specState.getText().toString() + " " 
       + specZip.getText().toString(); 

     new processLatandLong().execute(specAddressStr); 

    } 
} 
+0

將它作爲參數傳遞給AsyncTask構造函數? – dmon

+0

或作爲參數執行? (也是,stacktrace) – njzk2

回答

1

你可以通過字符串AsyncTask.execute(Your_String)doInBackground訪問Vlue爲:

specAddressStr = specAddress.getText().toString() + " " + 
        specCity.getText().toString() + "," + " " + 
        specState.getText().toString() + " " + 
        specZip.getText().toString(); 
    new LongOperation().execute(specAddressStr); 

private class LongOperation extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) { 
       String stredittext=params[0]; 
      } 
// your code.... 
} 
+0

謝謝。我想我大部分都是這樣。我仍然需要將字符串添加爲全局變量嗎?我很好奇String stredittext = params [0];以及。如果需要,我可以發佈我正在使用的代碼。我很抱歉問這麼多問題,我仍然在學習異步任務以及它們如何工作。 – Jasonwilliams10

+0

@ Jasonwilliams10:好的發佈您的AsyncTask類完整代碼 –

+0

我更新了原始問題的代碼請求。 – Jasonwilliams10