Пример #1
0
  private void getContacts() {
    ParseUser pu = ParseUser.getCurrentUser();
    ArrayList<String> contactname = new ArrayList<String>();
    ArrayList<String> contactnumber = new ArrayList<String>();
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String[] projection =
        new String[] {
          ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
          ContactsContract.CommonDataKinds.Phone.NUMBER
        };

    Cursor people = getContentResolver().query(uri, projection, null, null, null);

    int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
    int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

    people.moveToFirst();
    do {
      String name = people.getString(indexName);
      String number = people.getString(indexNumber);
      contactname.add(name);
      pu.put("Names", contactname);
      pu.saveInBackground();
      contactnumber.add(number);
      pu.put("Numbers", contactnumber);
      pu.saveInBackground();
    } while (people.moveToNext());
  }
Пример #2
0
  @Override
  public void onClick(View v) {
    final String user = username.getText().toString();
    String pass = password.getText().toString();
    final String userMail = email.getText().toString();
    String refCode = referalCode.getText().toString();
    if (!refCode.equals("")) {
      ref = Integer.parseInt(refCode);
    }
    if (username.getText().length() > 0 && password.getText().length() > 0) {
      final ParseUser newUser = new ParseUser();
      newUser.setUsername(user);
      newUser.setPassword(pass);
      newUser.setEmail(userMail);
      newUser.put("isAdmin", isAdmin);
      if (isAdmin == false) {
        newUser.put("otp", ref);
      }

      newUser.signUpInBackground(
          new SignUpCallback() {
            public void done(ParseException e) {
              if (e == null) {
                Toast.makeText(MainActivity.this, "Registered successfully", Toast.LENGTH_SHORT)
                    .show();
                finish();

              } else {
                Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
              }
            }
          });
    }
  }
Пример #3
0
  public void siginUpFB(User user, String data, SunshineFacebookLoginCallback callback) {

    this.facebookLoginCallback = callback;

    parseUser = new ParseUser();
    parseUser.setEmail(user.getEmail());
    parseUser.setUsername(user.getUserName());
    parseUser.setPassword(user.getPassword());
    // prepareParseUser(parseUser, user);
    parseUser.put("name", user.getName());

    parseUser.put("facebookData", data);

    ParseUser.logInInBackground(
        user.getUserName(),
        user.getPassword(),
        new LogInCallback() {
          @Override
          public void done(ParseUser user, ParseException e) {
            if (user != null) facebookLoginCallback.doneLoginFacebook(true);
            else
              parseUser.signUpInBackground(
                  new SignUpCallback() {
                    @Override
                    public void done(ParseException e) {
                      if (e == null) facebookLoginCallback.doneLoginFacebook(true);
                      else facebookLoginCallback.doneLoginFacebook(false);
                    }
                  });
          }
        });
  }
  /**
   * Ajout d'un nouvel utilisateur dans la base de donnees
   *
   * @param password
   * @param firstName
   * @param lastName
   * @param birthDay
   * @param gender
   * @throws java.text.ParseException
   */
  private void mettreAJourUtilisateur(
      final String password,
      final String firstName,
      final String lastName,
      final String birthDay,
      final String gender)
      throws java.text.ParseException, ParseException {

    System.out.println(" appel a mettreAJourUtilisateur");

    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
    final Date dBirthDay = sdf.parse(birthDay);
    ParseUser pUser = ParseUser.getCurrentUser();
    if (password != null) {
      pUser.put("password", password);
    }
    pUser.put("firstname", firstName);
    pUser.put("lastname", lastName);
    pUser.put("gender", gender);

    if (dBirthDay != null) {
      pUser.put("birthday", dBirthDay);
    }

    pUser.saveInBackground();
    Toast.makeText(getActivity(), "Modification enregistrée", Toast.LENGTH_SHORT).show();

    Intent newActivity = new Intent(getActivity(), ProfilLoginActivity.class);
    startActivity(newActivity);
    getActivity().finish();
    System.out.println(" Fin appel a mettreAJourUtilisateur");
  }
Пример #5
0
 public User(
     String name, String password, String email, String phone, String sex, String birthday) {
   mParseUser = new ParseUser();
   mParseUser.put(NAME, name);
   mParseUser.put(PHONE, phone);
   mParseUser.setUsername(email);
   mParseUser.put(SEX, sex);
   mParseUser.put(BIRTHDAY, birthday);
   mParseUser.setEmail(email);
   mParseUser.setPassword(password);
   mParseUser.put(BACKUP_EMAIL, email);
 }
