Search code examples
androidlocationmanageroncreate

Requesting Location updates in oncreate method


I am trying to implement a location alarm kind of application. But whenever my application opens. my current location shows as null.

Below is my code.

package com.hrupin;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener, LocationListener {


    private TextView setLat, setLong, destLat, destLong, currLat, currLong, tjd, fromhome, toward;
    private Button setmyLoc, setDest;

    private EditText editLat, editLong;

    private LocationManager orgManager;
    //private LocationListener orgListener;
    // private LocationListener destListener = new destListener();

    private boolean gps_enabled = false;
    private boolean network_enabled = false;

    private String bestProvider;


    double orginLongitude, orginLatitude, destLongtitude, destLatitude, currLatitude, currLongtitude;
    float firstLat, firstLang, secLat, secLang;
    Location destinationLocation = new Location("gps");
    Location originLocation = new Location("gps");
    Location currLocation = new Location("gps");

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setLat = (TextView) findViewById(R.id.setLat);
        setLong = (TextView) findViewById(R.id.setLong);
        destLat = (TextView) findViewById(R.id.destLat);
        destLong = (TextView) findViewById(R.id.destLong);
        currLat = (TextView) findViewById(R.id.currLat);
        currLong = (TextView)findViewById(R.id.currLong);
        tjd = (TextView)findViewById(R.id.setmeter);
        fromhome = (TextView)findViewById(R.id.destmeter);
        toward = (TextView)findViewById(R.id.currmeter);

        setDest = (Button)findViewById(R.id.SetLocation);

        editLat = (EditText)findViewById(R.id.editLat);
        editLong = (EditText)findViewById(R.id.editLong);

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


        try {
            gps_enabled = orgManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
            Log.i("gps_enabled", ex.toString());
        }
        try {
            network_enabled = orgManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
            Log.i("network_enabled", ex.toString());
        }

        // don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled) {
            AlertDialog.Builder builder = new Builder(
                    HelloAndroidGpsActivity.this);
            builder.setTitle("Attention!");
            builder.setMessage("Sorry, location is not determined. Please enable location providers");
            builder.setPositiveButton("OK",
                    HelloAndroidGpsActivity.this);
            builder.setNeutralButton("Cancel",
                    HelloAndroidGpsActivity.this);
            builder.create().show();
        }


        Criteria criteria = new Criteria();
        bestProvider = orgManager.getBestProvider(criteria, false);
        orgManager.requestLocationUpdates(bestProvider, 0, 0, this);
        Location location = orgManager.getLastKnownLocation(bestProvider);

        if (location!=null){
            setLat.setText("Latitude:" + currLatitude);
            setLong.setText("Longitude:" + currLongtitude);
            originLocation.setLatitude(currLatitude);
            originLocation.setLongitude(currLongtitude);
        }
        //else Toast.makeText(getBaseContext(), "Error in GPS", Toast.LENGTH_SHORT).show();

        setDest.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {


                destLat.setText("Lat:"+editLat.getText().toString().trim());
                destLong.setText("Long"+editLong.getText().toString().trim());

                destLatitude = Double.parseDouble(String.valueOf(editLat.getText().toString().trim()));
                destLongtitude = Double.parseDouble(String.valueOf(editLong.getText().toString().trim()));

                destinationLocation.setLatitude(destLatitude);
                destinationLocation.setLongitude(destLongtitude);

                float distance = originLocation.distanceTo(destinationLocation);
                tjd.setText(String.valueOf(distance/1000)+ " Kms ");

            }
        });
    }

    /** Register for the updates when Activity is in foreground */
    @Override
    protected void onResume() {
        super.onResume();
        orgManager.requestLocationUpdates(bestProvider, 60000, 1, this);
    }

    /** Stop the updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        orgManager.removeUpdates(this);
    }

    public void onClick(DialogInterface dialog, int which) {
        if (which == DialogInterface.BUTTON_NEUTRAL) {
            setLat.setText("Sorry, location is not determined. To fix this please enable location providers");
        } else if (which == DialogInterface.BUTTON_POSITIVE) {
            startActivity(new Intent(
                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        if (location != null) {
            // This needs to stop getting the location data and save the
            // battery power.
            //orgManager.removeUpdates(orgListener);

            currLatitude = location.getLatitude();
            currLongtitude = location.getLongitude();

            currLocation.setLatitude(currLatitude);
            currLocation.setLongitude(currLongtitude);

            currLat.setText(String.valueOf(currLatitude));
            currLong.setText(String.valueOf(currLongtitude));

            float fromhome = originLocation.distanceTo(currLocation);

            float toward = currLocation.distanceTo(destinationLocation);

            HelloAndroidGpsActivity.this.fromhome.setText(String.valueOf(fromhome/1000)+ " Kms ");
            HelloAndroidGpsActivity.this.toward.setText(String.valueOf(toward/1000) + " Kms ");

            if (toward/1000 <= 14 ){

                Toast.makeText(getBaseContext(), "You are "+ toward/1000 + " Kms towards Destination ", Toast.LENGTH_SHORT).show();
            }
        }
    }


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

    }

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

    }

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

    }
}

I know this kind of question has been million times. I have tried all methods which has been specified in answers. But i havent got any output. Please help.


Solution

  • You should not call requestLocationUpdates on onCreate as it is redundant since your code will call it on onResume. The flow is onCreate --> onStart --> onResume.