0

I am having problem with LocationListener. Why is my code not getting the latitude and longitude coordinates in onLocationChange() method? It is passing the coordinates of latitude and longitude to be 0. Can any one point out the error in this code and the changes that needs to be done?

public class Login extends AppCompatActivity implements LocationListener {
    private EditText e_mail, pass_word;
    FirebaseAuth mAuth;
    FirebaseFirestore fStore;
    String userID;
    public static final String TAG = "TAG";

    protected LocationManager locationManager;
    protected LocationListener locationListener;
    protected Context context;

    private double lat;
    private double lng;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        e_mail = findViewById(R.id.emailLogin);
        pass_word = findViewById(R.id.password);
        Button btn_login = findViewById(R.id.btn_login);
        Button btn_sign = findViewById(R.id.btn_signup);


        fStore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);




        btn_login.setOnClickListener(v -> {
            String email= e_mail.getText().toString().trim();
            String password=pass_word.getText().toString().trim();

            if(email.isEmpty())
            {
                e_mail.setError("Email is empty");
                e_mail.requestFocus();
                return;
            }
            if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
            {
                e_mail.setError("Enter the valid email");
                e_mail.requestFocus();
                return;
            }
            if(password.isEmpty())
            {
                pass_word.setError("Password is empty");
                pass_word.requestFocus();
                return;
            }
            if(password.length()<6)
            {
                pass_word.setError("Length of password is more than 6");
                pass_word.requestFocus();
                return;
            }
            mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(task -> {

                if(task.isSuccessful())
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
                    builder.setTitle("Registration")
                            .setMessage("What do you want to register as ? ")
                            .setCancelable(false)
                            .setPositiveButton("Organization", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent organization = new Intent(Login.this,OrganizationPage.class);
                                    startActivity(organization);
                                    Login.this.finish();
                                }
                            })
                            .setNegativeButton("Volunteer", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    uploadData();
                                    Intent volunteer = new Intent(Login.this,VolunteerPage.class);
                                    startActivity(volunteer);
                                    Login.this.finish();}
                            });
                    //Creating dialog box
                    AlertDialog dialog  = builder.create();
                    dialog.show();

                }
                else
                {
                    Toast.makeText(Login.this,
                            "Please Check Your login Credentials",
                            Toast.LENGTH_SHORT).show();
                }

            });



        });
        btn_sign.setOnClickListener(v -> {
            startActivity(new Intent(Login.this, Register.class));
        });
    }


    @Override
    public void onLocationChanged(@NonNull Location location) {
        lat =location.getLatitude();
        lng = location.getLongitude();
        Log.v("Activity location ", String.valueOf(lat)+"latitude of volunteer");
        Toast.makeText(this,lat+" Works "+lng,Toast.LENGTH_SHORT).show();
    }
    public void uploadData(){
        String name = username;

        double latitude = lat;
        double longitude = lng;

        Log.v("Activity location ", String.valueOf(latitude));



        userID = mAuth.getCurrentUser().getUid();
        CollectionReference collectionReference = fStore.collection("Volunteer data");
        Map<String,Object> user = new HashMap<>();
        user.put("timestamp", FieldValue.serverTimestamp());
        user.put("name",name);
        user.put("volunteerLatitude",latitude);
        user.put("volunteerLongitude",longitude);
        user.put("userid",userID);
        collectionReference.add(user)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Toast.makeText(getApplicationContext(),"Successfully Registered as Volunteer",Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getApplicationContext(),"Error!",Toast.LENGTH_SHORT).show();
                    }
                });
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Does this answer your question? [How do I implement the LocationListener?](https://stackoverflow.com/questions/42218419/how-do-i-implement-the-locationlistener) – Praveen G Feb 12 '22 at 10:33
  • No I am not able to understand what's wrong with this code – ARSALAN AHMAD 74 Feb 12 '22 at 10:43
  • 1
    In the above code, I don't see you requesting run time permission if permission is not granted, so if permission is not granted it simply returns. if you still find issues, I'd suggest you use FusedLocationProviderClient ref: https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient – Praveen G Feb 12 '22 at 11:56
  • If you try to log the value of `location.getLatitude()` inside `onLocationChanged()`, are you getting the correct result? Please respond with @AlexMamo – Alex Mamo Feb 13 '22 at 09:24
  • Yes there is some kind of issue in which first time the coordinates are passed in database correctly but for the next time the coordinates of lat lng are passed zero in data base. – ARSALAN AHMAD 74 Feb 13 '22 at 13:22

1 Answers1

0

You need to add location in your manifest.xml like this:

<manifest ... >
  <!-- Always include this permission -->
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

  <!-- Include only if your app benefits from precise location access. -->
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>
patpatwithhat
  • 335
  • 2
  • 11