Пример #6
0
  public void siginUp(User user, SunshineLoginCallback callback) {

    this.callback = callback;

    parseUser = new ParseUser();
    parseUser.setEmail(user.getEmail());
    parseUser.setUsername(user.getUserName());
    parseUser.setPassword(user.getPassword());
    // prepareParseUser(parseUser, user);
    parseUser.put("name", user.getName());

    if (user.getImgPath() != null) {
      File file = new File(user.getImgPath());
      parseFile = new ParseFile(file);
      parseFile.saveInBackground(
          new SaveCallback() {
            @Override
            public void done(ParseException e) {
              if (e != null) e.printStackTrace();
              parseUser.put("img", parseFile);
              parseUser.signUpInBackground(SunshineLogin.this);
            }
          });
    } else {
      parseUser.signUpInBackground(SunshineLogin.this);
    }
  }
Пример #7
0
 private void saveNewUser(Bitmap profileImageBitmap) {
   parseUser = ParseUser.getCurrentUser();
   parseUser.setUsername(name);
   parseUser.setEmail(email);
   parseUser.put("dob", birthday);
   //        Saving profile photo as a ParseFile
   ByteArrayOutputStream stream = new ByteArrayOutputStream();
   profileImageBitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
   byte[] data = stream.toByteArray();
   String thumbName = parseUser.getUsername().replaceAll("\\s+", "");
   final ParseFile parseFile = new ParseFile(thumbName + "_thumb.jpg", data);
   // we can use saveInBackground() in this method because this data is from Fb
   // so the user must have an internet connection
   parseFile.saveInBackground(
       new SaveCallback() {
         @Override
         public void done(ParseException e) {
           parseUser.put("profileThumb", parseFile);
           // Finally save all the user details
           parseUser.saveInBackground(
               new SaveCallback() {
                 @Override
                 public void done(ParseException e) {
                   Toast.makeText(
                           LoginActivity.this,
                           "New user: "******" Signed up",
                           Toast.LENGTH_SHORT)
                       .show();
                   // Only start the next activity after this one is done
                   startMainActivity();
                 }
               });
         }
       });
 }
  @Override
  public void onConnected(Bundle bundle) {
    Log.i(TAG, "Location services connected.");

    Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (lastLocation == null) {
      Toast.makeText(
              FullScreenMapActivity.this, "There is currently no connectivity", Toast.LENGTH_LONG)
          .show();
    } else {

      ParseGeoPoint point =
          new ParseGeoPoint(lastLocation.getLatitude(), lastLocation.getLongitude());
      ParseUser currentUser = ParseUser.getCurrentUser();
      currentUser.put("location", point);
      currentUser.saveInBackground();

      mGoogleMap.animateCamera(CameraUpdateFactory.zoomIn());

      CameraPosition cameraPosition =
          new CameraPosition.Builder()
              .target(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()))
              .zoom(12)
              .bearing(90)
              .tilt(30)
              .build();

      mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }
  }
  @OnClick(R.id.informationSubmitButton)
  public void finishInfoFlow() {
    if (collegeField.getText().toString().trim().length() > 0
        && graduationDateField.getText().toString().trim().length() > 0) {
      ParseUser user = ParseUser.getCurrentUser();

      user.put(ParseConstants.KEY_COLLEGE_ATTENDED, collegeField.getText().toString().trim());

      String string = graduationDateField.getText().toString().trim();
      DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
      try {
        Date date = formatter.parse(string);
        user.put(ParseConstants.KEY_GRADUATION_DATE, date);
        Log.d(TAG, date.toString());
      } catch (ParseException e) {
        Log.e(TAG, e.getMessage());
      }

      if (employerNameField.getText().toString().trim().length() > 0) {
        user.put(ParseConstants.KEY_EMPLOYER_NAME, employerNameField.getText().toString().trim());
      }

      if (examDateField.getText().toString().trim().length() > 0) {
        string = examDateField.getText().toString().trim();
        try {
          Date date = formatter.parse(string);
          user.put(ParseConstants.KEY_EXAM_DATE, date);
          Log.d(TAG, date.toString());
        } catch (ParseException e) {
          Log.e(TAG, e.getMessage());
        }
      }

      AccountingSwipeApplication.expandCardsOnResume = true;
      // Gives user full access
      user.put(ParseConstants.KEY_HAS_FULL_ACCESS, true);

      user.saveInBackground();
      finish();
    }
  }
