public void requestFacebookUserDetails() {
    GraphRequest request =
        GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
              @Override
              public void onCompleted(JSONObject profile, GraphResponse response) {
                // JSONObject userProfile = new JSONObject();
                if (profile == null) {
                  Log.wtf("FIRST", "PROFILE VAZIO");
                } else {
                  ParseUser currentUser = ParseUser.getCurrentUser();
                  try {
                    currentUser.put("name", profile.get("name"));
                    currentUser.saveInBackground();
                    goToHomePage();
                  } catch (JSONException e) {
                    Log.wtf("ERROR DETAIL", "Erro ao pegar detalhes");
                  }
                }
              }
            });

    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,picture,name,link");
    request.setParameters(parameters);
    request.executeAsync();
  }
Beispiel #2
0
  public boolean getBeepleImages() {
    currentToken = AccessToken.getCurrentAccessToken();
    if (currentToken != null) {
      GraphRequest request =
          GraphRequest.newGraphPathRequest(
              currentToken,
              "/10150428845566781/photos",
              new GraphRequest.Callback() {
                @Override
                public void onCompleted(GraphResponse response) {
                  JSONObject data = response.getJSONObject();
                  try {
                    String newestImage = data.getJSONArray("data").getJSONObject(0).getString("id");
                    getImage(newestImage);
                    Log.d(TAG, newestImage);
                  } catch (org.json.JSONException e) {
                    Log.e(TAG, e.toString());
                  }
                }
              });

      request.executeAsync();
      return true;
    } else {
      Log.d(TAG, "Current access token does not exist");
      return false;
    }
  }
  private void readPost() {
    AccessToken token = AccessToken.getCurrentAccessToken();
    String path = "/me/feed";
    GraphRequest request =
        new GraphRequest(
            token,
            path,
            null,
            HttpMethod.GET,
            new Callback() {

              @Override
              public void onCompleted(GraphResponse response) {
                JSONObject obj = response.getJSONObject();
                if (obj != null) {
                  Toast.makeText(
                          MainActivity.this, "result : " + obj.toString(), Toast.LENGTH_SHORT)
                      .show();
                } else {
                  Toast.makeText(
                          MainActivity.this,
                          "errof : " + response.getError().getErrorMessage(),
                          Toast.LENGTH_SHORT)
                      .show();
                }
              }
            });
    request.executeAsync();
  }
  private void getMoreInformation(LoginResult loginResult) {
    GraphRequest request =
        GraphRequest.newMeRequest(
            loginResult.getAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
              @Override
              public void onCompleted(JSONObject object, GraphResponse response) {

                Log.d(TAG, "response:" + response.toString());
                try {
                  String name = object.getString("name");
                  SharedPreferences.Editor editor = sp.edit();
                  editor.putString("fb_name", name);
                  editor.commit();
                  tv_name.setText(name);
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,link,gender,birthday,email");
    request.setParameters(parameters);
    request.executeAsync();
  }
Beispiel #5
0
 private void getFacebookId() {
   AccessToken accessToken = AccessToken.getCurrentAccessToken();
   GraphRequest request =
       GraphRequest.newMeRequest(
           accessToken,
           new GraphRequest.GraphJSONObjectCallback() {
             @Override
             public void onCompleted(JSONObject object, GraphResponse response) {
               JSONObject result = response.getJSONObject();
               try {
                 String id = result.getString("id");
                 ParseUser user = ParseUser.getCurrentUser();
                 user.put("facebookId", id);
                 try {
                   user.save();
                 } catch (ParseException e) {
                   e.printStackTrace();
                 }
               } catch (JSONException e) {
                 e.printStackTrace();
               }
             }
           });
   Bundle parameters = new Bundle();
   parameters.putString("fields", "id");
   request.setParameters(parameters);
   request.executeAsync();
 }
 private void getUserDetails(AccessToken accessToken) {
   showProgress(getString(R.string.get_username_progress));
   GraphRequest graphRequest =
       GraphRequest.newMeRequest(
           accessToken,
           new GraphRequest.GraphJSONObjectCallback() {
             @Override
             public void onCompleted(JSONObject object, GraphResponse response) {
               dismissProgress();
               if (object != null) {
                 try {
                   final String username = object.getString("name");
                   Log.d("TarotFeedback", username);
                   Log.d("TarotFeedback", object.toString());
                   saveUsername(username);
                   addFeedback(username);
                 } catch (JSONException e) {
                   e.printStackTrace();
                 }
               } else {
                 Toast.makeText(
                         TarotFeedbackActivity.this,
                         getString(R.string.get_username_error),
                         Toast.LENGTH_SHORT)
                     .show();
               }
             }
           });
   Bundle parameters = new Bundle();
   parameters.putString("fields", "name");
   graphRequest.setParameters(parameters);
   graphRequest.executeAsync();
 }
  public void RequestData() {
    GraphRequest request =
        GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
              @Override
              public void onCompleted(JSONObject object, GraphResponse response) {

                JSONObject json = response.getJSONObject();
                try {
                  if (json != null) {
                    String text =
                        "<b>Name :</b> "
                            + json.getString("name")
                            + "<br><br><b>Email :</b> "
                            + json.getString("email")
                            + "<br><br><b>Profile link :</b> "
                            + json.getString("link");
                    details_txt.setText(Html.fromHtml(text));
                    profile.setProfileId(json.getString("id"));
                  }

                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,link,email,picture");
    request.setParameters(parameters);
    request.executeAsync();
  }
  private void setupViewObjects(User user) {
    ivCoverPic = (ImageView) mFragmentView.findViewById(R.id.ivCoverPic);
    ivProfilePic = (ImageView) mFragmentView.findViewById(R.id.ivProfilePic);
    TextView tvProfileName = (TextView) mFragmentView.findViewById(R.id.tvProfileName);
    TextView tvProfileLocation = (TextView) mFragmentView.findViewById(R.id.tvProfileLocation);

    Picasso.with(getContext())
        .load(
            "https://graph.facebook.com/"
                + user.getAuthId()
                + "/picture?width="
                + String.valueOf(getContext().getResources().getDisplayMetrics().widthPixels))
        .into(ivProfilePic /*new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        src = bitmap;
                        Resources res = getResources();
                        RoundedBitmapDrawable dr =
                                RoundedBitmapDrawableFactory.create(res, src);
                        dr.setCornerRadius(500f);
                        ivProfilePic.setImageDrawable(dr);
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {

                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }
                }*/);

    GraphRequest request =
        GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {

              @Override
              public void onCompleted(JSONObject ret, GraphResponse graphResponse) {
                JSONObject cover = null;
                String url = null;
                try {
                  cover = ret.getJSONObject("cover");
                  url = cover.getString("source");
                } catch (JSONException e) {
                  e.printStackTrace();
                }
                Picasso.with(getContext()).load(url).into(ivCoverPic);
              }
            });

    Bundle parameters = new Bundle();
    parameters.putString("fields", "cover");
    request.setParameters(parameters);
    request.executeAsync();

    tvProfileName.setText(user.getName());
  }
  /** {@inheritDoc} */
  public void reloadUserInfo() {
    clearUserInfo();
    if (!isUserSignedIn()) {
      return;
    }

    final Bundle parameters = new Bundle();
    parameters.putString("fields", "name,picture.type(large)");
    final GraphRequest graphRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), "me");
    graphRequest.setParameters(parameters);
    GraphResponse response = graphRequest.executeAndWait();

    JSONObject json = response.getJSONObject();
    try {
      userName = json.getString("name");
      userImageUrl = json.getJSONObject("picture").getJSONObject("data").getString("url");

    } catch (final JSONException jsonException) {
      Log.e(
          LOG_TAG,
          "Unable to get Facebook user info. " + jsonException.getMessage() + "\n" + response,
          jsonException);
      // Nothing much we can do here.
    }
  }
Beispiel #10
0
  private void getUserDetailsFromFB() {
    GraphRequest request =
        GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
              @Override
              public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                try {
                  userNameText = jsonObject.getString("name");
                } catch (JSONException e) {
                  e.printStackTrace();
                }
                try {
                  emailId = jsonObject.getString("email");
                } catch (JSONException e) {
                  e.printStackTrace();
                }

                saveNewUser();
              }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "name,email");
    request.setParameters(parameters);
    request.executeAsync();
  }
