Пример #1
0
  /**
   * Generate a UI dialog for the request action in the given Android context with the provided
   * parameters.
   *
   * <p>Note that this method is asynchronous and the callback will be invoked in the original
   * calling thread (not in a background thread).
   *
   * @param context The Android context in which we will generate this dialog.
   * @param action String representation of the desired method: e.g. "feed" ...
   * @param parameters String key-value pairs to be passed as URL parameters.
   * @param listener Callback interface to notify the application when the dialog has completed.
   */
  public void dialog(
      Context context, String action, Bundle parameters, final DialogListener listener) {

    String endpoint = DIALOG_BASE_URL + action;
    parameters.putString("display", "touch");
    parameters.putString("redirect_uri", REDIRECT_URI);

    if (action.equals(LOGIN)) {
      parameters.putString("type", "user_agent");
      parameters.putString("client_id", mAppId);
    } else {
      parameters.putString("app_id", mAppId);
    }

    if (isSessionValid()) {
      parameters.putString(TOKEN, getAccessToken());
    }
    String url = endpoint + "?" + Util.encodeUrl(parameters);
    if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET)
        != PackageManager.PERMISSION_GRANTED) {
      Util.showAlert(context, "Error", "Application requires permission to access the Internet");
    } else {
      new FbDialog(context, url, listener).show();
    }
  }
Пример #2
0
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      Util.logd("Facebook-WebView", "Redirect URL: " + url);
      if (url.startsWith(Facebook.REDIRECT_URI)) {
        Bundle values = Util.parseUrl(url);

        String error = values.getString("error");
        if (error == null) {
          error = values.getString("error_type");
        }

        if (error == null) {
          mListener.onComplete(values);
        } else if (error.equals("access_denied") || error.equals("OAuthAccessDeniedException")) {
          mListener.onCancel();
        } else {
          mListener.onFacebookError(new FacebookError(error));
        }

        FbDialog.this.dismiss();
        return true;
      } else if (url.startsWith(Facebook.CANCEL_URI)) {
        mListener.onCancel();
        FbDialog.this.dismiss();
        return true;
      } else if (url.contains(DISPLAY_STRING)) {
        return false;
      }
      // launch non-dialog URLs in a full browser
      getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
      return true;
    }
    public void onComplete(final String response, final Object state) {
      try {
        // process the response here: executed in background thread
        Log.d("Facebook-Example", "Response: " + response.toString());
        JSONObject json = Util.parseJson(response);
        final String name = json.getString("name");

        // then post the processed result back to the UI thread
        // if we do not do this, an runtime exception will be generated
        // e.g. "CalledFromWrongThreadException: Only the original
        // thread that created a view hierarchy can touch its views."
        MainScreen.this.runOnUiThread(
            new Runnable() {
              public void run() {
                lblWelcome.setText("Welcome, " + name);
                Utility.strUsername = name;
                layoutForm.setVisibility(View.VISIBLE);
              }
            });
      } catch (JSONException e) {
        Log.w("Facebook-Example", "JSON Error in response");
      } catch (FacebookError e) {
        Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
      }
    }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
      Util.showAlert(
          this,
          "Warning",
          "Facebook Applicaton ID must be "
              + "specified before running this example: see Example.java");
    }

    setContentView(R.layout.main);
    mLoginButton = (LoginButton) findViewById(R.id.login);
    mText = (TextView) FacebookApplicationActivity.this.findViewById(R.id.txt);
    mUserPic = (ImageView) FacebookApplicationActivity.this.findViewById(R.id.user_pic);
    //       	mFacebook = new Facebook(APP_ID);
    Utility.mFacebook = new Facebook(APP_ID);
    // Instantiate the asynrunner object for asynchronous api calls.
    Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
    SessionStore.restore(mFacebook, this);
    SessionEvents.addAuthListener(new FbAPIsAuthListener());
    SessionEvents.addLogoutListener(new FbAPIsLogoutListener());
    mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);

    if (Utility.mFacebook.isSessionValid()) {
      requestUserData();
    }

    list = (ListView) findViewById(R.id.main_list);

    list.setOnItemClickListener(this);
    list.setAdapter(new ArrayAdapter<String>(this, R.layout.main_list_item, main_items));
  }
