Search code examples
javaandroidlocationsms

URL - send current location via SMS keep return 0,0 in latitude and longitude - Android Studio


I am trying to get longitude and latitude and send it via SMS to saved contact. But the longitude and latitude return 0,0 in my URL. How can I fix that? I tried some solution that I found here but it doesn't work for me.

This is my code:

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // check for runtime permissions
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS, Manifest.permission.READ_CONTACTS}, 100);
        }
    }

    // this is a special permission required only by devices using
    // Android Q and above. The Access Background Permission is responsible
    // for populating the dialog with "ALLOW ALL THE TIME" option
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 100);
    }



    button1 = findViewById(R.id.Button1);
    listView = (ListView) findViewById(R.id.ListView);
    db = new DbHelper(this);
    list = db.getAllContacts();
    customAdapter = new CustomAdapter(this, list);
    listView.setAdapter(customAdapter);
    send = findViewById(R.id.send);

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // calling of getContacts()
            if (db.count() != 5) {
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, PICK_CONTACT);
            } else {
                Toast.makeText(MainActivity.this, "Can't Add more than 5 Contacts", Toast.LENGTH_SHORT).show();
            }
        }
    });
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Location object = new Location("service Provider");
            double lat = object.getLatitude(); double lng = object.getLongitude();
            onSuccess(object);
        }
    });

}

public void onSuccess(Location currentLocation) {

    String uri = "http://maps.google.com/maps?saddr=" + currentLocation.getLatitude()+","+currentLocation.getLongitude();
    StringBuffer smsBody = new StringBuffer();
    smsBody.append(Uri.parse(uri));
        // get the SMSManager
        SmsManager smsManager = SmsManager.getDefault();

        // get the list of all the contacts in Database
        DbHelper db = new DbHelper(MainActivity.this);
        List<ContactModel> list = db.getAllContacts();

        // send SMS to each contact
        for (ContactModel c : list) {
            String message = "Hey, " + c.getName() + "I am in DANGER, i need help. Please urgently reach me out. Here are my coordinates.\n " + uri;
            smsManager.sendTextMessage(c.getPhoneNo(), null, message, null, null);
        }
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 100) {
        if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            Toast.makeText(this, "Permissions Denied!\n Can't use the App!", Toast.LENGTH_SHORT).show();
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // get the contact from the PhoneBook of device
    switch (requestCode) {
        case (PICK_CONTACT):
            if (resultCode == Activity.RESULT_OK) {

                Uri contactData = data.getData();
                Cursor c = managedQuery(contactData, null, null, null, null);
                if (c.moveToFirst()) {

                    String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                    String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    String phone = null;
                    try {
                        if (hasPhone.equalsIgnoreCase("1")) {
                            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
                            phones.moveToFirst();
                            phone = phones.getString(phones.getColumnIndex("data1"));
                        }
                        String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        db.addcontact(new ContactModel(0, name, phone));
                        list = db.getAllContacts();
                        customAdapter.refresh(list);
                    } catch (Exception ex) {
                    }
                }
            }
            break;
    }
}

And I am using Oreo version for Android. And for manifest: SEND_SMS , INTERNET , ACCESS_COARSE_LOCATION , ACCESS_FINE_LOCATION , READ_CONTACTS.


Solution

  • You are creating an instance of Location yourself:

    Location object = new Location("service Provider");
    

    That will have a location of 0,0 because you did not tell it where the location is.

    If you are expecting to actually get the device location, you cannot create the instance of Location yourself, as you are doing. You need to use LocationManager to obtain the Location.