Beispiel #11
0
  // Note that this method makes a synchronous Graph API call, so should not be called from the
  // main thread.
  private static JSONObject getAppSettingsQueryResponse(String applicationId) {
    Bundle appSettingsParams = new Bundle();
    appSettingsParams.putString(APPLICATION_FIELDS, TextUtils.join(",", APP_SETTING_FIELDS));

    GraphRequest request = GraphRequest.newGraphPathRequest(null, applicationId, null);
    request.setSkipClientToken(true);
    request.setParameters(appSettingsParams);

    return request.executeAndWait().getJSONObject();
  }
Beispiel #12
0
        @Override
        public void onSuccess(LoginResult loginResult) {

          GraphRequest request =
              GraphRequest.newMeRequest(
                  loginResult.getAccessToken(),
                  new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                      final String email = object.optString("email");
                      final String id = object.optString("id");

                      final HashMap<String, String> params = new HashMap<>();
                      params.put("profileId", id);
                      params.put("email", email);

                      JsonObjectRequest request =
                          new JsonObjectRequest(
                              Request.Method.POST,
                              requestURL,
                              new JSONObject(params),
                              new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                  String userID = response.optJSONObject("data").optString("_id");

                                  SharedPreferences.Editor editor =
                                      getActivity()
                                          .getSharedPreferences(prefFile, Context.MODE_PRIVATE)
                                          .edit();
                                  editor.putString("facebookEmail", email);
                                  editor.putString("facebookId", id);
                                  editor.putString("userID", userID);
                                  editor.apply();

                                  getActivity().finish();
                                }
                              },
                              new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                  VolleyLog.d("Error", "Error: " + error.getMessage());
                                }
                              });
                      VolleyApplication.getInstance().getRequestQueue().add(request);
                    }
                  });
          Bundle parameters = new Bundle();
          parameters.putString("fields", "email");
          request.setParameters(parameters);
          request.executeAsync();
        }
Beispiel #13
0
  private void makeMeRequest() {
    GraphRequest request =
        GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
              @Override
              public void onCompleted(JSONObject user, GraphResponse response) {
                if (user != null) {

                  JSONObject userProfile = new JSONObject();
                  try {

                    // profilePicture.setProfileId(user.getString("id"));

                    userProfile.put("facebookId", user.getLong("id"));
                    userProfile.put("name", user.getString("name"));
                    if (user.getString("gender") != null) {
                      userProfile.put("gender", (String) user.getString("gender"));
                    }
                    if (user.getString("email") != null) {
                      userProfile.put("email", (String) user.getString("email"));
                    }

                    ParseUser currentUser = ParseUser.getCurrentUser();
                    currentUser.put("name", user.getString("name"));
                    currentUser.put("type", "User");
                    currentUser.put("profile", userProfile);

                  } catch (JSONException e) {
                    Log.d("My", "Error parsing returned user data. " + e);
                  }

                } else if (response.getError() != null) {
                  switch (response.getError().getCategory()) {
                    case LOGIN_RECOVERABLE:
                      Log.d("theSOS", "Authentication error: " + response.getError());
                      break;

                    case TRANSIENT:
                      Log.d("theSOS", "Transient error. Try again. " + response.getError());
                      break;

                    case OTHER:
                      Log.d("theSOS", "Some other error: " + response.getError());
                      break;
                  }
                }
              }
            });
    request.executeAsync();
  }
Beispiel #14
0
  private void refreshFriends() {
    GraphRequest req =
        new GraphRequest(
            AccessToken.getCurrentAccessToken(),
            "/me/friends",
            null,
            HttpMethod.GET,
            new GraphRequest.Callback() {
              @Override
              public void onCompleted(GraphResponse response) {
                Log.d("PartyOn", "Graphresponse: " + response.toString());
                if (response.getJSONArray() == null && response.getJSONObject() == null) return;
                try {
                  JSONArray data = response.getJSONObject().getJSONArray("data");

                  realm.beginTransaction();

                  Friend friend;
                  for (int i = 0; i < data.length(); i++) {
                    friend = new Friend();
                    friend.setId(data.getJSONObject(i).getString("id"));
                    friend.setName(data.getJSONObject(i).getString("first_name"));
                    friend.setImageUrl(
                        data.getJSONObject(i)
                            .getJSONObject("picture")
                            .getJSONObject("data")
                            .getString("url"));
                    realm.copyToRealmOrUpdate(friend);
                  }

                  realm.commitTransaction();

                  RealmResults<Friend> results = realm.allObjects(Friend.class); // TODO: Run async

                  if (!compact) {
                    getListView().setVisibility(View.VISIBLE);
                    progressBar.setVisibility(View.GONE);
                  }

                  adapter.update(results);
                } catch (JSONException e) {
                  Log.d("PartyOn", "JSON", e);
                  realm.cancelTransaction();
                }
              }
            });
    Bundle args = new Bundle();
    args.putString("fields", "id,first_name,picture");
    req.setParameters(args);
    req.executeAsync();
  }
