2015-09-27 41 views
2

我是一個初學者,這可能是我在這裏失蹤的編程基礎知識,但這是我將學習這些東西的唯一方法。android studio從不同的方法訪問一個對象的屬性

下面是我的MainActivity代碼。它試圖獲取最後一個位置的細節,並將它們讀入我定義的類(類稱爲UserCurrentAddress),以便我可以使用這些細節。

我已經在MainActivity類中聲明瞭UserCurrentAddress類,然後在onCreate中實例化了這個類。然後,我使用代碼底部的按鈕單擊(onClickView)來連接API並獲取位置。 「handleNewLocation」方法最終會填充UserCurrentAddress對象(並且可以成功運行)。但是,當我嘗試從buttonClick事件中的UserCurrentAddress中讀取這些詳細信息(僅使用Toast)時,它將返回爲空。如果我把這個吐司放在「handleNewLocation」中,那麼它是正確填充的。 爲什麼UserCurrentAddress的屬性在buttonClick事件中不可見?

我認爲通過在活動類中聲明它可以在整個過程中看到它。

我意識到我可以在「handleNewLocation」方法中做我需要做的事情,但最好從該事件外部訪問這些屬性。

我希望我能解釋我的問題。

代碼:

package com.example.android.trainingapp; 

import android.content.IntentSender; 
import android.location.Address; 
import android.location.Geocoder; 
import android.location.Location; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 
import com.google.android.gms.maps.model.LatLng; 

import java.io.IOException; 
import java.util.List; 
import java.util.Locale; 

public class MainActivity extends AppCompatActivity 
     implements GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     View.OnClickListener{ 

    private GoogleApiClient mGoogleAPIClient; 
    private UserCurrentAddress userCurrentAddress; 
    Button bFindLocation; 
    private LocationRequest mlocationRequest; 
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     bFindLocation = (Button) findViewById(R.id.show_location); 
     bFindLocation.setOnClickListener(this); 

     mGoogleAPIClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 

     mlocationRequest = LocationRequest.create() 
       .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 
       .setInterval(10 * 1000) 
       .setFastestInterval(1 * 1000); 

     userCurrentAddress = new UserCurrentAddress(null, null, null, null, null, 0, 0, null); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 


    @Override 
    public void onConnected(Bundle bundle) { 

     Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleAPIClient); 

     if(location==null){ 
      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleAPIClient, mlocationRequest, (LocationListener) this); 
     } 
     else{ 
      handleNewLocation(location); 
     } 

    } 

    public void handleNewLocation(Location location){ 

     double currentLatitude, currentLongitude; 
     String addressOne, addressTwo, streetNumber, country, fullAddress, postCode, myAdress; 

     currentLatitude = location.getLatitude(); 
     currentLongitude = location.getLongitude(); 
     LatLng latLng = new LatLng(currentLatitude, currentLongitude); 

     Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 

     try { 

      List<Address> addresses = geocoder.getFromLocation(currentLatitude, currentLongitude, 1); 

      if(addresses != null){ 
       Address returnedAddress = addresses.get(0); 
       StringBuilder strReturnedAddress = new StringBuilder(); 
       for(int i=0; i < returnedAddress.getMaxAddressLineIndex(); i++){ 
        strReturnedAddress.append(returnedAddress.getAddressLine(i)).append(" "); 
       } 

       streetNumber = returnedAddress.getSubThoroughfare(); 
       addressOne = returnedAddress.getThoroughfare(); //Beech Rd 
       addressTwo = returnedAddress.getLocality(); //durban north 
       postCode = returnedAddress.getPostalCode(); 
       country = returnedAddress.getCountryName(); 
       myAdress = strReturnedAddress.toString(); 

       userCurrentAddress.streetNumber = streetNumber; 
       userCurrentAddress.addressOne = addressOne; 
       userCurrentAddress.addressTwo = addressTwo; 
       userCurrentAddress.postCode = postCode; 
       userCurrentAddress.country =country ; 
       userCurrentAddress.latitude = currentLatitude; 
       userCurrentAddress.longitude = currentLongitude; 
       userCurrentAddress.fullAddress = myAdress; 
       Toast.makeText(this, userCurrentAddress.streetNumber, Toast.LENGTH_LONG).show(); 

      } 
      else{ 

       myAdress = "No Address Returned"; 

      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
      myAdress = "Cannot get address"; 
     } 


    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     /* 
     * Google Play services can resolve some errors it detects. 
     * If the error has a resolution, try sending an Intent to 
     * start a Google Play services activity that can resolve 
     * error. 
     */ 
     if (connectionResult.hasResolution()) { 
      try { 
       // Start an Activity that tries to resolve the error 
       connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST); 
       /* 
       * Thrown if Google Play services canceled the original 
       * PendingIntent 
       */ 
      } catch (IntentSender.SendIntentException e) { 
       // Log the error 
       e.printStackTrace(); 
      } 
     } else { 
      /* 
      * If no resolution is available, display a dialog to the 
      * user with the error. 
      */ 
     } 
    } 

    @Override 
    public void onClick(View v) { 

     switch (v.getId()){ 
      case R.id.show_location: 
       mGoogleAPIClient.connect(); 
       Toast.makeText(this, userCurrentAddress.fullAddress, Toast.LENGTH_LONG).show(); 
     } 

    } 
} 
+0

你在哪裏試圖訪問它們?另一個活動,片段,方法? –

回答

1

從你所描述的,此行是什麼:

 userCurrentAddress = new UserCurrentAddress(null, null, null, null, null, 0, 0, null); 

必須的handleNewLocation()調用之後得到執行

嘗試將該行移動到GoogleApiClient.Builder調用之前的某個位置,看看是否有任何區別。

相關問題