Android - 在活动之间传递ParseUser对象

时间:2015-02-19 20:14:57

标签: android parse-platform

在我的Android应用中,我有3项活动供用户填写个人资料并注册:

  • 在第一项活动中,RegisterActivity:用户可以填写他们的姓名,地址,电话号码,紧急联系人等。
  • 第二项活动AppearanceActivity:用户可以填写他们的种族,身高,体重,头发颜色,眼睛颜色等。
  • 在第3个活动中PinsActivity:用户可以填写他们的Pin编号,第二个Pin编号和密码。

我能够传递ParseUser对象并将用户的输入保存在Parse的第1个活动和第2个活动中。但是,在第3次活动中,我无法在Parse上保存Pin编号和密码。我使用Log.d来检查userID,它对所有3个活动都是一样的,Pins和密码字段都有值。我只是不明白为什么我不能使用ParseUser对象的saveInBackground来保存最后一个活动中的Pins和密码。我想知道是否有专家可以帮助我。非常感谢你。

第一次注册活动:     公共类RegisterActivity扩展了Activity {

protected EditText mFirstName;
protected EditText mMiddleName;
protected EditText mLastName;
protected EditText mUserEmail;
protected EditText mPhoneNumber;
protected EditText mAddressLine1;
protected EditText mAddressLine2;
protected EditText mEmergencyName;
protected EditText mEmergencyPhone;
protected EditText mEmergencyRelationship;
protected EditText mEmergencyOtherInfo;
protected Button mNextPageButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    //Parse.enableLocalDatastore(this);
    Parse.initialize(this, "XXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXX");

    //Initialize
    mFirstName = (EditText)findViewById(R.id.firstNameRegisterEditText);
    mMiddleName = (EditText)findViewById(R.id.middleNameRegisterEditText);
    mLastName = (EditText)findViewById(R.id.lastNameRegisterEditText);
    mUserEmail = (EditText)findViewById(R.id.emailRegisterEditText);
    mPhoneNumber = (EditText)findViewById(R.id.phoneRegisterEditText);
    mAddressLine1 = (EditText)findViewById(R.id.addressRegisterText);
    mAddressLine2 = (EditText)findViewById(R.id.address2RegisterText);
    mEmergencyName = (EditText)findViewById(R.id.emergencyNameEditText);
    mEmergencyPhone = (EditText)findViewById(R.id.emergencyPhoneEditText);
    mEmergencyRelationship = (EditText)findViewById(R.id.emergencyRelationshipEditText);
    mEmergencyOtherInfo = (EditText)findViewById(R.id.medicalInfoEditText);
    mNextPageButton = (Button)findViewById(R.id.nextPageButton);

    //Listen to register button click
    mNextPageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Get first name, middle name, last name, user email, phone number, address line 1, address line 2,
            //emergency name, emergency phone, emergency relationship, emergency other info and convert them to string
            String firstName = mFirstName.getText().toString().trim();
            String middleName = mMiddleName.getText().toString().trim();
            String lastName = mLastName.getText().toString().trim();
            String userEmail = mUserEmail.getText().toString().trim();
            String phoneNumber = mPhoneNumber.getText().toString().trim();
            String addressLine1 = mAddressLine1.getText().toString().trim();
            String addressLine2 = mAddressLine2.getText().toString().trim();
            String emergencyName = mEmergencyName.getText().toString().trim();
            String emergencyPhone = mEmergencyPhone.getText().toString().trim();
            String emergencyRelationship = mEmergencyRelationship.getText().toString().trim();
            String emergencyOtherInfo = mEmergencyOtherInfo.getText().toString().trim();

            //String password = mUserPassword.getText().toString().trim();

            final ParseUser user = new ParseUser();

            //Store user in parse
            user.put("firstName", firstName);
            user.put("middleName", middleName);
            user.put("lastName", lastName);
            user.put("email", userEmail);
            user.put("phoneNumber", phoneNumber);
            user.put("addressLine1", addressLine1);
            user.put("addressLine2", addressLine2);
            user.put("emergencyName", emergencyName);
            user.put("emergencyPhone", emergencyPhone);
            user.put("emergencyRelationship", emergencyRelationship);
            user.put("otherInfo", emergencyOtherInfo);
            user.put("username", userEmail);

            //Store empty values for username, password, and email because the signUpInBackground requires these fields
            //We will actually add these values in later
            user.setUsername(userEmail);
            user.setEmail(userEmail);
            user.setPassword("");

            //Need to call Signup first
            user.signUpInBackground(new SignUpCallback() {
                @Override
                public void done(ParseException e) {
                    if (e == null){
                        //Saved successfully
                        //Passing user object to AppearanceActivity and take user to appearance register page
                        Intent intent = new Intent(RegisterActivity.this, AppearanceActivity.class);
                        intent.putExtra("user_id", user.getObjectId());
                        startActivity(intent);
                    } else {
                        //Save failed
                        Log.d("", "User update error: " + e);
                    }
                }
            });
        }
    });
}
}