Beispiel #15
0
  public static JSONObject awaitGetGraphMeRequestWithCache(final String accessToken) {
    JSONObject cachedValue = ProfileInformationCache.getProfileInformation(accessToken);
    if (cachedValue != null) {
      return cachedValue;
    }

    GraphRequest graphRequest = getGraphMeRequestWithCache(accessToken);
    GraphResponse response = graphRequest.executeAndWait();
    if (response.getError() != null) {
      return null;
    }

    return response.getJSONObject();
  }
Beispiel #16
0
  @Override
  public void onSuccess(final LoginResult loginResult) {
    if (loginResult == null || loginResult.getAccessToken() == null) {
      return;
    }

    Logger.debug(LoginActivity.TAG, loginResult.getAccessToken().getApplicationId());
    Logger.debug(LoginActivity.TAG, loginResult.getAccessToken().getToken());
    Logger.debug(LoginActivity.TAG, loginResult.getAccessToken().getUserId());

    // Request me
    final GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), this);
    request.setParameters(LoginActivity.FACEBOOK_ME_PERMISSION);
    request.executeAsync();
  }
  private void makeGraphCall() {
    // If you're using the paging URLs they will be URLEncoded, let's decode them.
    try {
      graphPath = URLDecoder.decode(graphPath, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    String[] urlParts = graphPath.split("\\?");
    String graphAction = urlParts[0];
    GraphRequest graphRequest =
        GraphRequest.newGraphPathRequest(
            AccessToken.getCurrentAccessToken(),
            graphAction,
            new GraphRequest.Callback() {
              @Override
              public void onCompleted(GraphResponse response) {
                if (graphContext != null) {
                  if (response.getError() != null) {
                    graphContext.error(getFacebookRequestErrorResponse(response.getError()));
                  } else {
                    graphContext.success(response.getJSONObject());
                  }
                  graphPath = null;
                  graphContext = null;
                }
              }
            });

    Bundle params = graphRequest.getParameters();

    if (urlParts.length > 1) {
      String[] queries = urlParts[1].split("&");

      for (String query : queries) {
        int splitPoint = query.indexOf("=");
        if (splitPoint > 0) {
          String key = query.substring(0, splitPoint);
          String value = query.substring(splitPoint + 1, query.length());
          params.putString(key, value);
        }
      }
    }

    graphRequest.setParameters(params);
    graphRequest.executeAsync();
  }
 private void getUserFacebookDetails(LoginResult loginResult) {
   final AccessToken token = loginResult.getAccessToken();
   GraphRequest request =
       GraphRequest.newMeRequest(
           loginResult.getAccessToken(),
           new GraphRequest.GraphJSONObjectCallback() {
             @Override
             public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
               Log.v("LoginActivity", graphResponse.toString());
               sharedPreferences.edit().putString("latestFbLogin", jsonObject.toString());
               parseFBData(jsonObject, token);
             }
           });
   Bundle parameters = new Bundle();
   parameters.putString("fields", "id,email,gender, birthday,first_name,last_name");
   request.setParameters(parameters);
   request.executeAsync();
 }
Beispiel #19
0
  private void getImage(String id) {

    if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }

    GraphRequest request =
        GraphRequest.newGraphPathRequest(
            currentToken,
            "/" + id,
            new GraphRequest.Callback() {
              @Override
              public void onCompleted(GraphResponse response) {
                JSONObject data = response.getJSONObject();
                try {
                  JSONArray images = data.getJSONArray("images");
                  for (int idx = 0; idx < images.length(); idx++) {
                    String height = images.getJSONObject(idx).getString("height");
                    String width = images.getJSONObject(idx).getString("width");
                    if (height != null && width != null) {
                      if (height.equals("320") || width.equals("320")) {
                        URL url = new URL(images.getJSONObject(idx).getString("source"));
                        setCurrentBitmap(
                            BitmapFactory.decodeStream(url.openConnection().getInputStream()));
                      }
                    } else {
                      Log.d(TAG, "Null value for height or width of image");
                    }
                  }
                } catch (org.json.JSONException | java.io.IOException e) {
                  Log.e(TAG, e.toString());
                }
              }
            });

    Bundle parameters = new Bundle();
    parameters.putString("fields", "images");
    request.setParameters(parameters);
    request.executeAsync();
  }
  private void getUserInfo() {
    Bundle parameters = new Bundle();
    final AlertDialog alertDialog =
        new AlertDialog.Builder(activityWeakReference.get())
            .setMessage("Baixando informações do usuário...")
            .setCancelable(false)
            .show();

    GraphRequest graphRequest =
        GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
              @Override
              public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                alertDialog.dismiss();
                changeCurrentState(StatusFacebookConn.CONNECTED);
                Log.i(TAGINFO, "Getting user info completed/Connected");
                try {
                  activityWeakReference
                      .get()
                      .getSharedPreferences("FacebookSession", Context.MODE_PRIVATE)
                      .edit()
                      .putString("FacebookEmail", jsonObject.getString("email"))
                      .commit();
                  activityWeakReference
                      .get()
                      .getSharedPreferences("FacebookSession", Context.MODE_PRIVATE)
                      .edit()
                      .putBoolean("FacebookLogged", true)
                      .commit();
                } catch (JSONException e) {
                  Log.e(TAGERROR, e.getMessage() + " - " + e.getCause());
                }
              }
            });
    parameters.putString("fields", "email");
    graphRequest.setParameters(parameters);
    graphRequest.executeAsync();
    Log.i(TAGINFO, "Requesting user info");
  }
  private void sendPost() {
    AccessToken token = AccessToken.getCurrentAccessToken();
    String path = "/me/feed";
    Bundle params = new Bundle();
    params.putString("message", "facebook post test");
    params.putString("link", "http://developers.facebook.com/docs/android");
    params.putString(
        "picture",
        "https://scontent.xx.fbcdn.net/hphotos-xpa1/t39.2178-6/851567_1813371155468532_1182857230_n.png");
    params.putString("name", "Hello Facebook");
    params.putString("description", "The 'Hello Facebook' sample  showcases simple …");

    GraphRequest request =
        new GraphRequest(
            token,
            path,
            params,
            HttpMethod.POST,
            new Callback() {

              @Override
              public void onCompleted(GraphResponse response) {
                JSONObject obj = response.getJSONObject();
                if (obj != null) {
                  Toast.makeText(
                          MainActivity.this, "id : " + obj.optString("id"), Toast.LENGTH_SHORT)
                      .show();
                } else {
                  Toast.makeText(
                          MainActivity.this,
                          "errof : " + response.getError().getErrorMessage(),
                          Toast.LENGTH_SHORT)
                      .show();
                }
              }
            });

    request.executeAsync();
  }
 protected void checkFacebookSession() {
   AccessToken accessToken = AccessToken.getCurrentAccessToken();
   if (accessToken != null && !accessToken.isExpired()) {
     GraphRequest request =
         GraphRequest.newMeRequest(
             accessToken,
             new GraphRequest.GraphJSONObjectCallback() {
               @Override
               public void onCompleted(JSONObject userJson, GraphResponse graphResponse) {
                 User.facebookUser(userJson);
               }
             });
     Bundle parameters = new Bundle();
     parameters.putString("fields", "id,name,link,gender,birthday,email");
     request.setParameters(parameters);
     request.executeAsync();
   } else {
     List<String> permissions = new ArrayList<String>();
     permissions.add("public_profile");
     permissions.add("email");
     LoginManager.getInstance().logInWithReadPermissions(getActivity(), permissions);
   }
 }
  @Override
  public void post(
      final Context context,
      final Corruption corruption,
      final AccessToken accessToken,
      final OperationCallback<Integer> callback) {
    File file = new File(corruption.getMediaFilePath());

    Bundle params = new Bundle();
    params.putString(Utils.Constants.DESCRIPTION, Utils.getNarrative(context, corruption));
    params.putByteArray(corruption.getMediaFilePath(), Utils.convertFileToBytes(file));

    GraphRequest request =
        new GraphRequest(
            accessToken,
            Utils.Constants.PAGE_VIDEOS,
            params,
            HttpMethod.POST,
            new GraphRequest.Callback() {
              @Override
              public void onCompleted(GraphResponse graphResponse) {
                if (graphResponse.getError() == null) {
                  try {
                    String post_Id = graphResponse.getJSONObject().getString("id");
                    corruption.setPostId(post_Id);
                  } catch (JSONException e) {
                    Logger.log(AudioPoster.class, e.getMessage());
                  }
                  callback.performOperation(R.string.success);
                } else {
                  callback.performOperation(R.string.failed);
                }
              }
            });

    request.executeAsync();
  }
