Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class RegisterActivity extends Activity {
- /** DROPBOX KEY AND ACCESSTYPE INFORMATION*/
- ///////////////////////////////////////////////////////////////////////////
- // Your app-specific settings. //
- ///////////////////////////////////////////////////////////////////////////
- final static private String APP_KEY = "XXXXXXXXX";
- final static private String APP_SECRET = "XXXXXXXXXX";
- final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
- ///////////////////////////////////////////////////////////////////////////
- // End app-specific settings. //
- ///////////////////////////////////////////////////////////////////////////
- final static private String ACCOUNT_PREFS_NAME = "prefs";
- final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
- final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
- /**--------------------------------------------------------------*/
- public static DropboxAPI<AndroidAuthSession> mDBApi;
- private boolean mLoggedIn;
- private final String TAG = "RegisterActivity";
- private ParseUser user;
- private static final int AUTHENTICATION_NONE = 0;
- private static final int AUTHENTICATION_STARTED = 1;
- private int state = AUTHENTICATION_NONE;
- Button btnRegister;
- Button btnLinkToLogin;
- EditText inputNickname;
- EditText inputEmail;
- EditText inputPassword;
- EditText inputRepeatPassword;
- TextView registerErrorMsg;
- ProgressBar registerProgress;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.register);
- /*Dropbox stuff*/
- AndroidAuthSession session = buildSession();
- mDBApi = new DropboxAPI<AndroidAuthSession>(session);
- /*Parse Stuff - Copy and Paste this into every onCreate method to be able to use Parse*/
- Parse.initialize(this, "XXXXXX", "XXXXX");
- /*Importing all assets like buttons, text fields*/
- inputNickname = (EditText) findViewById(R.id.registerName);
- inputEmail = (EditText) findViewById(R.id.registerEmail);
- inputPassword = (EditText) findViewById(R.id.registerPassword);
- inputRepeatPassword = (EditText) findViewById(R.id.registerRepeatPassword);
- btnRegister = (Button) findViewById(R.id.btnRegister);
- btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
- registerErrorMsg = (TextView) findViewById(R.id.register_error);
- registerProgress = (ProgressBar) findViewById(R.id.progress);
- registerProgress.setVisibility(4); //set to invisible
- }
- /**
- * Registers a new user - if success go to the StartScreen, if fail show error messages
- * @param view
- */
- public void onClickRegister(View view) {
- //Showing the progress spinner
- showProgressSpinner();
- String name = inputNickname.getText().toString();
- String email = inputEmail.getText().toString().toLowerCase(); //To avoid case sensitivity problems...
- String password = inputPassword.getText().toString();
- String repeatPassword = inputRepeatPassword.getText().toString();
- //My own validation check...
- //TODO: Check if it is possible to compare the two password inputs as an ParseException?
- if(name == null || name.length() == 0) {
- hideProgressSpinner();
- registerErrorMsg.setText("Please enter a valid name");
- } else if (badPassword(password)) {
- hideProgressSpinner();
- registerErrorMsg.setText("Please enter a valid password of minimum 6 characters");
- } else if (!password.equals(repeatPassword)) {
- hideProgressSpinner();
- registerErrorMsg.setText("You password doesn't match. Please try again!");
- } else {
- user = new ParseUser();
- user.setUsername(name.toLowerCase());
- user.put("naturalUsername", name); //to keep the input username, e.g capital letter
- user.put("globalScore", 0); //globalScore is set to zero when register
- user.setPassword(password);
- user.setEmail(email);
- user.signUpInBackground(new SignUpCallback() {
- @Override
- public void done(ParseException e) {
- hideProgressSpinner();
- if (e == null) {
- // Successful registration - Launch Start Screen
- mDBApi.getSession().startAuthentication(RegisterActivity.this); // DROPBOX AUTHENTICATION FOR USER TO ACCEPT IN WEBBROWSER.
- state = AUTHENTICATION_STARTED;
- } else {
- // Sign up didn't succeed. Looking at ParseExceptions...
- // Found a list of exceptions: https://www.parse.com/docs/android/api/constant-values.html
- if (e.getCode() == 202) {
- registerErrorMsg.setText("The username is already in use");
- } else if (e.getCode() == 203) {
- registerErrorMsg.setText("The email is already registered");
- } else if (e.getCode() == 125) {
- registerErrorMsg.setText("Please enter a valid e-mail");
- } else if (e.getCode() == 100) {
- registerErrorMsg.setText("Please check your internet connection!");
- } else {
- //Unknown error - Error code until all problems fixed...
- registerErrorMsg.setText("Oops! Something went wrong. The server says: " + e.getMessage());
- }
- }
- }
- });
- }
- }
- /**
- * Go to login screen
- * @param view
- */
- public void onClickLogin(View view) {
- Intent i = new Intent(getApplicationContext(), LoginActivity.class);
- startActivity(i);
- // Close Registration View
- finish();
- }
- private boolean badPassword(String password) {
- //Only two criterias for now...
- //TODO Fix stronger restrictions??
- return (password == null || password.length() < 5);
- }
- //TODO: Where should we put these, they are used in both RegisterActivity and LoginActivity
- //TODO: Consider using threads instead...
- private void showProgressSpinner() {
- //show the spinner
- registerProgress.setVisibility(0);
- //disable all clickable objects
- btnRegister.setEnabled(false);
- btnLinkToLogin.setEnabled(false);
- inputNickname.setEnabled(false);
- inputEmail.setEnabled(false);
- inputPassword.setEnabled(false);
- inputRepeatPassword.setEnabled(false);
- }
- private void hideProgressSpinner() {
- //hide the spinner
- registerProgress.setVisibility(8);
- //re-enable all clickable objects
- btnRegister.setEnabled(true);
- btnLinkToLogin.setEnabled(true);
- inputNickname.setEnabled(true);
- inputEmail.setEnabled(true);
- inputPassword.setEnabled(true);
- inputRepeatPassword.setEnabled(true);
- }
- private void showToast(String msg) {
- Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
- error.show();
- }
- /*
- * 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()
- */
- /**
- * Sets logged in.
- * @param loggedIn
- */
- private void setLoggedIn(boolean loggedIn) {
- mLoggedIn = loggedIn;
- if (loggedIn) {
- Log.d(TAG, "Logged In");
- } else {
- Log.d(TAG, "Not Logged In");
- }
- }
- /**
- * 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.
- * Disconnects the session from Dropbox.
- */
- private void logOut() {
- // Remove credentials from the session
- mDBApi.getSession().unlink();
- // Clear our stored keys
- clearKeys();
- // Change UI state to display logged out version
- setLoggedIn(false);
- }
- /** -----------------------------DROPBOX METHODS-----------------------------------*/
- /**
- *
- */
- @Override
- protected void onResume() {
- super.onResume();
- AndroidAuthSession session = mDBApi.getSession();
- // The next part must be inserted in the onResume() method of the
- // activity from which session.startAuthentication() was called, so
- // that Dropbox authentication completes properly.
- if (session.authenticationSuccessful()) {
- try {
- // Mandatory call to complete the authentication.
- session.finishAuthentication();
- state = AUTHENTICATION_NONE;
- // Store it locally in our app for later use
- TokenPair tokens = session.getAccessTokenPair();
- storeKeys(tokens.key, tokens.secret);
- setLoggedIn(true);
- Intent dashboard = new Intent(getApplicationContext(), StartScreen.class);
- //Close all views before launching start screen
- dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- startActivity(dashboard);
- // Close Registration Screen
- finish();
- } catch (IllegalStateException e) {
- showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
- }
- }
- if (!session.authenticationSuccessful() && state == AUTHENTICATION_STARTED){
- showToast("You denied the DropBox authentication. Registration did not succeed. Try Again");
- state = AUTHENTICATION_NONE;
- try{
- user.delete();
- }
- catch (ParseException e){
- Log.d(TAG,"Object does not exist or internet failed " + e.getMessage());
- }
- }
- }
- /**
- * Shows keeping the access keys returned from Trusted Authenticator in a local
- * store, rather than storing user name & password, and re-authenticating each
- * time (which is not to be done, ever).
- *
- * @return Array of [access_key, access_secret], or null if none stored
- */
- private String[] getKeys() {
- SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
- String key = prefs.getString(ACCESS_KEY_NAME, null);
- String secret = prefs.getString(ACCESS_SECRET_NAME, null);
- if (key != null && secret != null) {
- String[] ret = new String[2];
- ret[0] = key;
- ret[1] = secret;
- return ret;
- } else {
- return null;
- }
- }
- /**
- *
- * @param key
- * @param secret
- *
- * Shows keeping the access keys returned from Trusted Authenticator in a local
- * store, rather than storing user name & password, and re-authenticating each
- * time (which is not to be done, ever).
- */
- private void storeKeys(String key, String secret) {
- // Save the access key for later
- SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
- Editor edit = prefs.edit();
- edit.putString(ACCESS_KEY_NAME, key);
- edit.putString(ACCESS_SECRET_NAME, secret);
- edit.commit();
- }
- /**
- * Clears the store Dropbox keys.
- */
- private void clearKeys() {
- SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
- Editor edit = prefs.edit();
- edit.clear();
- edit.commit();
- }
- /**
- * Initializes the unique dropbox keys and builds a new session.
- * @return
- */
- private AndroidAuthSession buildSession() {
- AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
- AndroidAuthSession session;
- String[] stored = getKeys();
- if (stored != null) {
- AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
- session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
- } else {
- session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
- }
- return session;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment