@Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.facebook_login_ui);

    // start login sub activity
    loghelper = FacebookLoginHelper.instance(this);
    handler = new LoginHandler();

    facebook_info_span = (View) this.findViewById(R.id.facebook_info_span);
    facebook_info = (TextView) this.findViewById(R.id.facebook_info);
    facebook_info_span.setVisibility(View.VISIBLE);
    orm = SocialORM.instance(this);
    boolean forinvalidsession = getIntent().getBooleanExtra("forinvalidsession", false);
    if (forinvalidsession) {
      Log.d(TAG, "for invalid session issue=" + this);
      loghelper.clearSesion();
      AccountListener.AccountManager.logout();
    }

    // for UI
    email = (EditText) this.findViewById(R.id.facebook_login_email);
    email.setHint(R.string.facebook_email_address);
    pwd = (EditText) this.findViewById(R.id.facebook_login_pwd);
    pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
    pwd.setHint(R.string.facebook_password);

    login = (Button) this.findViewById(R.id.facebook_login_ok_button);
    sign_up = (Button) this.findViewById(R.id.facebook_login_sign_up_button);

    Paint p = login.getPaint();
    float width1 = p.measureText(login.getText().toString());
    p = null;

    p = sign_up.getPaint();
    float width2 = p.measureText(sign_up.getText().toString());
    int width = Math.round(Math.max(width1, width1));

    width = width + 40;
    login.getLayoutParams().width = width;
    sign_up.getLayoutParams().width = width;
    p = null;

    login.setText(R.string.facebook_login_ok);
    sign_up.setText(R.string.facebook_login_sign_up);
    checkbox_sync_phonebook = (CheckBox) this.findViewById(R.id.checkbox_sync_phonebook);
    checkbox_sync_phonebook.setChecked(orm.isEnableSyncPhonebook());
    checkbox_sync_phonebook.setOnCheckedChangeListener(checkedListener);

    login.setOnClickListener(loginClick);
    sign_up.setOnClickListener(signupClick);

    SocialORM.Account ac = orm.getFacebookAccount();
    email.setText(ac.email);
    pwd.setText(ac.password);

    setTitle(R.string.menu_title_login);
  }
 void recordPermSession(FacebookSession tmps, SocialORM orm) {
   loghelper.recordPermanantSession(
       tmps.getSessionKey(), tmps.getSecretKey(), tmps.getLogerInUserID());
   // clear user data
   Log.d(TAG, "clear the pre-user data, this will need some time");
   // if the account is not changes, still have no necessary to clear the data
   String pre_account = orm.getSettingValue(SocialORM.pre_account);
   SocialORM.Account ac = orm.getFacebookAccount();
   if (pre_account == null || pre_account.equalsIgnoreCase(ac.email)) {
     Log.d(TAG, "we are the same account=" + pre_account);
     // if it is the same account, no need to remove the cache data,
     // if the user want to clear the history data,
     // she/he can use the "advanced setting" to reset the database
   } else {
     Log.d(TAG, "we are different account=" + pre_account);
     orm.clearCurrentUserData();
     TwitterHelper.ClearCache();
   }
   // update pre account
   orm.addSetting(SocialORM.pre_account, ac.email);
 }
 public void onClick(View v) {
   hideInputKeyBoard(v);
   // validate the input
   String emailStr = email.getText().toString().trim();
   String pwdStr = pwd.getText().toString().trim();
   if (emailStr.length() == 0 || pwdStr.length() == 0) {
     setHint("Please input email and password.");
   } else {
     // update to db
     orm.updateFacebookAccount(emailStr, pwdStr);
     startThread();
   }
 }
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
   Log.d("checked", "is checked=" + isChecked);
   if (isChecked == true) {
     checkbox_sync_phonebook.setOnCheckedChangeListener(null);
     Message msg = handler.obtainMessage(EBABLE_CHECK);
     msg.getData().putBoolean("fromlogin", true);
     checkbox_sync_phonebook.setChecked(false);
     SyncAddressBookHelper.processSyncAddressBook(
         FacebookLoginActivity.this, isChecked, null, msg);
   } else {
     orm.EnableSyncPhonebook(false);
   }
 }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    switch (requestCode) {
      case LOGIN_WEBVIEW:
        {
          Log.d(TAG, "come back from WebView");

          boolean failtologin = true;
          if (resultCode == 100 || resultCode == 101) // reset the session
          {
            failtologin = false;
            // try to get session
            GetSessionThread sessionThread = new GetSessionThread(handler);
            sessionThread.start();
          } else if (resultCode == 1000) {
            Log.d(TAG, "user choose to exit the login process");
            FacebookLoginActivity.this.setResult(1000);
            sendMessageToService(false);
          } else {
            // TODO
            // FAIL to login?
            Log.d(TAG, "fail to login in resultCode=" + resultCode);
            FacebookLoginActivity.this.setResult(200);
            sendMessageToService(false);
          }

          if (failtologin) {
            quitLooperAndFinish();
          }

          break;
        }
      case FACEBOOK_SETTING:
        {
          Log.d(TAG, "after FACEBOOK_SETTING");

          // reset the UI from database
          if (resultCode == 1000) {
            SocialORM.Account ac = orm.getFacebookAccount();
            email.setText(ac.email);
            pwd.setText(ac.password);
          }
          // startThread();
          break;
        }
    }
  }
    public void run() {
      handler.post(
          new Runnable() {
            public void run() {
              FacebookLoginActivity.this.setTitle(R.string.facebook_getsession_title);
              facebook_info.setText(R.string.facebook_getsession_wait_message);
            }
          });

      Log.d(TAG, "reconstrcut the facebook session");
      FacebookSession tmps = null;
      try {
        tmps = loghelper.getDesktopApp().requestSession(token);

        handler.post(
            new Runnable() {
              public void run() {
                facebook_info.setText(R.string.facebook_getsession_successed);
              }
            });
      } catch (FacebookException e) {
        Log.e(TAG, "fail to get facebook session=" + e.getMessage());
        handler.post(
            new Runnable() {
              public void run() {
                facebook_info.setText(R.string.facebook_fail_to_get_session);
                FacebookLoginActivity.this.setResult(200);
                sendMessageToService(false);
                quitLooperAndFinish();
              }
            });
        return;
      }
      // save into database
      String Sessionkey = tmps.getSessionKey();
      String secretKey = tmps.getSecretKey();
      long userId = tmps.getLogerInUserID();
      loghelper.recordTmpSession(Sessionkey, secretKey, userId);
      SocialORM orm = new SocialORM(FacebookLoginActivity.this);

      boolean persm = false;
      try {
        handler.post(
            new Runnable() {
              public void run() {
                facebook_info.setText(R.string.facebook_make_session_permanent);
              }
            });
        persm =
            tmps.AuthLogin(
                tmps.getSessionKey(),
                FacebookLoginHelper.SECRET_KEY,
                loghelper.getEmail(),
                loghelper.getPwd());

        handler.post(
            new Runnable() {
              public void run() {
                facebook_info.setText(R.string.facebook_make_session_permanent_suc);
              }
            });
      } catch (FacebookException kke) {
        Log.d(TAG, "fail to get perm session=" + kke.getMessage());
      }

      if (true == persm) {
        recordPermSession(tmps, orm);
      } else {
        Log.d(TAG, "fail to get permnant session");
        if (orm.isUsePermanentSeesion() == false) {
          Log.d(TAG, "fail to get permnant session, use tmp session");
          recordPermSession(tmps, orm);
        } else {
          handler.post(
              new Runnable() {
                public void run() {
                  Toast.makeText(
                          FacebookLoginActivity.this,
                          R.string.facebook_get_permanent_session_failed,
                          Toast.LENGTH_LONG)
                      .show();
                }
              });
        }
      }

      // reset the session and async in activity
      AccountManager.login();

      handler.post(
          new Runnable() {
            public void run() {
              FacebookLoginActivity.this.setResult(100);
              sendMessageToService(true);
            }
          });

      handler.post(
          new Runnable() {
            public void run() {
              quitLooperAndFinish();
            }
          });
    }
  void auth_login() {
    isInProcess = true;
    setButtonEnable(false);
    Log.d(TAG, "reconstrcut the facebook session");
    final FacebookSession tmps;
    boolean persm = false;
    try {
      setHint(getString(R.string.verify_account_hint));
      tmps = loghelper.getDesktopApp().AuthLoginNoSession(loghelper.getEmail(), loghelper.getPwd());
    } catch (FacebookException e) {
      Log.e(TAG, "fail to get facebook session=" + e.getMessage());
      handler.post(
          new Runnable() {
            public void run() {
              facebook_info.setText(R.string.facebook_fail_to_get_session);
              // FacebookLoginActivity.this.setResult(200);
              // sendMessageToService(false);
              // quitLooperAndFinish();
            }
          });
      mHandler.obtainMessage(QUIT_THREAD).sendToTarget();
      isInProcess = false;
      setButtonEnable(true);
      return;
    }
    try {
      persm =
          tmps.AuthLogin(
              tmps.getSessionKey(),
              FacebookLoginHelper.SECRET_KEY,
              loghelper.getEmail(),
              loghelper.getPwd());
    } catch (FacebookException e) {
      Log.e(TAG, "Fail to get permanant session, ignore this step.");
    }
    setHint(getString(R.string.verify_account_suc_hint));

    // get login info in background

    // save into database
    String Sessionkey = tmps.getSessionKey();
    String secretKey = tmps.getSecretKey();
    long userId = tmps.getLogerInUserID();
    loghelper.recordTmpSession(Sessionkey, secretKey, userId);
    SocialORM orm = SocialORM.instance(FacebookLoginActivity.this);

    if (true == persm) {
      recordPermSession(tmps, orm);
    } else {
      Log.d(TAG, "fail to get permnant session");
      if (orm.isUsePermanentSeesion() == false) {
        Log.d(TAG, "fail to get permnant session, use tmp session");
        recordPermSession(tmps, orm);
      } else {
        handler.post(
            new Runnable() {
              public void run() {
                Toast.makeText(
                        FacebookLoginActivity.this,
                        R.string.facebook_get_permanent_session_failed,
                        Toast.LENGTH_LONG)
                    .show();
              }
            });
      }
    }

    // reset the session and async in activity
    AccountManager.login();

    handler.post(
        new Runnable() {
          public void run() {
            FacebookLoginActivity.this.setResult(100);
            sendMessageToService(true);
          }
        });

    handler.post(
        new Runnable() {
          public void run() {
            quitLooperAndFinish();
          }
        });

    isInProcess = false;
    setButtonEnable(true);
  }