Beispiel #24
0
        @Override
        public void onSuccess(LoginResult loginResult) {

          GraphRequest request =
              GraphRequest.newMeRequest(
                  loginResult.getAccessToken(),
                  new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                      try {
                        FBmap = new LinkedMultiValueMap<String, String>();
                        FBmap.add("nome", jsonObject.getString("name"));
                        FBmap.add("email", jsonObject.getString("email"));
                        FBmap.add("senha", jsonObject.getString("id"));
                        urlFoto =
                            jsonObject
                                .getJSONObject("picture")
                                .getJSONObject("data")
                                .getString("url");

                        new HttpBuscaEmailFB(
                                (new Webservice()).buscaUsuarioEmail(jsonObject.getString("email")),
                                null,
                                Usuario.class,
                                "")
                            .execute();

                      } catch (JSONException e) {
                        e.printStackTrace();
                      }
                    }
                  });
          Bundle params = new Bundle();
          params.putString("fields", "id,name,email,picture");
          request.setParameters(params);
          request.executeAsync();
        }
Beispiel #25
0
  public static void getGraphMeRequestWithCacheAsync(
      final String accessToken, final GraphMeRequestWithCacheCallback callback) {
    JSONObject cachedValue = ProfileInformationCache.getProfileInformation(accessToken);
    if (cachedValue != null) {
      callback.onSuccess(cachedValue);
      return;
    }

    GraphRequest.Callback graphCallback =
        new GraphRequest.Callback() {
          @Override
          public void onCompleted(GraphResponse response) {
            if (response.getError() != null) {
              callback.onFailure(response.getError().getException());
            } else {
              ProfileInformationCache.putProfileInformation(accessToken, response.getJSONObject());
              callback.onSuccess(response.getJSONObject());
            }
          }
        };
    GraphRequest graphRequest = getGraphMeRequestWithCache(accessToken);
    graphRequest.setCallback(graphCallback);
    graphRequest.executeAsync();
  }
  private void requestProfileInfo() {
    String request_string = "/" + AccessToken.getCurrentAccessToken().getUserId() + "/picture";
    Bundle parameters = new Bundle();
    parameters.putBoolean("redirect", false);
    parameters.putInt("height", 300);
    parameters.putInt("width", 300);

    GraphRequest dp_request =
        new GraphRequest(
            AccessToken.getCurrentAccessToken(),
            request_string,
            parameters,
            HttpMethod.GET,
            new GraphRequest.Callback() {

              @Override
              public void onCompleted(GraphResponse graphResponse) {
                JSONObject obj = graphResponse.getJSONObject();
                try {
                  JSONObject profile_data = (JSONObject) obj.get("data");
                  String current_dp_url = (String) profile_data.get("url");
                  url = current_dp_url;

                } catch (JSONException e) {
                  Log.d(TAG, "something went wrong with profile picture request");
                } catch (NullPointerException e) {
                  e.printStackTrace();
                  Log.d(TAG, graphResponse.getError().toString());
                }
              }
            });

    // dp_request.setParameters(parameters);

    // request for name, gender, age_range
    GraphRequest meRequest =
        GraphRequest.newMeRequest(
            accessToken,
            new GraphRequest.GraphJSONObjectCallback() {

              @Override
              public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                try {
                  name = jsonObject.getString("first_name");
                  String gender_string = jsonObject.getString("gender");
                  if (gender_string.equals("male")) {
                    gender = false;
                  } else {
                    gender = true;
                  }
                  age = 21;

                } catch (JSONException e) {
                  e.printStackTrace();
                } catch (NullPointerException e) {
                  e.printStackTrace();
                }
              }
            });

    // saveUserToDB();

    parameters = new Bundle();
    parameters.putString("fields", "id,first_name, gender, age_range");

    meRequest.setParameters(parameters);

    final GraphRequestBatch request;
    request = new GraphRequestBatch(meRequest, dp_request);
    meRequest.executeAndWait();
    dp_request.executeAndWait();
    saveUserToDB();
    registerUser();
  }
  public void getFacebookData() {
    final ArrayList<String> strings = new ArrayList<>();
    GraphRequestBatch batch;
    batch =
        new GraphRequestBatch(
            GraphRequest.newMeRequest(
                access_token,
                new GraphRequest.GraphJSONObjectCallback() {
                  @Override
                  public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                    if (graphResponse.getError() != null) {
                      // handle error
                      System.out.println("ERROR");
                    } else {
                      System.out.println("Success");
                    }

                    try {
                      String jsonresult = String.valueOf(jsonObject);
                      System.out.println("JSON Result" + jsonresult);
                      String str_firstname = jsonObject.getString("name");
                      nameText.setText(str_firstname);
                    } catch (JSONException e) {
                      e.printStackTrace();
                    }
                  }
                }),
            new GraphRequest(
                access_token,
                "me/feed",
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                  @Override
                  public void onCompleted(GraphResponse graphResponse) {
                    if (graphResponse.getError() != null) {
                      // handle error
                      System.out.println("ERROR");
                    } else {
                      System.out.println("Success");
                    }

                    try {
                      JSONObject json = null;
                      JSONArray jarray = null;
                      json = new JSONObject(graphResponse.getRawResponse());
                      jarray = json.getJSONArray("data");
                      for (int i = 0; i < jarray.length(); i++) {
                        JSONObject oneStory = null;
                        oneStory = jarray.getJSONObject(i);

                        String story;

                        story = oneStory.optString("story");
                        if (story.isEmpty()) story = oneStory.optString("message");
                        strings.add(i, story);
                      }
                    } catch (JSONException e) {
                      e.printStackTrace();
                    }

                    Log.d("RESPONSE", strings.toString());
                    ArrayAdapter<String> arrayAdapter =
                        new ArrayAdapter<String>(
                            MainActivity.this, android.R.layout.simple_list_item_1, strings);
                    dataList.setAdapter(arrayAdapter);
                  }
                }));

    batch.executeAsync();
  }
    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
      final Album album = mAlbums.get(position);

      holder.mAlbumNameView.setText(album.getName());

      String facebookId = null;
      try {
        facebookId = album.getAuthor().fetchIfNeeded().getString("facebookId");

        ParseQuery<Photo> query = ParseQuery.getQuery(Photo.class);
        query.whereEqualTo("originAlbum", album);
        query.findInBackground(
            new FindCallback<Photo>() {
              public void done(List<Photo> scoreList, ParseException e) {
                if (e == null) {
                  if (!scoreList.isEmpty()) {
                    int width = holder.mThumbnailView.getWidth();
                    int height = holder.mThumbnailView.getHeight();
                    mBitmapDownloader.queueUrl(
                        holder.mThumbnailView,
                        scoreList.get(0).getImage().getUrl(),
                        new Size(width, height));
                  }
                } else {
                  e.printStackTrace();
                }
              }
            });

        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        GraphRequest request =
            GraphRequest.newGraphPathRequest(
                accessToken,
                "/" + facebookId,
                new GraphRequest.Callback() {
                  @Override
                  public void onCompleted(GraphResponse response) {
                    JSONObject result = response.getJSONObject();
                    try {
                      String name = result.getString("name");
                      String pictureUrl =
                          result.getJSONObject("picture").getJSONObject("data").getString("url");
                      holder.mAuthorNameView.setText(name);
                      holder.mNumberCollaboratorsView.setText(
                          String.valueOf(album.getNumberOfCollaborators()));

                      int width = holder.mAuthorPictureView.getWidth();
                      int height = holder.mAuthorPictureView.getHeight();

                      mBitmapDownloader.queueUrl(
                          holder.mAuthorPictureView, pictureUrl, new Size(width, height));
                    } catch (JSONException e) {
                      e.printStackTrace();
                    }
                  }
                });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "name,picture");
        request.setParameters(parameters);
        request.executeAsync();
      } catch (ParseException e) {
        e.printStackTrace();
      }
    }