Пример #10
0
 public void register(
     String email,
     String password,
     String userName,
     String picName,
     String picPhoneNumber,
     final ParseCallback callback) {
   final ParseUser parseUser = new ParseUser();
   parseUser.setUsername(userName);
   parseUser.setPassword(password);
   parseUser.setEmail(email);
   parseUser.put("picName", picName);
   parseUser.put("picPhoneNumber", picPhoneNumber);
   parseUser.signUpInBackground(
       new SignUpCallback() {
         @Override
         public void done(ParseException e) {
           if (e == null) {
             if (callback != null) {
               ParseUser user = ParseUser.getCurrentUser();
               UserModel userModel = new UserModel();
               userModel.setEmail(user.getEmail());
               userModel.setUserName(user.getUsername());
               userModel.setSessionToken(user.getSessionToken());
               userModel.setPicName(user.getString("picName"));
               userModel.setPicPhoneNumber(user.getString("picPhoneNumber"));
               parseUser.saveInBackground();
               if (callback != null) {
                 callback.onSuccess(userModel, AppConstants.APIUSER_REGISTRATION_COMPLETED);
               }
             }
           } else {
             if (callback != null) {
               callback.onError(
                   AvaniUtils.generateException(e), AppConstants.APIUSER_REGISTRATION_FAILED);
             }
           }
         }
       });
 }
Пример #11
0
  private void finishSubmitting(ParseUser parseUser) {
    settings.edit().putBoolean("my_first_time", false).commit();

    ParseUser mCurrentUser = parseUser;

    mCurrentUser.put("gender", mGender);
    mCurrentUser.put("age", Integer.parseInt(mAge));
    mCurrentUser.put("dataPlan", Integer.parseInt(mDataPlan));
    mCurrentUser.put("serviceProvider", mServiceProvider);
    mCurrentUser.put("phoneModel", mPhoneModel);
    mCurrentUser.put("dataThisMonth", Double.parseDouble(mDataThisMonth));

    mCurrentUser.saveInBackground(
        new SaveCallback() {
          @Override
          public void done(ParseException e) {
            if (e != null) {
              AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);

              builder.setMessage(e.getMessage());
              builder.setTitle("Oops!");
              builder.setPositiveButton(android.R.string.ok, null);
              AlertDialog dialog = builder.create();
              dialog.show();
            } else {
              Intent returnToMainIntent = new Intent(SignUpActivity.this, MainActivity.class);
              returnToMainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              returnToMainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
              Toast.makeText(SignUpActivity.this, "User details updated.", Toast.LENGTH_LONG)
                  .show();
              startActivity(returnToMainIntent);
            }
          }
        });
  }
Пример #12
0
  @Override
  protected void onDestroy() {
    if (currentUser != null) {
      currentUser.put("isOnline", false);
      currentUser.saveInBackground();
    }

    if (broadcastMain != null) {
      unregisterReceiver(broadcastMain);
      broadcastMain = null;
    }
    super.onDestroy();
  }
  private void doRegister() {
    final String email = emailET.getText().toString();
    String password = passwordET.getText().toString();
    String confirmPW = confirmPwET.getText().toString();

    ParseUser parseUser = new ParseUser();
    parseUser.setUsername(email);
    parseUser.setEmail(email);
    parseUser.put("first_time", true);
    parseUser.put("setup_complete", false);
    parseUser.setPassword(password);
    parseUser.signUpInBackground(
        new SignUpCallback() {
          @Override
          public void done(ParseException e) {
            if (e == null) {
              Toast.makeText(getActivity(), "Success!", Toast.LENGTH_SHORT).show();
              takeBackToLogin(email);
            }
          }
        });
  }
Пример #14
0
  @OnClick(R.id.save)
  public void onClickSave() {
    String lecturaString = mUltimaLectura.getText().toString().trim();
    String fechaString = mFechaAnterior.getText().toString().trim();
    String pagoString = mUltimoPago.getText().toString().trim();
    String consumoString = mUltimoConsumo.getText().toString().trim();

    mUser = ParseUser.getCurrentUser();

    if (lecturaString.isEmpty()) {
      mUltimaLectura.setError(getResources().getString(R.string.error_field_required));
      mUltimaLectura.requestFocus();
      return;
    }

    mUser.put(ParseConstants.KEY_LECTURA_ANTERIOR, Integer.parseInt(lecturaString));
    mUser.put(ParseConstants.KEY_TARIFA, mTarifas.get(mSpinner.getSelectedItemPosition()));
    if (!pagoString.isEmpty())
      mUser.put(ParseConstants.KEY_ULTIMO_PAGO, Float.parseFloat(pagoString));
    if (!consumoString.isEmpty())
      mUser.put(ParseConstants.KEY_ULTIMO_CONSUMO, Integer.parseInt(consumoString));

    try {
      Date fecha = mDateFormatter.parse(fechaString);
      mUser.put(ParseConstants.KEY_FECHA_LECTURA, fecha);
    } catch (ParseException e) {
      // TODO:send error
    }

    mUser.saveInBackground(
        new SaveCallback() {
          @Override
          public void done(com.parse.ParseException e) {
            if (e == null) {
              NavUtils.navigateUpFromSameTask(EditRecibo.this);
            }
          }
        });
  }
