2012-03-12 68 views
2

我正在編寫一個應用程序,需要顯示地址以便日後可以使用。 我從LocationManager獲取位置,並且想要顯示按下時顯示地址的Toast。我的問題是,按下按鈕時,什麼也沒有發生。 (甚至在logcat中)將當前地址顯示爲吐司

下面的代碼:

Button getTaxi = (Button) findViewById(R.id.GetTaxi); 
getTaxi.setOnClickListener(new View.OnClickListener() { 

    public void getAddress() { 
     Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault()); 
     String result = null; 
     try { 
      List<Address> list = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
      if (list != null && list.size() > 0) { 
       Address address = list.get(0); 
       // sending back first address line and locality 
       result = address.getAddressLine(0) + ", " + address.getLocality(); 
      } 
     } catch (IOException e) { 
      String exception = String.format("IOException!!"); 
      Toast.makeText(getApplicationContext(), exception, Toast.LENGTH_LONG); 
     } finally { 
      if (result != null) { 
       Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG); 
      } else 
       Toast.makeText(getApplicationContext(), "nix is", Toast.LENGTH_LONG); 
     } 

     final Intent intent = new Intent(); 
     setResult(RESULT_OK, intent); 
     finish(); 
     return; 
    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
    } 
}); 

我知道這是真的propably混亂,但我剛開始JAVA/Android的編程。

非常感謝你提前!

回答

5

而是執行此操作:

Button getTaxi = (Button) findViewById(R.id.GetTaxi); 
getTaxi.setOnClickListener(new View.OnClickListener() { 


    Toast toast; 

    public void getAddress() { 
     Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault()); 
     String result = null; 
     try { 
      List<Address> list = geocoder.getFromLocation(
        location.getLatitude(), location.getLongitude(), 1); 
      if (list != null && list.size() > 0) { 
       Address address = list.get(0); 
       // sending back first address line and locality 
       result = address.getAddressLine(0) + ", " + address.getLocality(); 
      } 
     } catch (IOException e) { 
      String exception = String.format("IOException!!"); 
      toast = Toast.makeText(getApplicationContext(), exception, Toast.LENGTH_LONG); 
     } finally { 

      if (result != null) { 
       toast = Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG); 
      } else 
       toast = Toast.makeText(getApplicationContext(), "nix is", Toast.LENGTH_LONG); 
     } 




     final Intent intent = new Intent(); 
     setResult(RESULT_OK, intent); 
     finish(); 
     return; 
    } 


    @Override 
    public void onClick(View v) { 
     getAddress(); 
     toast.show(); 
    } 
}); 
+0

謝謝你這麼mutch!這幫助我很多! – Teonee 2012-03-12 04:29:33

2

getAddress未被調用。在onClick方法中添加getAddress()。

2

public void onClick(View v)需要有代碼,因爲這是按下按鈕時執行的代碼。就你而言,看起來你可以簡單地在onClick()內撥打getAddress()

0

你必須做出的onclick梅託德,然後你必須通過的getAddress() ,那麼你可以很容易地使addreess當u點擊後按鈕