所以基本上这是我的例子

活动A,B和C。

假设我想将变量从A发送到C,同时打开活动B。我当时在考虑多个意图,但这似乎行不通。请帮一个简单的例子。

“活动A”

package com.example.munaseribrahimewallet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.content.SharedPreferences;
import android.view.MotionEvent;
import android.view.View;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

public class SignUpActivity extends AppCompatActivity{


    //we will use these constants later to pass the Member name and id to another activity
    public static final String EXTRA_EMAIL = "com.example.munaseribrahimewallet.EXTRA_NAME";
    private DatePickerDialog mDatePickerDialog;






    private static final Pattern PASSWORD_PATTERN =
            Pattern.compile("^" +
                    //"(?=.*[0-9])" +         //at least 1 digit
                    //"(?=.*[a-z])" +         //at least 1 lower case letter
                    //"(?=.*[A-Z])" +         //at least 1 upper case letter
                    "(?=.*[a-zA-Z])" +      //any letter
                    "(?=.*[@#$%^&+=])" +    //at least 1 special character
                    "(?=\\S+$)" +           //no white spaces
                    ".{4,}" +               //at least 4 characters
                    "$");

    private EditText inputEmail, inputPassword, confirmPassword,editDate;     //hit option + enter if you on mac , for windows hit ctrl + enter
    private Button btnSignIn, btnSignUp, btnResetPassword;
    private ProgressBar progressBar;
    private FirebaseAuth mAuth;
    DatabaseReference reff;
    Member member;
    long maxid = 0;

    String email, password, cPassword, id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        //Get Firebase auth instance
        mAuth = FirebaseAuth.getInstance();
        reff = FirebaseDatabase.getInstance().getReference("Members");


        btnSignIn = (Button) findViewById(R.id.sign_in_button);
        btnSignUp = (Button) findViewById(R.id.sign_up_button);
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        confirmPassword = (EditText) findViewById(R.id.password2);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btnResetPassword = (Button) findViewById(R.id.btn_reset_password);
        editDate = (EditText) findViewById(R.id.editDateBirth);


        reff = FirebaseDatabase.getInstance().getReference().child("Member");
        reff.addValueEventListener(
                new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.exists())
                            maxid = (dataSnapshot.getChildrenCount());
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }



                });



        btnResetPassword.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(SignUpActivity.this, ResetPasswordActivity.class));
                    }
                });

        btnSignIn.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                        startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
                    }
                });

        btnSignUp.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        email = inputEmail.getText().toString();
                        password = inputPassword.getText().toString();
                        cPassword = confirmPassword.getText().toString();

                        if (TextUtils.isEmpty(email)) {
                            Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (TextUtils.isEmpty(password)) {
                            Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (TextUtils.isEmpty(cPassword)) {
                            Toast.makeText(getApplicationContext(), "Confirm password!", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (password.length() < 6) {
                            Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!(password.matches(cPassword))) {
                            Toast.makeText(getApplicationContext(), "Password and Confirmation Password are not the same!", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        progressBar.setVisibility(View.VISIBLE);
                        //create user
                        mAuth.createUserWithEmailAndPassword(email, password)
                                .addOnCompleteListener(SignUpActivity.this,
                                        new OnCompleteListener<AuthResult>() {
                                            @Override
                                            public void onComplete(@NonNull Task<AuthResult> task) {
                                                Toast.makeText(SignUpActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                                                progressBar.setVisibility(View.GONE);
                                                // If sign in fails, display a message to the user. If sign in succeeds
                                                // the auth state listener will be notified and logic to handle the
                                                // signed in user can be handled in the listener.
                                                if (!task.isSuccessful()) {
                                                    Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
                                                            Toast.LENGTH_SHORT).show();
                                                } else {
                                                    mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(
                                                            new OnCompleteListener<Void>() {
                                                                @Override
                                                                public void onComplete(@NonNull Task<Void> task) {


                                                                    if (task.isSuccessful()) {

                                                                        Toast.makeText(SignUpActivity.this, "Registered successfully. Please check your email for verification", Toast.LENGTH_SHORT).show();
                                                                        inputEmail.setText("");
                                                                        inputPassword.setText("");


                                                                        Intent intent = new Intent(SignUpActivity.this, ProfileActivity.class);
                                                                        intent.putExtra(EXTRA_EMAIL, email);
                                                                        startActivity(intent);

                                                                        finish();
                                                                    }
                                                                }
                                                            });
                                                }
                                            }
                                        });




                    }


                });

    }




    @Override
    protected void onResume() {
        super.onResume();
        progressBar.setVisibility(View.GONE);
    }

    private boolean validateEmail() {
        String emailInput = inputEmail.getText().toString().trim();

        if (emailInput.isEmpty()) {
            inputEmail.setError("Field can't be empty");
            return false;
        } else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) {
            inputEmail.setError("Please enter a valid email address");
            return false;
        } else {

            inputEmail.setError(null);
            return true;
        }
    }
    private boolean validatePassword() {
        String passwordInput = inputPassword.getText().toString().trim();

        if (passwordInput.isEmpty()) {
            inputPassword.setError("Field can't be empty");
            return false;
        } else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) {
            inputPassword.setError("Password too weak");
            return false;
        } else {
            inputPassword.setError(null);
            return true;
        }
    }

    public void addMember() {
        //getting the values to save
        email = inputEmail.getText().toString().trim();
        id = reff.push().getKey();


        //checking if the value is provided
        if (!TextUtils.isEmpty(email)) {
            //getting a unique id using push().getKey() method
            //it will create a unique id and we will use it as the Primary Key for our Contact

            //Saving the Contact
            reff.child(id).setValue(member);


            //setting edittext to blank again
            inputEmail.setText("");
            inputPassword.setText("");

            //displaying a success toast
            Toast.makeText(this, "Member added", Toast.LENGTH_LONG).show();
        } else {
            //if the value is not given displaying a toast
            Toast.makeText(this, "Please enter a email", Toast.LENGTH_LONG).show();
        }
    }
    private boolean updateMember(String id, String email) {
        //getting the specified Contact reference
        DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Member").child(id);

        //updating Contact
        //Member member = new Member(id, email);
        dR.setValue(member);

        return true;
    }


}


