Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

android - GPS coordinates (using location manager) get printed as null

OnCreateMethod,

LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);


LocationListener listener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            coordinates = new GeoPoint((int)location.getLatitude(), (int)location.getLongitude()).toString();

        }
    };
    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);

}

and when i try to show coordinates (setText) in a TextView, it says "null"

Android Manifest,

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Even though my TextView displays "null", i get a notification on my status bar which says "Searching for GPS"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is my approach:

Always use a Asynch Task for getting Coordinates etc.

This is because GPS locking etc takes time and you don't want to bog down your main UI thread. Using a asynch task will enable you to throw a process in the background and auto update the UI field once the method has effectively executed.

Here is a code snippet: For the do in background part of the Asynch task

protected String doInBackground(Location... params) {
        /*
         * Get a new geocoding service instance, set for localized addresses.
         * This example uses android.location.Geocoder, but other geocoders that
         * conform to address standards can also be used.
         */
        // Show user progress bar
        pd.show();      
        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        
        // Get the current location from the input parameter list
        Location location = params[0];

        // Create a list to contain the result address
        List<Address> addresses = null;

        // Try to get an address for the current location. Catch IO or network
        // problems.
        try {

            /*
             * Call the synchronous getFromLocation() method with the latitude
             * and longitude of the current location. Return at most 1 address.
             */
            addresses = geocoder.getFromLocation(location.getLatitude(),
                    location.getLongitude(), 1);

            // Catch network or other I/O problems.
        } catch (IOException exception1) {

            // Log an error and return an error message
            Log.e(LocationUtils.APPTAG,
                    mContext.getString(R.string.IO_Exception_getFromLocation));

            // print the stack trace
            exception1.printStackTrace();

            // Return an error message
            return (mContext.getString(R.string.IO_Exception_getFromLocation));

            // Catch incorrect latitude or longitude values
        } catch (IllegalArgumentException exception2) {

            // Construct a message containing the invalid arguments
            String errorString = mContext.getString(
                    R.string.illegal_argument_exception,
                    location.getLatitude(), location.getLongitude());
            // Log the error and print the stack trace
            Log.e(LocationUtils.APPTAG, errorString);
            exception2.printStackTrace();

            //
            return errorString;
        }
        // If the reverse geocode returned an address
        if (addresses != null && addresses.size() > 0) {

            // Get the first address
            Address address = addresses.get(0);

            // Format the first line of address
            addressText = mContext.getString(
                    R.string.address_output_string,

                    // If there's a street address, add it
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "",

                    // Locality is usually a city
                    address.getLocality(),

                    // The country of the address
                    address.getCountryName());

            // Return the text
            return addressText;

            // If there aren't any addresses, post a message
        } else {
            return mContext.getString(R.string.no_address_found);
        }
    }

After the background task has finished executing you can run a onPostExecute method.

protected void onPostExecute(String  result) {
        delegate.processFinished(result);
        // Update the EditText on the UI Thread.
        ed.setText(result);
        // Hide progress bar    
        pd.hide();
    }

In your relevant Main Class you can then call the Aysch Task and ask it to display the results.

public void getAddress(View v) {
        // In Gingerbread and later, use Geocoder.isPresent() to see if a
        // geocoder is available.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
                && !Geocoder.isPresent()) {
            // No geocoder is present. Issue an error message
            Toast.makeText(getActivity(), R.string.no_geocoder_available,
                    Toast.LENGTH_LONG).show();
            return;
        }

        if (servicesConnected()) {
            // Get the current location
            Location currentLocation = mLocationClient.getLastLocation();
            Lat = currentLocation.getLatitude();
            Lng = currentLocation.getLongitude();
            LatLng = Double.toString(Lat) + "," + Double.toString(Lng);
            // Message to show results 
            Toast.makeText(getActivity(), LatLng, 0).show();

            // Turn the indefinite activity indicator on
            // Start the background task
            GetAddressTask getAddressTask = new GetAddressTask(getActivity(),
                    locationAddress, pd);
            getAddressTask.delegate = this;
            getAddressTask.execute(currentLocation);

        } else {
            Toast.makeText(getActivity(), "servicesConnected() == false",
                    Toast.LENGTH_SHORT).show();
        }
    }

Note: this is only the relevant code snippets you need. Refer to my github if you require more detailed approach. Don't forget to upvote and accept answer!enter image description hereenter image description here

Ps:

I included a couple of pictures of an app I made to illustrate what the code can do don't worry about the map and stuff. It just shows events I have added and shared with friends who have the same app on their phone via a Google Cloud Server.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...