2nd AppearanceActivity

public class AppearanceActivity extends Activity {
protected EditText mEthnicity;
protected EditText mHeight;
protected EditText mWeight;
protected EditText mHairColor;
protected EditText mEyeColor;
protected EditText mBirthday;
protected EditText mGender;
protected Button mNextPageButtonOnAppearance;
String userId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_appearance);

    //Receiving
    Intent intent = getIntent();
    //assigns data that was passed from previous activity.
    userId = intent.getExtras().getString("user_id");
    Log.d("Kiem", "userID is: " + userId);

    //sets variables to their respective xml elements.
    mEthnicity = (EditText)findViewById(R.id.ethnicityEditText);
    mHeight = (EditText)findViewById(R.id.heightNumberPicker);
    mWeight = (EditText)findViewById(R.id.weightEditText);
    mHairColor = (EditText)findViewById(R.id.hairEditText);
    mEyeColor = (EditText)findViewById(R.id.eyeEditText);
    mBirthday = (EditText)findViewById(R.id.birthdayDatePicker);
    mGender = (EditText)findViewById(R.id.genderEditText);
    mNextPageButtonOnAppearance = (Button)findViewById(R.id.nextPageButtonOnAppearance);

    //Listen to Next Page button to click
    mNextPageButtonOnAppearance.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            //Get ethnicity, height, weight, hair color, eye color, birthday, gender and covert them to string
            final String ethnicity = mEthnicity.getText().toString().trim();
            final String height = mHeight.getText().toString().trim();
            final String weight = mWeight.getText().toString().trim();
            final String hairColor = mHairColor.getText().toString().trim();
            final String eyeColor = mEyeColor.getText().toString().trim();
            String birthday = mBirthday.getText().toString().trim();
            final String gender = mGender.getText().toString().trim();

            ParseQuery<ParseUser> query = ParseUser.getQuery();
            query.whereEqualTo("objectId", userId);
            // Execute the query to find the object with ID
            query.getInBackground(userId, new GetCallback<ParseUser>() {
                public void done(final ParseUser user, ParseException e) {
                    if (e == null) {
                        user.put("ethnicity", ethnicity);
                        user.put("hairColor", hairColor);
                        user.put("eyeColor", eyeColor);
                        user.put("gender", gender);
                        user.put("height", height);
                        user.put("weight", weight);

                        user.saveInBackground(new SaveCallback() {
                            @Override
                            public void done(ParseException e) {
                                if(e == null){
                                    //Saved successfully
                                    //Passing user object to PinsActivity and take user to Pins register page
                                    Intent intent = new Intent(AppearanceActivity.this, PinsActivity.class);
                                    intent.putExtra("user_id", user.getObjectId());
                                    startActivity(intent);
                                } else {
                                    //Save failed
                                    Log.d("", "User update error: " + e);
                                }
                            }
                        });

                    } else {
                        //Log.d("Kiem", "Error: " + e.getMessage());
                    }
                }
            });


        }
    });

//AlertDialog with list view to select ethnicity
public void alertEthnicityListView(View view){
    final CharSequence[] ethics = {"Caucasian", "African American", "Asian", "Hispanic", "Middle-Eastern/Indian","Native American","Other"};
    AlertDialog.Builder builder = new AlertDialog.Builder(AppearanceActivity.this);
    builder.setTitle("Select your ethinicity");
    builder.setItems(ethics, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int ethic) {
            mEthnicity.setText(ethics[ethic]);
        }
    }).show();
}

//AlertDialog with list view to select hair color
public void alertHairListView(View view){
    final CharSequence[] hairs = {"Brown", "Black", "Blonde", "Red", "Strawberry-Blonde", "Dirty-Blonde", "Dyed-Pink", "Dyed-Blue", "Dyed-Green", "Dyed-Purple", "Dyed-Red"};
    AlertDialog.Builder builder = new AlertDialog.Builder(AppearanceActivity.this);
    builder.setTitle("Select your hair color");
    builder.setItems(hairs, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int hair) {
            mHairColor.setText(hairs[hair]);
        }
    }).show();
}