Пример #5
0
 protected Void b(Void[] paramArrayOfVoid) {
   try {
     Settings.publishInstallAndWait(this.kz, this.ky);
     return null;
   } catch (Exception localException) {
     while (true) Util.logd("Facebook-publish", localException.getMessage());
   }
 }
Пример #6
0
 /**
  * Invalidate the current user session by removing the access token in memory, clearing the
  * browser cookie, and calling auth.expireSession through the API.
  *
  * <p>Note that this method blocks waiting for a network response, so do not call it in a UI
  * thread.
  *
  * @param context The Android context in which the logout should be called: it should be the same
  *     context in which the login occurred in order to clear any stored cookies
  * @throws IOException
  * @throws MalformedURLException
  * @return JSON string representation of the auth.expireSession response ("true" if successful)
  */
 public String logout(Context context) throws MalformedURLException, IOException {
   Util.clearCookies(context);
   Bundle b = new Bundle();
   b.putString("method", "auth.expireSession");
   String response = request(b);
   setAccessToken(null);
   setAccessExpires(0);
   return response;
 }
Пример #7
0
 /**
  * Synchronously make a request to the Facebook Graph API with the given HTTP method and string
  * parameters. Note that binary data parameters (e.g. pictures) are not yet supported by this
  * helper function.
  *
  * <p>See http://developers.facebook.com/docs/api
  *
  * <p>Note that this method blocks waiting for a network response, so do not call it in a UI
  * thread.
  *
  * @param graphPath Path to resource in the Facebook graph, e.g., to fetch data about the
  *     currently logged authenticated user, provide "me", which will fetch
  *     http://graph.facebook.com/me
  * @param params Key-value string parameters, e.g. the path "search" with parameters {"q" :
  *     "facebook"} would produce a query for the following graph resource:
  *     https://graph.facebook.com/search?q=facebook
  * @param httpMethod http verb, e.g. "GET", "POST", "DELETE"
  * @throws IOException
  * @throws MalformedURLException
  * @return JSON string representation of the response
  */
 public String request(String graphPath, Bundle params, String httpMethod)
     throws FileNotFoundException, MalformedURLException, IOException {
   params.putString("format", "json");
   if (isSessionValid()) {
     params.putString(TOKEN, getAccessToken());
   }
   String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL;
   return Util.openUrl(url, httpMethod, params);
 }