“活动B”

package com.example.munaseribrahimewallet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import org.w3c.dom.Text;

public class PaypalDB extends AppCompatActivity {

    private Button btnPaypalLogin;
    private EditText editPaypalLogin;
    private TextView temail, thomeAddress, tcountry, tcompanyName, tcompanyAddress, tzipcode, tdate, tname, tpaypalEmail;
    Member member;
    DatabaseReference reff;
    String memail, mhomeAddress, mcountry, mcompanyName, mcompanyAddress, mzipcode, mdate, mname, mpaypalEmail, mid;
    long maxid = 0;



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

        reff = FirebaseDatabase.getInstance().getReference("Members");

        editPaypalLogin = (EditText) findViewById(R.id.editPaypalLogin);
        btnPaypalLogin = (Button) findViewById(R.id.btnPaypalLogin);

        temail= (TextView) findViewById(R.id.txtemail);
        thomeAddress= (TextView) findViewById(R.id.txthomeaddress);
        tcountry= (TextView) findViewById(R.id.txtcountry);
        tcompanyName= (TextView) findViewById(R.id.txtcompanyname);
        tzipcode= (TextView) findViewById(R.id.txtzipcode);
        tdate= (TextView) findViewById(R.id.txtdate);
        tname= (TextView) findViewById(R.id.txtname);
        tcompanyAddress = (TextView) findViewById(R.id.txtcompany);


        reff = FirebaseDatabase.getInstance().getReference().child("Member");
        reff.addValueEventListener(
                new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.exists())
                            maxid = (dataSnapshot.getChildrenCount());
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }



                });
        btnPaypalLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Bundle extras = getIntent().getExtras();
                memail = extras.getString("EXTRA_EMAIL");


                mhomeAddress = extras.getString("EXTRA_HOMEADDRESS");
                mcountry = extras.getString("EXTRA_SPINNERCOUNTRYTEXT");
                mcompanyName = extras.getString("EXTRA_COMPANYNAME");
                mcompanyAddress = extras.getString("EXTRA_COMPANYADDRESS");
                mzipcode = extras.getString("EXTRA_ZIPCODE");
                mdate = extras.getString("EXTRA_DATE");
                mname = extras.getString("EXTRA_NAME");


                mpaypalEmail = editPaypalLogin.getText().toString();

                tcompanyAddress.setText(mcompanyAddress);
                tname.setText(mname);

                mid = reff.push().getKey();

                DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Member").child(mid);

                reff.child(mid).setValue(member);
                member = new Member(mid, memail, mdate, mhomeAddress, mcountry, mcompanyName, mcompanyAddress, mzipcode, mpaypalEmail, mname);
                dR.setValue(member);
            }

        });
    }
}

最佳答案

尝试使用sharedPreference

创建SharedPreferences

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();


将数据存储为KEY / VALUE对

editor.putBoolean("key_name1", true);           // Saving boolean - true/false
editor.putInt("key_name2", "int value");        // Saving integer
editor.putFloat("key_name3", "float value");    // Saving float
editor.putLong("key_name4", "long value");      // Saving long
editor.putString("key_name5", "string value");  // Saving string

// Save the changes in SharedPreferences
editor.commit(); // commit changes


获取SharedPreferences数据

// If value for key not exist then return second param value - In this case null

boolean userFirstLogin= pref.getBoolean("key_name1", true);  // getting boolean
int pageNumber=pref.getInt("key_name2", 0);             // getting Integer
float amount=pref.getFloat("key_name3", null);          // getting Float
long distance=pref.getLong("key_name4", null);          // getting Long
String email=pref.getString("key_name5", null);         // getting String
Deleting Key value from SharedPreferences

editor.remove("key_name3"); // will delete key key_name3
editor.remove("key_name4"); // will delete key key_name4

// Save the changes in SharedPreferences
editor.commit(); // commit changes


从SharedPreferences清除所有数据

 editor.clear();
 editor.commit(); // commit changes


如果您难以理解我的解决方案,请参考This to get more details

关于java - Android Studio将变量发送到其他 Activity 并同时打开 Activity ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57127284/

10-10 22:29