Пример #15
0
  private void saveChanges(ParseUser user) {

    boolean hasChanged = false;
    if (!name.getText().toString().equals(nameBeforeChange)) {
      user.put("name", name.getText().toString());
      hasChanged = true;
    }

    if (!website.getText().toString().equals(websiteBeforeChange)) {
      user.put("website", website.getText().toString());
      hasChanged = true;
    }

    if (!bio.getText().toString().equals(bioBeforeChange)) {
      user.put("bio", bio.getText().toString());
      hasChanged = true;
    }

    if (!email.getText().toString().equals(emailBeforeChange)) {
      user.setEmail(email.getText().toString());
      hasChanged = true;
    }

    if (!phoneNumber.getText().toString().equals(phoneNumberBeforeChange)) {
      user.put("phone_number", phoneNumber.getText().toString());
      hasChanged = true;
    }

    if (!genderSpinner.getSelectedItem().toString().equals(genederBeforeChange)) {
      user.put("gender", genderSpinner.getSelectedItem().toString());
      hasChanged = true;
    }

    if (hasChanged) {
      user.saveInBackground();
    }
  }
  public void updateCurrentUser(String name, String email, String gender) {
    ParseUser currentUser = ParseUser.getCurrentUser();

    currentUser.put("name", name);
    currentUser.put("email", email);
    currentUser.put("gender", gender);

    currentUser.saveInBackground(
        new SaveCallback() {

          @Override
          public void done(ParseException e) {
            setProgressBarIndeterminateVisibility(false);

            if (e == null) {
              Logger.d(MainApplication.TAG, "User info was successfully updated!");
            } else {
              Logger.d(
                  MainApplication.TAG,
                  "An error occurred and it was not possible to update the user info.");
            }
          }
        });
  }
Пример #17
0
    @Override
    protected Boolean doInBackground(Void... params) {
      try {
        if (mSingUpFlag) {
          ParseUser user = new ParseUser();
          user.setEmail(mEmail);
          user.setUsername(mEmail);
          user.setPassword(mPassword);
          user.put("name", mName);
          user.signUp();

          return true;
        } else {
          ParseUser user = ParseUser.logIn(mEmail, mPassword);
          if (user != null) {
            return true;
          }
        }
      } catch (ParseException e) {
        e.printStackTrace();
      }

      return false;
    }
  @Override
  public void onClick(View v) {
    String username = usernameField.getText().toString();
    String password = passwordField.getText().toString();
    String passwordAgain = confirmPasswordField.getText().toString();

    String email = null;
    if (config.isParseLoginEmailAsUsername()) {
      email = usernameField.getText().toString();
    } else if (emailField != null) {
      email = emailField.getText().toString();
    }

    String name = null;
    if (nameField != null) {
      name = nameField.getText().toString();
    }

    if (username.length() == 0) {
      if (config.isParseLoginEmailAsUsername()) {
        showToast(R.string.com_parse_ui_no_email_toast);
      } else {
        showToast(R.string.com_parse_ui_no_username_toast);
      }
    } else if (password.length() == 0) {
      showToast(R.string.com_parse_ui_no_password_toast);
    } else if (password.length() < minPasswordLength) {
      showToast(
          getResources()
              .getQuantityString(
                  R.plurals.com_parse_ui_password_too_short_toast,
                  minPasswordLength,
                  minPasswordLength));
    } else if (passwordAgain.length() == 0) {
      showToast(R.string.com_parse_ui_reenter_password_toast);
    } else if (!password.equals(passwordAgain)) {
      showToast(R.string.com_parse_ui_mismatch_confirm_password_toast);
      confirmPasswordField.selectAll();
      confirmPasswordField.requestFocus();
    } else if (email != null && email.length() == 0) {
      showToast(R.string.com_parse_ui_no_email_toast);
    } else if (name != null && name.length() == 0) {
      showToast(R.string.com_parse_ui_no_name_toast);
    } else {
      ParseUser user = new ParseUser();

      // Set standard fields
      user.setUsername(username);
      user.setPassword(password);
      user.setEmail(email);

      // Set additional custom fields only if the user filled it out
      if (name.length() != 0) {
        user.put(USER_OBJECT_NAME_FIELD, name);
      }

      loadingStart();
      user.signUpInBackground(
          new SignUpCallback() {

            @Override
            public void done(ParseException e) {
              if (isActivityDestroyed()) {
                return;
              }

              if (e == null) {
                loadingFinish();
                signupSuccess();
              } else {
                loadingFinish();
                if (e != null) {
                  debugLog(
                      getString(R.string.com_parse_ui_login_warning_parse_signup_failed)
                          + e.toString());
                  switch (e.getCode()) {
                    case ParseException.INVALID_EMAIL_ADDRESS:
                      showToast(R.string.com_parse_ui_invalid_email_toast);
                      break;
                    case ParseException.USERNAME_TAKEN:
                      showToast(R.string.com_parse_ui_username_taken_toast);
                      break;
                    case ParseException.EMAIL_TAKEN:
                      showToast(R.string.com_parse_ui_email_taken_toast);
                      break;
                    default:
                      showToast(R.string.com_parse_ui_signup_failed_unknown_toast);
                  }
                }
              }
            }
          });
    }
  }