Пример #8
0
 @Override
 public void onPageStarted(WebView view, String url, Bitmap favicon) {
   Util.logd("Facebook-WebView", "Webview loading URL: " + url);
   super.onPageStarted(view, url, favicon);
   try {
     mSpinner.show();
   } catch (Exception ignored) {
   }
 }
 @Override
 protected Void doInBackground(Void... voids) {
   try {
     Facebook.publishInstall(Facebook.this, mApplicationId, mApplicationContext);
   } catch (Exception e) {
     Util.logd("Facebook-publish", e.getMessage());
   }
   return null;
 }
 /**
  * Manually publish install attribution to the facebook graph. Internally handles tracking repeat
  * calls to prevent multiple installs being published to the graph.
  *
  * @param context
  * @return returns false on error. Applications should retry until true is returned. Safe to call
  *     again after true is returned.
  */
 public boolean publishInstall(final Context context) {
   try {
     // copy the application id to guarantee thread safety..
     String applicationId = mAppId;
     if (applicationId != null) {
       publishInstall(this, applicationId, context);
       return true;
     }
   } catch (Exception e) {
     // if there was an error, fall through to the failure case.
     Util.logd("Facebook-publish", e.getMessage());
   }
   return false;
 }
 public void onComplete(final String response, final Object state) {
   Log.d("Facebook-FacebookInterfaceActivity", "Got response: " + response);
   String message = "<empty>";
   try {
     JSONObject json = Util.parseJson(response);
     message = json.getString("message");
   } catch (JSONException e) {
     Log.w("Facebook-FacebookInterfaceActivity", "JSON Error in response");
   } catch (FacebookError e) {
     Log.w("Facebook-FacebookInterfaceActivity", "Facebook Error: " + e.getMessage());
   }
   final String text = "Your Wall Post: " + message;
   FacebookInterfaceActivity.this.runOnUiThread(
       new Runnable() {
         public void run() {
           mText.setText(text);
         }
       });
 }
  /**
   * This function does the heavy lifting of publishing an install.
   *
   * @param fb
   * @param applicationId
   * @param context
   * @throws Exception
   */
  private static void publishInstall(
      final Facebook fb, final String applicationId, final Context context)
      throws JSONException, FacebookError, MalformedURLException, IOException {

    String attributionId = Facebook.getAttributionId(context.getContentResolver());
    SharedPreferences preferences =
        context.getSharedPreferences(ATTRIBUTION_PREFERENCES, Context.MODE_PRIVATE);
    String pingKey = applicationId + "ping";
    long lastPing = preferences.getLong(pingKey, 0);
    if (lastPing == 0 && attributionId != null) {
      Bundle supportsAttributionParams = new Bundle();
      supportsAttributionParams.putString(APPLICATION_FIELDS, SUPPORTS_ATTRIBUTION);
      JSONObject supportResponse =
          Util.parseJson(fb.request(applicationId, supportsAttributionParams));
      Object doesSupportAttribution = (Boolean) supportResponse.get(SUPPORTS_ATTRIBUTION);

      if (!(doesSupportAttribution instanceof Boolean)) {
        throw new JSONException(
            String.format(
                "%s contains %s instead of a Boolean",
                SUPPORTS_ATTRIBUTION, doesSupportAttribution));
      }

      if ((Boolean) doesSupportAttribution) {
        Bundle publishParams = new Bundle();
        publishParams.putString(ANALYTICS_EVENT, MOBILE_INSTALL_EVENT);
        publishParams.putString(ATTRIBUTION_KEY, attributionId);

        String publishUrl = String.format(PUBLISH_ACTIVITY_PATH, applicationId);

        fb.request(publishUrl, publishParams, "POST");

        // denote success since no error threw from the post.
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong(pingKey, System.currentTimeMillis());
        editor.commit();
      }
    }
  }
    public void onComplete(final String response, final Object state) {
      try {
        // process the response here: (executed in background thread)
        Log.d("Facebook-FacebookInterfaceActivity", "Response: " + response.toString());
        JSONObject json = Util.parseJson(response);
        final String src = json.getString("src");

        // then post the processed result back to the UI thread
        // if we do not do this, an runtime exception will be generated
        // e.g. "CalledFromWrongThreadException: Only the original
        // thread that created a view hierarchy can touch its views."
        FacebookInterfaceActivity.this.runOnUiThread(
            new Runnable() {
              public void run() {
                mText.setText("Hello there, photo has been uploaded at \n" + src);
              }
            });
      } catch (JSONException e) {
        Log.w("Facebook-FacebookInterfaceActivity", "JSON Error in response");
      } catch (FacebookError e) {
        Log.w("Facebook-FacebookInterfaceActivity", "Facebook Error: " + e.getMessage());
      }
    }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
      Util.showAlert(
          this,
          "Warning",
          "Facebook Applicaton ID must be "
              + "specified before running this example: see FacebookInterfaceActivity.java");
    }

    setContentView(R.layout.facebook);
    mLoginButton = (LoginButton) findViewById(R.id.login);
    mText = (TextView) FacebookInterfaceActivity.this.findViewById(R.id.txt);
    mRequestButton = (Button) findViewById(R.id.requestButton);
    mPostButton = (Button) findViewById(R.id.postButton);
    mDeleteButton = (Button) findViewById(R.id.deletePostButton);
    mUploadButton = (Button) findViewById(R.id.uploadButton);

    mFacebook = new Facebook(APP_ID);
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);

    SessionStore.restore(mFacebook, this);
    SessionEvents.addAuthListener(new SampleAuthListener());
    SessionEvents.addLogoutListener(new SampleLogoutListener());
    mLoginButton.init(this, mFacebook);

    mRequestButton.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            mAsyncRunner.request("me", new SampleRequestListener());
          }
        });
    mRequestButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mUploadButton.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            Bundle params = new Bundle();
            params.putString("method", "photos.upload");

            URL uploadFileUrl = null;
            try {
              uploadFileUrl =
                  new URL("http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
            } catch (MalformedURLException e) {
              e.printStackTrace();
            }
            try {
              HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection();
              conn.setDoInput(true);
              conn.connect();
              int length = conn.getContentLength();

              byte[] imgData = new byte[length];
              InputStream is = conn.getInputStream();
              is.read(imgData);
              params.putByteArray("picture", imgData);

            } catch (IOException e) {
              e.printStackTrace();
            }

            mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
          }
        });
    mUploadButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mPostButton.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            mFacebook.dialog(FacebookInterfaceActivity.this, "feed", new SampleDialogListener());
          }
        });
    mPostButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);
  }
      @Override
      public void onComplete(String response, Object state) {
        try {
          Log.i(TAG, response);
          json = Util.parseJson(response);

          // photos are in the form of a json array
          child = json.getJSONArray("data");

          int total = child.length();

          // contains links to photos
          links = new ArrayList<String>(total);

          // adds link to each photo to our list after replacing the "https" from url
          // DownloadManager does not support https in gingerbread
          for (int i = 0; i < total; i++) {
            photo_json = child.getJSONObject(i);

            if (dl_high_res_pics) {
              JSONArray image_set = photo_json.getJSONArray("images");

              // highest resolution picture has the index zero in the images jsonarray
              JSONObject highest_res_pic = image_set.getJSONObject(0);
              String http_replaced =
                  highest_res_pic.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            } else {
              // source property of the json object points to the photo's link
              String http_replaced = photo_json.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            }
          }

          download_photos.this.runOnUiThread(
              new Runnable() {
                public void run() {
                  //	mytask = new DownloadImageTask();
                  //	mytask.execute(links);
                  // start downloading using asynctask
                  // new DownloadImageTask().execute(links);
                  // downloadThread.setPath(path);
                  // downloadThread.setWholeTasks(links.size());
                  if (resume_file.exists()) {

                    initial_value = readProgress()[0];
                    final_value = links.size();
                    // case if the task is already completed
                    if (initial_value == final_value) {
                      completed = true;
                      resume_pause.setVisibility(View.GONE);

                      progress_download.setMax(final_value);
                      progress_download.setProgress(0); // bug in progress bar
                      progress_download.setProgress(initial_value);

                      progress_text.setText("Completed.");
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");

                    }

                    // case if some of the photos are already downloaded
                    else {
                      progress_download.setMax(links.size());
                      // progress_download.setProgress(0);	//bug in progress bar
                      progress_download.setProgress(initial_value);

                      // N.B if i= initial_value -1, then one image will be downloaded again. so to
                      // save cost we start with i = initial_value
                      for (int i = initial_value; i < links.size(); i++) {
                        mtext.setText(
                            getText(R.string.download_textview_message_1)
                                + " "
                                + path.toString()
                                + ". ");
                        // downloadThread.setRunningTask(i + 1);
                        downloadThread.enqueueDownload(
                            new DownloadTask(
                                links.get(i), path, i + 1, final_value, download_photos.this));
                      }
                    }
                  }

                  // case if the task is entirely new task
                  else {
                    for (int i = 0; i < links.size(); i++) {
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");
                      // downloadThread.setRunningTask(i + 1);
                      downloadThread.enqueueDownload(
                          new DownloadTask(
                              links.get(i), path, i + 1, links.size(), download_photos.this));
                    }
                  }
                }
              });
        } catch (JSONException ex) {
          Log.e(TAG, "JSONEXception : " + ex.getMessage());
        }
      }
