2015-09-27 42 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调用之前的某个位置,看看是否有任何区别。

相关问题