//AlertDialog with list view to select eye color
public void alertEyeListView(View view){
    final CharSequence[] eyes = {"Green", "Blue", "Hazel", "Brown", "Amber", "Other"};

    AlertDialog.Builder builder = new AlertDialog.Builder(AppearanceActivity.this);
    builder.setTitle("Select your eye color");
    builder.setItems(eyes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int eye) {
            mEyeColor.setText(eyes[eye]);
        }
    }).show();
}

//AlertDialog with list view to select gender
public void alertGenderListView(View view){
    final CharSequence[] genders = {"Male", "Female"};

    AlertDialog.Builder builder = new AlertDialog.Builder(AppearanceActivity.this);
    builder.setTitle("Select your gender");
    builder.setItems(genders, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int gender) {
            mGender.setText(genders[gender]);
        }
    }).show();
}

//AlertDialog with list view to select birthday
Calendar myCalendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // TODO Auto-generated method stub
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, monthOfYear);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        updateLabel();
    }

};

private void updateLabel() {
    String myFormat = "MM/dd/yy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
    mBirthday.setText(sdf.format(myCalendar.getTime()));
}
}

第三个PinsActivity

public class PinsActivity extends Activity {
protected EditText mPassword;
protected EditText mConfirmPassword;
protected Button mRegisterButton;
protected EditText mPin;
protected EditText mFakePin;
String userId;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pins);

    //Receiving
    Intent intent = getIntent();
    //assigns data that was passed from previous activity.
    userId = intent.getExtras().getString("user_id");
    Log.d("Kiem2", "userID is: " + userId);

    //sets variables to their respective xml elements.
    mPassword = (EditText)findViewById(R.id.passwordEditText);
    mConfirmPassword = (EditText)findViewById(R.id.confirmPasswordEditText);
    mRegisterButton = (Button)findViewById(R.id.registerButton);
    mPin = (EditText)findViewById(R.id.pinEditText);
    mFakePin = (EditText)findViewById(R.id.fakePinEditText);

    //Force soft keyboard to appear for user to type in password and confirm password
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(mPassword, InputMethodManager.SHOW_IMPLICIT);
    imm.showSoftInput(mConfirmPassword, InputMethodManager.SHOW_IMPLICIT);

    //Listen to Register Button to click
    mRegisterButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Kiem3", "userID is: " + userId);
            signup();
        }
    });
}

private void signup(){
    //get values for password, confirm password, pin, fake pin fields and convert them to strings
    final String password = mPassword.getText().toString();
    final String confirmPassword = mConfirmPassword.getText().toString();
    final String pin = mPin.getText().toString().trim();
    final String fakePin = mFakePin.getText().toString().trim();

    Log.d("Value of fakepin ", "is: " + fakePin);

    ParseQuery<ParseUser> query = ParseUser.getQuery();
    query.whereEqualTo("objectId", userId);
    // Execute the query to find the object with ID
    query.getInBackground(userId, new GetCallback<ParseUser>() {
        public void done(final ParseUser user, ParseException e) {
            if (e == null) {
                user.put("password", password);
                user.put("pin", pin);
                user.put("fakePin", fakePin);
                user.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if (e == null) {
                            // Saved successfully.
                            //Passing user object to AppearanceActivity and take user to appearance register page
                            Intent intent = new Intent(PinsActivity.this, MainActivity.class);
                            intent.putExtra("user_id", user.getObjectId());
                            startActivity(intent);
                        } else {
                            // The save failed.
                            Log.d("", "User update error: " + e);
                        }
                    }
                });
                Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
            } else {
                //Log.d("Kiem", "Error: " + e.getMessage());
            }
        }
    });

    //Check if password and confirm password fields are not blank and that they're matched
    boolean validationError = false;
    StringBuilder validationErrorMessage = new StringBuilder(getString(R.string.error_intro));

    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(confirmPassword)) {
        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));

    //Append validationErrorMessage with the appropriate error strings as well as set validationError as errors are detected
    if (validationError) {
        Toast.makeText(PinsActivity.this, validationErrorMessage.toString(), Toast.LENGTH_LONG).show();
        return;
    }
}
}

1 个答案:

答案 0 :(得分:1)

我通过使用bundle传递数据然后在最后一个活动上将数据上传到Parse来解决了这个问题。谢谢你。