Пример #16
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.context = this;
    setContentView(R.layout.main);

    // Without application id further processing cannot happen. APP_ID can be obtained from the
    // developers.facebook/apps page.
    if (APP_ID == null) {
      Util.showAlert(context, "Error", "Facebook application id is required");
    }

    // Facebook sesssion initialization
    mFacebook = new Facebook(APP_ID);

    // Check if previously obtained access token exists, in which case use the same.
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);
    if (access_token != null) {
      mFacebook.setAccessToken(access_token);
    }
    if (expires != 0) {
      mFacebook.setAccessExpires(expires);
    }

    // Authentication from previously fetched accessed token
    if (mFacebook.isSessionValid()) {
      makeToast("Authorization complete. Values fetched from preferences");
      Bundle params = new Bundle();
      params.putString("fields", "name,id");
      mAsyncRunner = new AsyncFacebookRunner(mFacebook);
      mAsyncRunner.request("me", params, new UserRequestListener());
    }

    // Only call authorize if the access_token has expired.
    if (!mFacebook.isSessionValid()) {
      mFacebook.authorize(
          this,
          PERMISSIONS,
          new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
              SharedPreferences.Editor editor = mPrefs.edit();
              editor.putString("access_token", mFacebook.getAccessToken());
              editor.putLong("access_expires", mFacebook.getAccessExpires());
              editor.commit();

              // Authorization complete after fetching new token from facebook
              makeToast("Authorization complete. Connected to Facebook servers");

              Bundle params = new Bundle();
              params.putString("fields", "name,id");
              mAsyncRunner = new AsyncFacebookRunner(mFacebook);
              mAsyncRunner.request("me", params, new UserRequestListener());
            }

            @Override
            public void onFacebookError(FacebookError error) {
              makeToast(error.getMessage());
            }

            @Override
            public void onError(DialogError e) {
              makeToast(e.getMessage());
            }

            @Override
            public void onCancel() {
              makeToast("Exception in onCancel()");
            }
          });
    }
  }
  public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
    switch (position) {
      case 2:
        {
          if (!Utility.mFacebook.isSessionValid()) {
            Util.showAlert(this, "Warning", "You must first log in.");
          } else {
            dialog =
                ProgressDialog.show(
                    FacebookApplicationActivity.this,
                    "",
                    getString(R.string.please_wait),
                    true,
                    true);
            new AlertDialog.Builder(this)
                .setTitle(R.string.Graph_FQL_title)
                .setMessage(R.string.Graph_FQL_msg)
                .setPositiveButton(
                    R.string.graph_button,
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        graph_or_fql = "graph";
                        Bundle params = new Bundle();
                        params.putString("fields", "name, picture, location");
                        Utility.mAsyncRunner.request(
                            "me/friends", params, new FriendsRequestListener());
                      }
                    })
                .setNegativeButton(
                    R.string.fql_button,
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        graph_or_fql = "fql";
                        String query =
                            "select name, current_location, uid, pic_square from user where uid in (select uid2 from friend where uid1=me()) order by name";
                        Bundle params = new Bundle();
                        params.putString("method", "fql.query");
                        params.putString("query", query);
                        Utility.mAsyncRunner.request(null, params, new FriendsRequestListener());
                      }
                    })
                .setOnCancelListener(
                    new DialogInterface.OnCancelListener() {
                      @Override
                      public void onCancel(DialogInterface d) {
                        dialog.dismiss();
                      }
                    })
                .show();
          }
          break;
        }

        /*
         * Source Tag: upload_photo You can upload a photo from the media
         * gallery or from a remote server How to upload photo:
         * https://developers.facebook.com/blog/post/498/
         */
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    if (Utility.APP_ID == null) {
      Util.showAlert(
          this,
          "Warning",
          "Facebook Applicaton ID must be "
              + "specified before running this example: see Example.java");
    }

    setContentView(R.layout.main);

    /* Get Handles for all the controls on the screen which needs
     * manipulation
     */
    mLoginButton = (LoginButton) findViewById(R.id.login);
    btnSearchHotel = (Button) findViewById(R.id.btnSearch);
    lblWelcome = (TextView) findViewById(R.id.lblWelcome);
    txtCityName = (EditText) findViewById(R.id.txtCityName);
    layoutForm = (LinearLayout) findViewById(R.id.layoutForm);
    layoutForm.setVisibility(View.INVISIBLE);

    // Create an instance of Facebook object, passing the APP ID.
    Utility.mFacebook = new Facebook(Utility.APP_ID);

    Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);

    SessionStore.restore(Utility.mFacebook, this);
    SessionEvents.addAuthListener(new SampleAuthListener());
    SessionEvents.addLogoutListener(new SampleLogoutListener());
    mLoginButton.init(this, Utility.mFacebook);

    Spinner spin = (Spinner) findViewById(R.id.ddlHotelChain);
    spin.setOnItemSelectedListener(
        new OnItemSelectedListener() {

          public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // Set the Hotel Chain selected.
            strHotelChain = items_hotel_chain[position];
          }

          public void onNothingSelected(AdapterView<?> arg0) {
            // So, nothing comes here. ;)
          }
        });

    @SuppressWarnings({"rawtypes", "unchecked"})
    ArrayAdapter aa =
        new ArrayAdapter(this, android.R.layout.simple_spinner_item, items_hotel_chain);

    aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spin.setAdapter(aa);

    btnSearchHotel.setOnClickListener(
        new OnClickListener() {

          public void onClick(View v) {
            // If city name is entered, call new intent by passing,
            // city name and hotel chain to the new intent.
            if (!txtCityName.getText().toString().trim().equals("")) {
              Intent i = new Intent(getBaseContext(), HotelList.class);
              i.putExtra("cityName", txtCityName.getText().toString().replace(" ", "+").trim());
              i.putExtra("hotelChain", strHotelChain);
              startActivity(i);
            }
            // City name cannot be empty, so tell the user.
            else {
              Toast.makeText(getBaseContext(), "Please enter city name", Toast.LENGTH_SHORT).show();
            }
          }
        });

    if (Utility.mFacebook.isSessionValid()) {
      lblWelcome.setText("Welcome, " + Utility.strUsername);
      layoutForm.setVisibility(View.VISIBLE);
    }
  }
