Get the user’s location (City, State, Country) with the facebook login?

Asked

Viewed 320 times

-1

How do I get the user’s city, state and country, with a facebook login?

I have the code below:

facebook.setReadPermissions("email", "public_profile", "user_birthday","user_location");

private void facebookLogin() {
    mAuth = FirebaseAuth.getInstance();
    mCallbackManager = CallbackManager.Factory.create();
    facebook.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "facebook:onSuccess:" + loginResult);
            GraphRequest graphRequest = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    Log.d("JSON", "" + response.getJSONObject().toString());
                    try {
                        nome = object.optString("first_name");
                        sobrenome = object.optString("last_name");
                        email = object.optString("email");
                        aniversario = object.optString("user_birthday");
                        idFB = object.optString("id");
                        sexo = object.getString("gender");
                        paisLogin = object.getJSONObject("location").getString("country"); //como fazer a query?
                        cidade = object.getJSONObject("location").getString("city"); //como fazer a query?
                        SaveSharedPreferences.setIdFacebook(getContext(),idFB);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields","id,first_name,last_name,email,location,gender");
            graphRequest.setParameters(parameters);
            graphRequest.executeAsync();
            AuthCredential credential = FacebookAuthProvider.getCredential(loginResult.getAccessToken().getToken());
            handleFacebookAccessToken(credential);
            //handleFacebookAccessToken(loginResult.getAccessToken());
        }

2 answers

0

There is more than one way to do this. In documentation on Location, shows some examples and parameters that you need to use to rescue the location. On Android, you can make an asynchronous request using the class GraphRequest using GET, which would be HttpMethod.GET. See below:

/* make the API call */
new GraphRequest(
    AccessToken.getCurrentAccessToken(),
    "...?fields=location",
    null,
    HttpMethod.GET,
    new GraphRequest.Callback() {
        public void onCompleted(GraphResponse response) {
            /* aqui será exibida o resultado */

            // para resgatar o nome da cidade, basta resgatar o objeto 
            // JSON passando como parâmetro o nome do campo
            String cidade = (String) response.getJSONObject()
                .getJSONObject("location").get("city");
        }
    }
).executeAsync();

See below for a list of parameters that can be passed to receive specific values:

  • city: City
  • city_id: City identification
  • country: Country
  • country_code: Country code
  • latitude: Latitude
  • located_in: Main location if elsewhere
  • longitude: Longitude
  • name: Name
  • region: Region
  • region_id: Region identification
  • state: State
  • street: Street
  • zip: Zip code

Behold more details in the documentation about Location.

  • Thank you! In my answer I use this. My biggest doubt was how to call this new "call". But in any case it does not explain the question of the parameters, my answer puts them, without them, it is not possible to pick up the objects, but, Thank you again!

-2


This worked for me by adding the getLocationUser method, it searches the id-based location, coming from the "Location" node in the previous Json:

private void facebookLogin() {
    mAuth = FirebaseAuth.getInstance();
    mCallbackManager = CallbackManager.Factory.create();
    //Login com facebook arrumar um lugar melhor e mais organizado..
    facebook.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "facebook:onSuccess:" + loginResult);
            GraphRequest graphRequest = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    Log.d("JSON", "" + response.getJSONObject().toString());
                    try {
                        nome = object.optString("first_name");
                        sobrenome = object.optString("last_name");
                        email = object.optString("email");
                        aniversario = object.optString("user_birthday");
                        idFB = object.optString("id");
                        sexo = object.getString("gender");
                        locationID = object.getJSONObject("location").getString("id");
                        getLocationUser(locationID); <<<<-----
                        SaveSharedPreferences.setIdFacebook(getContext(),idFB);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields","id,first_name,last_name,email,location,gender");
            graphRequest.setParameters(parameters);
            graphRequest.executeAsync();
            AuthCredential credential = FacebookAuthProvider.getCredential(loginResult.getAccessToken().getToken());
            handleFacebookAccessToken(credential);
            //handleFacebookAccessToken(loginResult.getAccessToken());
        }

        @Override
        public void onCancel() {
            Log.d(TAG, "facebook:onCancel");
            // ...
        }

        @Override
        public void onError(FacebookException error) {
            Log.d(TAG, "facebook:onError", error);
            // ...
        }
    });
}

private void getLocationUser(String id) {
    Bundle params = new Bundle();
    params.putString("location", "id");
    new GraphRequest(
            AccessToken.getCurrentAccessToken(),
            id+"/?fields=location",
            params,
            HttpMethod.GET,
            new GraphRequest.Callback() {
                public void onCompleted(GraphResponse response) {
                    Log.e("Response 2", response + "");
                    try {
                        paisLogin = (String) response.getJSONObject().getJSONObject("location").get("country");
                        cidade = (String) response.getJSONObject().getJSONObject("location").get("city");
                        UF = (String) response.getJSONObject().getJSONObject("location").get("state");
                        Log.e("Location", paisLogin);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
    ).executeAsync();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.