Пример #19
0
  public void registerUser(String password) {
    Toast.makeText(
            this, "Registering user " + email + " with password " + password, Toast.LENGTH_SHORT)
        .show();
    // perform the user registration attempt.

    ParseUser user = new ParseUser();
    // we set the username to be the email as it is a required field
    // we also set email to be the email so it follows the pattern from the Fb data
    user.setUsername(email);
    user.setPassword(password);
    user.setEmail(email);
    user.put("dob", birthday);

    user.signUpInBackground(
        new SignUpCallback() {
          public void done(ParseException e) {
            if (e == null) {
              // Hooray! Let them use the app now.
              startMainActivity();
            } else {
              // Sign up didn't succeed. Look at the ParseException
              // to figure out what went wrong
              if (e.getCode() == ParseException.USERNAME_TAKEN
                  || e.getCode() == ParseException.EMAIL_TAKEN) {
                Toast.makeText(
                        LoginActivity.this,
                        "This email is already associated with an account. If you registered using Facebook, use Facebook to sign in too.",
                        Toast.LENGTH_SHORT)
                    .show();
              } else if (e.getCode() == ParseException.CONNECTION_FAILED) {
                // Unfortunately there's no logInEventually() method for obvious reasons -
                // There's no way to tell if the user is old or new without checking the server
                // so we wouldn't know what to display on the next activity
                // It would be like signing in to Facebook without internet
                // Instead we just ask the user to try again later, like most apps do
                Toast.makeText(
                        LoginActivity.this,
                        "You don't have an internet connection. Please check your connectivity and try again.",
                        Toast.LENGTH_SHORT)
                    .show();
              } else if (e.getCode() == ParseException.INTERNAL_SERVER_ERROR) {
                // Nothing we can do about a backend error when we don't control the backend
                Toast.makeText(
                        LoginActivity.this,
                        "Unfortunately the server is down. Please try again in a few minutes.",
                        Toast.LENGTH_SHORT)
                    .show();
              } else {
                // Allow testers to report bugs easily. Remove this before finalising code for
                // production.
                Toast.makeText(
                        LoginActivity.this,
                        "Sorry, something went wrong. Please tell the developer the error code is: Register_"
                            + e.getCode(),
                        Toast.LENGTH_SHORT)
                    .show();
              }
            }
          }
        });
  }
Пример #20
0
  // View.OnClickListener method (create account button clicked)
  @Override
  public void onClick(View view) {
    String password = mEdtPassword.getText().toString();
    String passwordAgain = mEdtConfirmPassword.getText().toString();
    String name = mEdtName.getText().toString();

    if (password.length() == 0) {
      showSnack(R.string.com_parse_ui_no_password_toast);
    } else if (password.length() < mMinPasswordLength) {
      showSnack(
          getResources()
              .getQuantityString(
                  R.plurals.com_parse_ui_password_too_short_toast,
                  mMinPasswordLength,
                  mMinPasswordLength));
    } else if (passwordAgain.length() == 0) {
      showSnack(R.string.com_parse_ui_reenter_password_toast);
    } else if (!password.equals(passwordAgain)) {
      showSnack(R.string.com_parse_ui_mismatch_confirm_password_toast);
      mEdtConfirmPassword.selectAll();
      mEdtConfirmPassword.requestFocus();
    } else if (name.length() == 0) {
      showSnack(R.string.com_parse_ui_no_name_toast);
    } else {
      final ParseUser user = ParseObject.create(ParseUser.class);

      // Set standard fields
      user.setUsername(mEmailAddress);
      user.setEmail(mEmailAddress);
      user.setPassword(password);

      // Set additional custom fields only if the user filled it out
      if (name.length() != 0) {
        user.put(SignInActivity.USER_OBJECT_NAME_FIELD, name);
      }

      loadingStart();
      user.signUpInBackground(
          new SignUpCallback() {

            @Override
            public void done(ParseException e) {
              if (isActivityDestroyed()) {
                Log.e(LOG_TAG, "Activity was destroyed during sign up");
                return;
              }

              loadingFinish();
              if (e == null) {
                signUpSuccess(user);
              } else {
                switch (e.getCode()) {
                  case ParseException.INVALID_EMAIL_ADDRESS:
                    showSnack(R.string.com_parse_ui_invalid_email_toast);
                    break;
                  case ParseException.USERNAME_TAKEN:
                    showSnack(R.string.com_parse_ui_username_taken_toast);
                    break;
                  case ParseException.EMAIL_TAKEN:
                    showSnack(R.string.com_parse_ui_email_taken_toast);
                    break;
                  default:
                    Log.e(LOG_TAG, "Error signing up " + mEmailAddress + ": " + e.toString());
                    showSnack(R.string.com_parse_ui_signup_failed_unknown_toast);
                }
              }
            }
          });
    }
  }