Пример #19
0
  @Override
  public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
    switch (position) {
        /*
         * Source Tag: update_status_tag
         * Update user's status by invoking the feed dialog
         * To post to a friend's wall, provide his uid in the 'to' parameter
         * Refer to https://developers.facebook.com/docs/reference/dialogs/feed/ for more info.
         */
      case 0:
        {
          Bundle params = new Bundle();
          params.putString("caption", getString(R.string.app_name));
          params.putString("description", getString(R.string.app_desc));
          params.putString("picture", Utility.HACK_ICON_URL);
          params.putString("name", getString(R.string.app_action));

          Utility.mFacebook.dialog(Hackbook.this, "feed", params, new UpdateStatusListener());
          String access_token = Utility.mFacebook.getAccessToken();
          System.out.println(access_token);
          break;
        }

        /*
         * Source Tag: app_requests
         * Send an app request to friends. If no friend is specified, the user will see a friend selector and will be able to select a maximum of 50 recipients.
         * To send request to specific friend, provide the uid in the 'to' parameter
         * Refer to https://developers.facebook.com/docs/reference/dialogs/requests/ for more info.
         */
      case 1:
        {
          Bundle params = new Bundle();
          params.putString("message", getString(R.string.request_message));
          Utility.mFacebook.dialog(Hackbook.this, "apprequests", params, new AppRequestsListener());
          break;
        }

        /*
         * Source Tag: friends_tag
         * You can get friends using graph.facebook.com/me/friends, this returns the list sorted by UID
         * OR
         * using the friend table. With this you can sort the way you want it.
         * friend table - https://developers.facebook.com/docs/reference/fql/friend/
         * user table - https://developers.facebook.com/docs/reference/fql/user/
         */
      case 2:
        {
          if (!Utility.mFacebook.isSessionValid()) {
            Util.showAlert(this, "Warning", "You must first log in.");
          } else {
            dialog =
                ProgressDialog.show(Hackbook.this, "", getString(R.string.please_wait), true, true);
            new AlertDialog.Builder(this)
                .setTitle(R.string.Graph_FQL_title)
                .setMessage(R.string.Graph_FQL_msg)
                .setPositiveButton(
                    R.string.graph_button,
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        graph_or_fql = "graph";
                        Bundle params = new Bundle();
                        params.putString("fields", "name, picture, location");
                        Utility.mAsyncRunner.request(
                            "me/friends", params, new FriendsRequestListener());
                      }
                    })
                .setNegativeButton(
                    R.string.fql_button,
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        graph_or_fql = "fql";
                        String query =
                            "select name, current_location, uid, pic_square from user where uid in (select uid2 from friend where uid1=me()) order by name";
                        Bundle params = new Bundle();
                        params.putString("method", "fql.query");
                        params.putString("query", query);
                        Utility.mAsyncRunner.request(null, params, new FriendsRequestListener());
                      }
                    })
                .setOnCancelListener(
                    new DialogInterface.OnCancelListener() {
                      @Override
                      public void onCancel(DialogInterface d) {
                        dialog.dismiss();
                      }
                    })
                .show();
          }
          break;
        }

        /*
         * Source Tag: upload_photo
         * You can upload a photo from the media gallery or from a remote server
         * How to upload photo: https://developers.facebook.com/blog/post/498/
         */
      case 3:
        {
          if (!Utility.mFacebook.isSessionValid()) {
            Util.showAlert(this, "Warning", "You must first log in.");
          } else {
            dialog =
                ProgressDialog.show(Hackbook.this, "", getString(R.string.please_wait), true, true);
            new AlertDialog.Builder(this)
                .setTitle(R.string.gallery_remote_title)
                .setMessage(R.string.gallery_remote_msg)
                .setPositiveButton(
                    R.string.gallery_button,
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        Intent intent =
                            new Intent(
                                Intent.ACTION_PICK, (MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
                        startActivityForResult(intent, PICK_EXISTING_PHOTO_RESULT_CODE);
                      }
                    })
                .setNegativeButton(
                    R.string.remote_button,
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        /*
                         * Source tag: upload_photo_tag
                         */
                        Bundle params = new Bundle();
                        params.putString(
                            "url", "http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
                        params.putString("caption", "FbAPIs Sample App photo upload");
                        Utility.mAsyncRunner.request(
                            "me/photos", params, "POST", new PhotoUploadListener(), null);
                      }
                    })
                .setOnCancelListener(
                    new DialogInterface.OnCancelListener() {
                      @Override
                      public void onCancel(DialogInterface d) {
                        dialog.dismiss();
                      }
                    })
                .show();
          }
          break;
        }

        /*
         * User can check-in to a place, you require publish_checkins permission for that.
         * You can use the default Times Square location or fetch user's current location
         * Get user's checkins - https://developers.facebook.com/docs/reference/api/checkin/
         */
      case 4:
        {
          final Intent myIntent = new Intent(getApplicationContext(), Places.class);

          new AlertDialog.Builder(this)
              .setTitle(R.string.get_location)
              .setMessage(R.string.get_default_or_new_location)
              .setPositiveButton(
                  R.string.current_location_button,
                  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      myIntent.putExtra("LOCATION", "current");
                      startActivity(myIntent);
                    }
                  })
              .setNegativeButton(
                  R.string.times_square_button,
                  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      myIntent.putExtra("LOCATION", "times_square");
                      startActivity(myIntent);
                    }
                  })
              .show();
          break;
        }

      case 5:
        {
          if (!Utility.mFacebook.isSessionValid()) {
            Util.showAlert(this, "Warning", "You must first log in.");
          } else {
            new FQLQuery(Hackbook.this).show();
          }
          break;
        }
        /*
         * This is advanced feature where you can request new permissions
         * Browser user's graph, his fields and connections.
         * This is similar to the www version - http://developers.facebook.com/tools/explorer/
         */
      case 6:
        {
          Intent myIntent = new Intent(getApplicationContext(), GraphExplorer.class);
          if (Utility.mFacebook.isSessionValid()) {
            Utility.objectID = "me";
          }
          startActivity(myIntent);
          break;
        }
    }
  }
  /**
   * IMPORTANT: This method must be invoked at the top of the calling activity's onActivityResult()
   * function or Facebook authentication will not function properly!
   *
   * <p>If your calling activity does not currently implement onActivityResult(), you must implement
   * it and include a call to this method if you intend to use the authorize() method in this SDK.
   *
   * <p>For more information, see http://developer.android.com/reference/android/app/
   * Activity.html#onActivityResult(int, int, android.content.Intent)
   */
  public void authorizeCallback(int requestCode, int resultCode, Intent data) {
    if (requestCode == mAuthActivityCode) {

      // Successfully redirected.
      if (resultCode == Activity.RESULT_OK) {

        // Check OAuth 2.0/2.10 error code.
        String error = data.getStringExtra("error");
        if (error == null) {
          error = data.getStringExtra("error_type");
        }

        // A Facebook error occurred.
        if (error != null) {
          if (error.equals(SINGLE_SIGN_ON_DISABLED)
              || error.equals("AndroidAuthKillSwitchException")) {
            Util.logd(
                "Facebook-authorize",
                "Hosted auth currently " + "disabled. Retrying dialog auth...");
            startDialogAuth(mAuthActivity, mAuthPermissions);
          } else if (error.equals("access_denied") || error.equals("OAuthAccessDeniedException")) {
            Util.logd("Facebook-authorize", "Login canceled by user.");
            mAuthDialogListener.onCancel();
          } else {
            String description = data.getStringExtra("error_description");
            if (description != null) {
              error = error + ":" + description;
            }
            Util.logd("Facebook-authorize", "Login failed: " + error);
            mAuthDialogListener.onFacebookError(new FacebookError(error));
          }

          // No errors.
        } else {
          setAccessToken(data.getStringExtra(TOKEN));
          setAccessExpiresIn(data.getStringExtra(EXPIRES));
          if (isSessionValid()) {
            Util.logd(
                "Facebook-authorize",
                "Login Success! access_token="
                    + getAccessToken()
                    + " expires="
                    + getAccessExpires());
            mAuthDialogListener.onComplete(data.getExtras());
          } else {
            mAuthDialogListener.onFacebookError(
                new FacebookError("Failed to receive access token."));
          }
        }

        // An error occurred before we could be redirected.
      } else if (resultCode == Activity.RESULT_CANCELED) {

        // An Android error occured.
        if (data != null) {
          Util.logd("Facebook-authorize", "Login failed: " + data.getStringExtra("error"));
          mAuthDialogListener.onError(
              new DialogError(
                  data.getStringExtra("error"),
                  data.getIntExtra("error_code", -1),
                  data.getStringExtra("failing_url")));

          // User pressed the 'back' button.
        } else {
          Util.logd("Facebook-authorize", "Login canceled by user.");
          mAuthDialogListener.onCancel();
        }
      }
    }
  }