android studio从不同的方法访问对象的属性

时间:2015-09-27 19:38:22

标签: java android

我是初学者,这可能是我在这里缺少的编程基础,但这是我学习这些东西的唯一方法。

以下是我的MainActivity代码。它试图获取最后一个位置的详细信息并将它们读入我定义的类(类称为UserCurrentAddress),以便我可以使用这些详细信息。

我在MainActivity类中声明了UserCurrentAddress类,然后在onCreate中实例化。然后,我使用代码底部的按钮单击(onClickView)来连接API并获取位置。 " handleNewLocation"方法最终填充UserCurrentAddress对象(这成功地工作)。但是,当我尝试从buttonClick事件(仅使用Toast)中的UserCurrentAddress读取这些详细信息时,它将返回null。如果我把这个吐司放在" handleNewLocation"然后它被正确填充。 为什么从ButtonClick事件看不到UserCurrentAddress的属性?

我想通过在活动类中声明它,它将始终可见。

我意识到我可以在" 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();
        }

    }
}

1 个答案:

答案 0 :(得分:1)

根据您的描述,这一行:

       userCurrentAddress = new UserCurrentAddress(null, null, null, null, null, 0, 0, null);
在<{em> handleNewLocation()电话之后,必须

执行

尝试在GoogleApiClient.Builder来电之前将该行移至某个位置,看看是否有任何区别。