Beispiel #29
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_login);
    mCallbackManager = CallbackManager.Factory.create();

    getSupportActionBar().hide();

    if (mata_sessao) {
      LoginManager.getInstance().logOut();
    }

    final EditText etEmail = (EditText) findViewById(R.id.etEmail);
    final EditText etSenha = (EditText) findViewById(R.id.etSenha);
    etEmail.requestFocus();

    Button btEntrar = (Button) findViewById(R.id.btEntrar);

    btEntrar.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View arg0) {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            map.add("email", String.valueOf(etEmail.getText().toString()));
            map.add("senha", String.valueOf(etSenha.getText().toString()));

            Usuario usuario = new Usuario();
            Webservice ws = new Webservice();
            new HttpLogin(ws.login(), map, Usuario.class, "").execute();
          }
        });

    TextView tvCadastrar = (TextView) findViewById(R.id.tvCadastrar);

    tvCadastrar.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View arg0) {
            Intent tela1 = new Intent(Login.this, Cadastro.class);
            startActivity(tela1);
          }
        });

    ProfileTracker profileTracker =
        new ProfileTracker() {
          @Override
          protected void onCurrentProfileChanged(Profile profile, Profile newProfile) {}
        };

    LoginButton FBLoginButton = (LoginButton) findViewById(R.id.fb_login_button);
    FBLoginButton.registerCallback(mCallbackManager, mCallBack);

    if (AccessToken.getCurrentAccessToken() != null) {
      GraphRequest request2 =
          GraphRequest.newMeRequest(
              AccessToken.getCurrentAccessToken(),
              new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                  try {
                    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
                    map.add("email", jsonObject.getString("email"));
                    map.add("senha", jsonObject.getString("id"));

                    new HttpLoginFB((new Webservice()).login(), map, Usuario.class, "").execute();

                  } catch (JSONException e) {
                    e.printStackTrace();
                  }
                }
              });
      Bundle params2 = new Bundle();
      params2.putString("fields", "id,name,email");
      request2.setParameters(params2);
      request2.executeAsync();
    }
  }
  /**
   * Asynchronously resolves App Link data for multiple URLs
   *
   * @param uris A list of Uri objects to resolve into App Links
   * @return A Task that, when successful, will return a Map of Uri->AppLink for each Uri that was
   *     successfully resolved into an App Link. Uris that could not be resolved into App Links will
   *     not be present in the Map. In the case of general server errors, the task will be completed
   *     with the corresponding error.
   */
  public Task<Map<Uri, AppLink>> getAppLinkFromUrlsInBackground(List<Uri> uris) {
    final Map<Uri, AppLink> appLinkResults = new HashMap<Uri, AppLink>();
    final HashSet<Uri> urisToRequest = new HashSet<Uri>();
    StringBuilder graphRequestFields = new StringBuilder();

    for (Uri uri : uris) {
      AppLink appLink = null;
      synchronized (cachedAppLinks) {
        appLink = cachedAppLinks.get(uri);
      }

      if (appLink != null) {
        appLinkResults.put(uri, appLink);
      } else {
        if (!urisToRequest.isEmpty()) {
          graphRequestFields.append(',');
        }
        graphRequestFields.append(uri.toString());
        urisToRequest.add(uri);
      }
    }

    if (urisToRequest.isEmpty()) {
      return Task.forResult(appLinkResults);
    }

    final Task<Map<Uri, AppLink>>.TaskCompletionSource taskCompletionSource = Task.create();

    Bundle appLinkRequestParameters = new Bundle();

    appLinkRequestParameters.putString("ids", graphRequestFields.toString());
    appLinkRequestParameters.putString(
        "fields",
        String.format(
            "%s.fields(%s,%s)",
            APP_LINK_KEY, APP_LINK_ANDROID_TARGET_KEY, APP_LINK_WEB_TARGET_KEY));
    GraphRequest appLinkRequest =
        new GraphRequest(
            // We will use the current access token if we have one else we will use the client
            // token
            AccessToken.getCurrentAccessToken(), /* Access Token */
            "", /* Graph path */
            appLinkRequestParameters, /* Query parameters */
            null, /* HttpMethod */
            new GraphRequest.Callback() {
              /* Callback */
              @Override
              public void onCompleted(GraphResponse response) {
                FacebookRequestError error = response.getError();
                if (error != null) {
                  taskCompletionSource.setError(error.getException());
                  return;
                }

                JSONObject responseJson = response.getJSONObject();
                if (responseJson == null) {
                  taskCompletionSource.setResult(appLinkResults);
                  return;
                }

                for (Uri uri : urisToRequest) {
                  String uriString = uri.toString();
                  if (!responseJson.has(uriString)) {
                    continue;
                  }

                  JSONObject urlData = null;
                  try {
                    urlData = responseJson.getJSONObject(uri.toString());
                    JSONObject appLinkData = urlData.getJSONObject(APP_LINK_KEY);

                    JSONArray rawTargets = appLinkData.getJSONArray(APP_LINK_ANDROID_TARGET_KEY);

                    int targetsCount = rawTargets.length();
                    List<AppLink.Target> targets = new ArrayList<AppLink.Target>(targetsCount);

                    for (int i = 0; i < targetsCount; i++) {
                      AppLink.Target target = getAndroidTargetFromJson(rawTargets.getJSONObject(i));
                      if (target != null) {
                        targets.add(target);
                      }
                    }

                    Uri webFallbackUrl = getWebFallbackUriFromJson(uri, appLinkData);
                    AppLink appLink = new AppLink(uri, targets, webFallbackUrl);

                    appLinkResults.put(uri, appLink);
                    synchronized (cachedAppLinks) {
                      cachedAppLinks.put(uri, appLink);
                    }
                  } catch (JSONException e) {
                    // The data for this uri was missing or badly formed.
                    continue;
                  }
                }

                taskCompletionSource.setResult(appLinkResults);
              }
            });

    appLinkRequest.executeAsync();

    return taskCompletionSource.getTask();
  }