Пример #21
0
  /** Checks to see if any fields are empty and/or if two password fields are equal */
  public void checkFields(View v) {

    EditText name_field = (EditText) findViewById(R.id.nameField);
    EditText addr_field = (EditText) findViewById(R.id.addressField);
    EditText dob_field = (EditText) findViewById(R.id.dateOfBirthField);
    EditText email_field = (EditText) findViewById(R.id.emailField);
    EditText pass1 = (EditText) findViewById(R.id.passwordField);
    EditText pass2 = (EditText) findViewById(R.id.passwordConfirmField);

    String name = name_field.getText().toString().trim();
    String address = addr_field.getText().toString().trim();
    String dob = dob_field.getText().toString().trim();
    String email = email_field.getText().toString().trim();
    String password = pass1.getText().toString().trim();
    String passwordRetry = pass2.getText().toString().trim();

    if (TextUtils.isEmpty(name)) {
      name_field.setError("You must enter a username");
    }

    if (TextUtils.isEmpty(address)) {
      name_field.setError("You must enter an address");
    }

    if (TextUtils.isEmpty(dob)) {
      name_field.setError("You must enter a date of birth");
    }

    if (TextUtils.isEmpty(email)) {
      email_field.setError("You must enter an email");
    }

    if (TextUtils.isEmpty(password)) {
      pass1.setError("You must enter a password");
    }

    if (TextUtils.isEmpty(passwordRetry)) {
      pass2.setError("You must enter a password");
    }

    if (password.equals(passwordRetry)) {

      String android_id =
          Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
      Log.d("ANDROID ID", android_id);

      ParseUser user = new ParseUser();
      user.setUsername(name);
      user.setPassword(password);
      user.setEmail(email);
      user.put("address", address);
      user.put("dateOfBirth", dob);
      user.put("androidID", android_id);

      user.signUpInBackground(
          new SignUpCallback() {
            public void done(ParseException e) {
              if (e == null) {
                // success
              } else {
                // Sign up didn't succeed. Look at the ParseException
                // to figure out what went wrong
                Log.d("Error", e.toString());
              }
            }
          });

      // These two lines automatically take the user back to the home page after a successful
      // registration
      Intent goHome = new Intent(Register.this, HomePage.class);
      startActivity(goHome);

    } else {
      // Displays dialog to inform the user the passwords were unequal and they must try again
      AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
      builder.setMessage(R.string.unequalPasswords).setTitle(R.string.passwordDialogTitle);
      builder.setCancelable(true);
      builder.setPositiveButton(
          "Ok",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
              dialog.cancel();
            }
          });
      AlertDialog alert = builder.create();
      alert.show();
    }
  }
