Guest User

RegisterActivity

a guest
May 17th, 2013
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.86 KB | None | 0 0
  1.  
  2.  
  3. public class RegisterActivity extends Activity {
  4.  
  5.     /** DROPBOX KEY AND ACCESSTYPE INFORMATION*/
  6.     ///////////////////////////////////////////////////////////////////////////
  7.     //                      Your app-specific settings.                      //
  8.     ///////////////////////////////////////////////////////////////////////////
  9.     final static private String APP_KEY = "XXXXXXXXX";
  10.     final static private String APP_SECRET = "XXXXXXXXXX";
  11.     final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
  12.     ///////////////////////////////////////////////////////////////////////////
  13.     //                      End app-specific settings.                       //
  14.     ///////////////////////////////////////////////////////////////////////////
  15.     final static private String ACCOUNT_PREFS_NAME = "prefs";
  16.     final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
  17.     final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
  18.     /**--------------------------------------------------------------*/
  19.     public static DropboxAPI<AndroidAuthSession> mDBApi;
  20.     private boolean mLoggedIn;
  21.     private final String TAG = "RegisterActivity";
  22.     private ParseUser user;
  23.     private static final int AUTHENTICATION_NONE = 0;
  24.     private static final int AUTHENTICATION_STARTED = 1;
  25.     private int state = AUTHENTICATION_NONE;
  26.  
  27.     Button btnRegister;
  28.     Button btnLinkToLogin;
  29.     EditText inputNickname;
  30.     EditText inputEmail;
  31.     EditText inputPassword;
  32.     EditText inputRepeatPassword;
  33.     TextView registerErrorMsg;
  34.     ProgressBar registerProgress;
  35.  
  36.     @Override
  37.     public void onCreate(Bundle savedInstanceState) {
  38.         super.onCreate(savedInstanceState);
  39.         setContentView(R.layout.register);
  40.  
  41.         /*Dropbox stuff*/
  42.         AndroidAuthSession session = buildSession();
  43.         mDBApi = new DropboxAPI<AndroidAuthSession>(session);
  44.  
  45.         /*Parse Stuff - Copy and Paste this into every onCreate method to be able to use Parse*/
  46.         Parse.initialize(this, "XXXXXX", "XXXXX");
  47.  
  48.         /*Importing all assets like buttons, text fields*/
  49.         inputNickname = (EditText) findViewById(R.id.registerName);
  50.         inputEmail = (EditText) findViewById(R.id.registerEmail);
  51.         inputPassword = (EditText) findViewById(R.id.registerPassword);
  52.         inputRepeatPassword = (EditText) findViewById(R.id.registerRepeatPassword);
  53.         btnRegister = (Button) findViewById(R.id.btnRegister);
  54.         btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
  55.         registerErrorMsg = (TextView) findViewById(R.id.register_error);
  56.         registerProgress = (ProgressBar) findViewById(R.id.progress);
  57.         registerProgress.setVisibility(4); //set to invisible
  58.  
  59.     }
  60.     /**
  61.      * Registers a new user - if success go to the StartScreen, if fail show error messages
  62.      * @param view
  63.      */
  64.     public void onClickRegister(View view) {
  65.  
  66.         //Showing the progress spinner
  67.         showProgressSpinner();
  68.         String name = inputNickname.getText().toString();
  69.         String email = inputEmail.getText().toString().toLowerCase(); //To avoid case sensitivity problems...
  70.         String password = inputPassword.getText().toString();
  71.         String repeatPassword = inputRepeatPassword.getText().toString();
  72.  
  73.         //My own validation check...
  74.         //TODO: Check if it is possible to compare the two password inputs as an ParseException?
  75.         if(name == null || name.length() == 0) {
  76.             hideProgressSpinner();
  77.             registerErrorMsg.setText("Please enter a valid name");
  78.         } else if (badPassword(password)) {
  79.             hideProgressSpinner();
  80.             registerErrorMsg.setText("Please enter a valid password of minimum 6 characters");
  81.         } else if (!password.equals(repeatPassword)) {
  82.             hideProgressSpinner();
  83.             registerErrorMsg.setText("You password doesn't match. Please try again!");
  84.         }  else {
  85.  
  86.             user = new ParseUser();
  87.             user.setUsername(name.toLowerCase());
  88.             user.put("naturalUsername", name);      //to keep the input username, e.g capital letter
  89.             user.put("globalScore", 0);             //globalScore is set to zero when register
  90.             user.setPassword(password);
  91.             user.setEmail(email);
  92.  
  93.  
  94.             user.signUpInBackground(new SignUpCallback() {
  95.                 @Override
  96.                 public void done(ParseException e) {
  97.                     hideProgressSpinner();
  98.                     if (e == null) {
  99.                         // Successful registration - Launch Start Screen
  100.                         mDBApi.getSession().startAuthentication(RegisterActivity.this); // DROPBOX AUTHENTICATION FOR USER TO ACCEPT IN WEBBROWSER.
  101.                         state = AUTHENTICATION_STARTED;
  102.                     } else {
  103.                         // Sign up didn't succeed. Looking at ParseExceptions...
  104.                         // Found a list of exceptions: https://www.parse.com/docs/android/api/constant-values.html
  105.                         if (e.getCode() == 202) {
  106.                             registerErrorMsg.setText("The username is already in use");
  107.                         } else if (e.getCode() == 203) {
  108.                             registerErrorMsg.setText("The email is already registered");
  109.                         } else if (e.getCode() == 125) {
  110.                             registerErrorMsg.setText("Please enter a valid e-mail");
  111.                         } else if (e.getCode() == 100) {
  112.                             registerErrorMsg.setText("Please check your internet connection!");
  113.                         } else {
  114.                             //Unknown error - Error code until all problems fixed...
  115.                             registerErrorMsg.setText("Oops! Something went wrong. The server says: " + e.getMessage());
  116.                         }
  117.                     }
  118.                 }
  119.             });
  120.         }
  121.     }
  122.  
  123.     /**
  124.      * Go to login screen
  125.      * @param view
  126.      */
  127.     public void onClickLogin(View view) {
  128.         Intent i = new Intent(getApplicationContext(), LoginActivity.class);
  129.         startActivity(i);
  130.         // Close Registration View
  131.         finish();
  132.     }
  133.    
  134.     private boolean badPassword(String password) {
  135.         //Only two criterias for now...
  136.         //TODO Fix stronger restrictions??
  137.         return (password == null || password.length() < 5);
  138.     }
  139.  
  140.     //TODO: Where should we put these, they are used in both RegisterActivity and LoginActivity
  141.     //TODO: Consider using threads instead...
  142.     private void showProgressSpinner() {
  143.         //show the spinner
  144.         registerProgress.setVisibility(0);
  145.         //disable all clickable objects
  146.         btnRegister.setEnabled(false);
  147.         btnLinkToLogin.setEnabled(false);
  148.         inputNickname.setEnabled(false);
  149.         inputEmail.setEnabled(false);
  150.         inputPassword.setEnabled(false);
  151.         inputRepeatPassword.setEnabled(false);
  152.     }
  153.  
  154.     private void hideProgressSpinner() {
  155.         //hide the spinner
  156.         registerProgress.setVisibility(8);
  157.         //re-enable all clickable objects
  158.         btnRegister.setEnabled(true);
  159.         btnLinkToLogin.setEnabled(true);
  160.         inputNickname.setEnabled(true);
  161.         inputEmail.setEnabled(true);
  162.         inputPassword.setEnabled(true);
  163.         inputRepeatPassword.setEnabled(true);
  164.     }
  165.     private void showToast(String msg) {
  166.         Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
  167.         error.show();
  168.     }
  169.     /*
  170.      * FÖRMODLIGEN INTE EN HELT NÖDVÄNDIG METOD. KAN ANVÄNDAS I SETTINGS ACTIVITY SCREEN KAN KANSKE GÅ LIKA BRA MED mDBApi.getSession.isLinked()
  171.      */
  172.     /**
  173.      * Sets logged in.
  174.      * @param loggedIn
  175.      */
  176.     private void setLoggedIn(boolean loggedIn) {
  177.         mLoggedIn = loggedIn;
  178.         if (loggedIn) {
  179.             Log.d(TAG, "Logged In");
  180.         } else {
  181.             Log.d(TAG, "Not Logged In");
  182.         }
  183.     }
  184.     /**
  185.      * TODO: DENNA METODEN BORDE ANROPAS FRÅN VÅR TYP SETTINGS ACTIVITY SCREEN IFALL LÄSAREN DÄR VILL LOGGA UT ELLER TA BORT SITT ACCOUNT.
  186.      * Disconnects the session from Dropbox.
  187.      */
  188.     private void logOut() {
  189.         // Remove credentials from the session
  190.         mDBApi.getSession().unlink();
  191.         // Clear our stored keys
  192.         clearKeys();
  193.         // Change UI state to display logged out version
  194.         setLoggedIn(false);
  195.     }
  196.    
  197.     /** -----------------------------DROPBOX METHODS-----------------------------------*/
  198.     /**
  199.      *
  200.      */
  201.     @Override
  202.     protected void onResume() {
  203.         super.onResume();
  204.         AndroidAuthSession session = mDBApi.getSession();
  205.  
  206.         // The next part must be inserted in the onResume() method of the
  207.         // activity from which session.startAuthentication() was called, so
  208.         // that Dropbox authentication completes properly.
  209.         if (session.authenticationSuccessful()) {
  210.             try {
  211.                 // Mandatory call to complete the authentication.
  212.                 session.finishAuthentication();
  213.                 state = AUTHENTICATION_NONE;
  214.  
  215.                 // Store it locally in our app for later use
  216.                 TokenPair tokens = session.getAccessTokenPair();
  217.                 storeKeys(tokens.key, tokens.secret);
  218.                 setLoggedIn(true);
  219.                
  220.                 Intent dashboard = new Intent(getApplicationContext(), StartScreen.class);
  221.                 //Close all views before launching start screen
  222.                 dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  223.                 startActivity(dashboard);
  224.                 // Close Registration Screen
  225.                 finish();
  226.             } catch (IllegalStateException e) {
  227.                 showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
  228.             }
  229.  
  230.         }
  231.         if (!session.authenticationSuccessful() && state == AUTHENTICATION_STARTED){
  232.             showToast("You denied the DropBox authentication. Registration did not succeed. Try Again");
  233.             state = AUTHENTICATION_NONE;
  234.             try{
  235.                 user.delete();
  236.             }
  237.             catch (ParseException e){
  238.                 Log.d(TAG,"Object does not exist or internet failed " + e.getMessage());
  239.             }      
  240.         }
  241.  
  242.     }
  243.     /**
  244.      * Shows keeping the access keys returned from Trusted Authenticator in a local
  245.      * store, rather than storing user name & password, and re-authenticating each
  246.      * time (which is not to be done, ever).
  247.      *
  248.      * @return Array of [access_key, access_secret], or null if none stored
  249.      */
  250.     private String[] getKeys() {
  251.         SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
  252.         String key = prefs.getString(ACCESS_KEY_NAME, null);
  253.         String secret = prefs.getString(ACCESS_SECRET_NAME, null);
  254.         if (key != null && secret != null) {
  255.             String[] ret = new String[2];
  256.             ret[0] = key;
  257.             ret[1] = secret;
  258.             return ret;
  259.         } else {
  260.             return null;
  261.         }
  262.     }
  263.  
  264.     /**
  265.      *
  266.      * @param key
  267.      * @param secret
  268.      *
  269.      * Shows keeping the access keys returned from Trusted Authenticator in a local
  270.      * store, rather than storing user name & password, and re-authenticating each
  271.      * time (which is not to be done, ever).
  272.      */
  273.     private void storeKeys(String key, String secret) {
  274.         // Save the access key for later
  275.         SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
  276.         Editor edit = prefs.edit();
  277.         edit.putString(ACCESS_KEY_NAME, key);
  278.         edit.putString(ACCESS_SECRET_NAME, secret);
  279.         edit.commit();
  280.     }
  281.     /**
  282.      * Clears the store Dropbox keys.
  283.      */
  284.     private void clearKeys() {
  285.         SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
  286.         Editor edit = prefs.edit();
  287.         edit.clear();
  288.         edit.commit();
  289.     }
  290.     /**
  291.      * Initializes the unique dropbox keys and builds a new session.
  292.      * @return
  293.      */
  294.     private AndroidAuthSession buildSession() {
  295.         AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
  296.         AndroidAuthSession session;
  297.  
  298.         String[] stored = getKeys();
  299.         if (stored != null) {
  300.             AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
  301.             session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
  302.         } else {
  303.             session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
  304.         }
  305.  
  306.         return session;
  307.     }
  308.  
  309.  
  310.  
  311. }
Advertisement
Add Comment
Please, Sign In to add comment