Пример #22
0
  @Override
  public void onClick(View v) {
    final ParseUser currentUser = ParseUser.getCurrentUser();

    switch (v.getId()) {
      case (R.id.reset_password_button):
        Utils.resetPassword(ProfileEditActivity.this, currentUser.getEmail());
        break;

      case (R.id.save_changes_button):

        // check that all the user availabilities are valid
        for (int i = 0; i < availabilityAdapter.getCount() - 1; i++) {
          if (!availabilityAdapter.getItem(i).isValid()) {
            Utils.showMessageBox(
                v.getContext(),
                "Invalid period",
                "At least one of the availability period are invalid");
            return;
          }
        }

        // handle name
        String name = nameEdit.getText().toString();
        if (!name.isEmpty()) {
          currentUser.put("name", name);
        }

        // handle address
        if (address != null) {
          currentUser.put("address", Utils.addressToJSONArray(address));
          currentUser.put(
              "addressLocation", new ParseGeoPoint(address.getLatitude(), address.getLongitude()));
        }

        // handle phone number
        String phone = phoneEdit.getText().toString();
        if (!phone.isEmpty()) {
          currentUser.put("phone", phone);
        }
        currentUser.put("sharePhone", phoneShareEdit.isChecked());

        final ProgressDialog pd =
            ProgressDialog.show(ProfileEditActivity.this, "", "Saving profile...", true, false);
        List<Task<Void>> tasks = new ArrayList<>();

        // handle profile picture (save before proceeding
        if (picByteArray != null) {
          Log.d("My Loggggg", "profile picture changed");
          final ParseFile photoFile =
              new ParseFile(currentUser.getUsername().toString() + "profile_pic.jpg", picByteArray);

          tasks.add(
              photoFile
                  .saveInBackground()
                  .onSuccess(
                      new Continuation<Void, Void>() {
                        @Override
                        public Void then(Task<Void> task) throws Exception {
                          currentUser.put("photo", photoFile);
                          return null;
                        }
                      }));
        }

        // save changes in user availability
        for (int i = 0; i < availabilityAdapter.getCount() - 1; i++) {
          Integer id = (Integer) availabilityAdapter.getItem(i).getTag();
          AvailabilityRecord record = availabilityAdapter.getItem(i);
          if (id != null) {
            // update if need old records
            ParseObject userAvailability = userAvailabilitiesList.get(id);
            userAvailabilitiesList.set(id, null);
            record.toParseObject(userAvailability);
            tasks.add(userAvailability.saveInBackground());
          } else {
            // else is a new record
            ParseObject newUserAvailability = record.toParseObject();
            newUserAvailability.put("user", currentUser);
            tasks.add(newUserAvailability.saveInBackground());
          }
        }
        // remove from parse all availabilities that user remove
        for (ParseObject availability : userAvailabilitiesList) {
          if (availability != null) {
            tasks.add(availability.deleteInBackground());
          }
        }

        Task.whenAll(tasks)
            .onSuccessTask(
                new Continuation<Void, Task<Void>>() {
                  @Override
                  public Task<Void> then(Task<Void> task) throws Exception {
                    return currentUser.saveInBackground();
                  }
                })
            .continueWith(
                new Continuation<Void, Void>() {
                  @Override
                  public Void then(Task<Void> task) throws Exception {
                    pd.dismiss();
                    if (!task.isFaulted()) {
                      Toast.makeText(
                              getApplicationContext(),
                              "Changes saved successfully",
                              Toast.LENGTH_LONG)
                          .show();
                      finish();
                    } else {
                      Log.e("ProfileEdit", "error saving changes: " + task.getError().getMessage());
                      Utils.showMessageBox(
                          ProfileEditActivity.this,
                          "Failed saving changes",
                          getString(R.string.unknown_error_occur));
                    }
                    return null;
                  }
                },
                Task.UI_THREAD_EXECUTOR);

        break;

      case (R.id.change_pic_button):
        // create Intent to take a picture and return control to the calling application
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA_REQUEST);

        break;

      case R.id.profile_address_change_edit:
        // move user to address selection activity
        Intent addressSelectionIntent =
            new Intent(ProfileEditActivity.this, AddressSelectionActivity.class);
        startActivityForResult(addressSelectionIntent, REQUEST_ADDRESS);

        break;
    }
  }
Пример #23
0
	public void SingUp(View v) {
		ParseUser user = new ParseUser();
		user.setUsername("reyesmagos");
		user.setPassword("reyesmagos");
		user.setEmail("*****@*****.**");
		user.put("type", 2);
		user.put("nit", "890936694");
		user.put("sector", "Informatica");
		user.put("subSector", "subsector");
		user.put("enterpriseType", "microempresa");
		user.put("partners", "alexis calderon, oscar gallon,");
		user.put("municipio", "Medellin");
		user.put("department", "Antioquia");
		user.put("adress", "Call 67 #50-50");
		user.put("lat", "6.454353");
		user.put("lng", "-75.3434");
		user.put("operatingCountries","guatemala, salvador,");
		user.put("gremio", "Softwariii");
		user.signUpInBackground(new SignUpCallback() {

			@Override
			public void done(ParseException arg0) {
				// TODO Auto-generated method stub
				if (arg0 == null) {
					Log.i("error", "sing");
				}

			}
		});
	}
Пример #24
0
 public static void updateUserProfile(
     final String nickName, final String mFbId, Bitmap profilePic) {
   final ParseUser user = ParseUser.getCurrentUser();
   user.put(Common.OBJECT_USER_FB_ID, mFbId);
   updateUserProfile(nickName, profilePic);
 }
 private void updateUserStatus(boolean online) {
   user.put("online", online);
   user.saveEventually();
 }
Пример #26
0
  public void onSignUpClick(View v) {
    // получим данные из полей ввода
    final String username = etUsername.getText().toString();
    final String password = etPassword.getText().toString();
    String email = etEmail.getText().toString();
    final Resources res = getResources();

    // проверим поля ввода. прервем выполнение метода, если встретим ошибку
    if ("".equals(username) || "".equals(password)) {
      Toast.makeText(
              getApplicationContext(),
              res.getString(R.string.blankFieldsSignUpError),
              Toast.LENGTH_SHORT)
          .show();
      return;
    }
    if (!emailValidator.isValid()) {
      Toast.makeText(getApplicationContext(), R.string.emailFormatError, Toast.LENGTH_SHORT).show();
      return;
    }

    // проверки пройдены. сохраним данные нового пользователя на Parse.com
    mProgress.setVisibility(View.VISIBLE);
    showLogInORLogOut(false, false);
    ParseUser user = new ParseUser();
    user.setUsername(username);
    user.setPassword(password);
    user.setEmail(email);
    user.put("IMEI", Util.deviceIMEI);
    user.put("premiumUser", Util.premiumUser);
    user.put("youngIsOnTop", Util.youngIsOnTop);
    user.put("singleTapTimePick", Util.singleTapTimePick);
    user.put("showTaxometer", Util.showTaxometer);
    user.put("userHasAccess", Util.userHasAccess);

    SignUpCallback signUpCallback =
        new SignUpCallback() {
          public void done(ParseException error) {
            if (error == null) {
              Logger.d("SignUp success. Waiting for email confirmation");
              Toast.makeText(
                      getApplicationContext(),
                      res.getString(R.string.confirmEmail),
                      Toast.LENGTH_LONG)
                  .show();
              tvWelcome.setText(res.getString(R.string.confirmEmail));
              // сохранять данные пользователя локально в SharedPreferences логично только после
              // подтверждения от Parse.com
              saveLocalSharedPrefs(username, password);
              showLogInORLogOut(false, true);
            } else {
              Logger.d("SignUp error code " + error.getCode());
              String errorMsg;
              switch (error.getCode()) {
                case 203:
                  errorMsg = res.getString(R.string.emailError);
                  break;
                case 202:
                  errorMsg = res.getString(R.string.usernameError);
                  break;
                case 125:
                  errorMsg = res.getString(R.string.emailFormatError);
                  break;
                default:
                  errorMsg = res.getString(R.string.irregularErrMSG);
                  break;
              }
              Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
              showLogInORLogOut(true, false);
            }
            mProgress.setVisibility(View.INVISIBLE);
          }
        };
    user.signUpInBackground(signUpCallback);
  }
Пример #27
0
  private void signup() {
    final String username = usernameEditText.getText().toString().trim();
    final String password = passwordEditText.getText().toString().trim();
    final String passwordAgain = passwordAgainEditText.getText().toString().trim();

    // Validate the sign up data
    boolean validationError = false;
    StringBuilder validationErrorMessage = new StringBuilder(getString(R.string.error_intro));
    if (username.length() == 0) {
      validationError = true;
      validationErrorMessage.append(getString(R.string.error_blank_username));
    }
    if (password.length() == 0) {
      if (validationError) {
        validationErrorMessage.append(getString(R.string.error_join));
      }
      validationError = true;
      validationErrorMessage.append(getString(R.string.error_blank_password));
    }
    if (!password.equals(passwordAgain)) {
      if (validationError) {
        validationErrorMessage.append(getString(R.string.error_join));
      }
      validationError = true;
      validationErrorMessage.append(getString(R.string.error_mismatched_passwords));
    }
    validationErrorMessage.append(getString(R.string.error_end));

    // If there is a validation error, display the error
    if (validationError) {
      Toast.makeText(SignUpActivity.this, validationErrorMessage.toString(), Toast.LENGTH_LONG)
          .show();
      return;
    }

    // Set up a progress dialog
    final ProgressDialog dialog = new ProgressDialog(SignUpActivity.this);
    dialog.setMessage(getString(R.string.progress_signup));
    dialog.show();

    // Set up a new Parse user
    ParseUser user = new ParseUser();

    user.setUsername(username);
    user.setPassword(password);

    user.put(User.EXIST_PROFILE, false);
    user.put(User.EXIST_COVER, false);

    user.put(User.WISHLIST, new ArrayList<>());
    user.put(User.DONELIST, new ArrayList<>());
    user.put(User.DONE, 0);

    // Call the Parse signup method
    user.signUpInBackground(
        new SignUpCallback() {
          @Override
          public void done(com.parse.ParseException e) {
            dialog.dismiss();
            if (e != null) {
              // Show the error message
              Toast.makeText(SignUpActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            } else {
              // Start an intent for the dispatch activity
              Intent intent = new Intent(SignUpActivity.this, DispatchActivity.class);
              intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
              startActivity(intent);
              overridePendingTransition(
                  R.anim.trans_activity_fade_in, R.anim.trans_activity_fade_out);
            }
          }
        });
  }