Search code examples
javaandroidandroid-fragmentsinterfacebundle

Passing the value to two fragments which its container activity by onClick event of another activity


I would like to pass the data from another activity's onClick event to previous activity's FRAGMENT. I can see the log and it shows values from activity to main activity, but it cannot be passed to the main activity's fragments.

I have took a references of this link: Send string from an activity B to a fragment F of activity A

But I am a beginner and has a dumb mind, I tried and cannot get a expected result, and most important is, I don't really understand the idea of the solution.

I was confused on the usage of the interface although I have read many sources and cases during troubleshooting this issue. Or May I use another solution to implement this function?

Thanks for any assistance.

enter image description here

Main activity:

Fragment_step_1 getHashMapStep1 = new Fragment_step_1();
Fragment_step_2 getHashMapStep2 = new Fragment_step_2();
......
public void onCreate(Bundle savedInstanceState) {
    ......
    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        Bundle extrasFrag2 = getIntent().getExtras();
        boolean getFromConfirmPage = getIntent().getBooleanExtra("checkReturn", fromConfirm);
        Log.e("boolean", String.valueOf(getFromConfirmPage));
        if(extras == null) {
            getEmailFromID = null;

        } else {
            if(getFromConfirmPage){
                strFullName = extras.getString("ConfirmFullName");
                strIDNum = extras.getString("ConfirmIDNum");
                strDOB = extras.getString("ConfirmDOB");
                strPhone = extras.getString("ConfirmPhone");
                strEmail = extras.getString("ConfirmEmail");
                strAddress = extras.getString("ConfirmAddress");
                strPlanPrice = extras.getString("plan_price");
                strPlan_type = extras.getString("ConfirmPlanType");
                Bundle argsFrag1 = getHashMapStep1.getArguments();
                Bundle argsFrag2 = getHashMapStep2.getArguments();

                argsFrag1.putString("ConfirmFullName", strFullName);
                argsFrag1.putString("ConfirmIDNum", strIDNum);
                argsFrag1.putString("ConfirmPhone", strPhone);
                argsFrag1.putString("ConfirmEmail", strEmail);
                argsFrag2.putString("ConfirmDOB", strDOB);
                argsFrag2.putString("ConfirmAddress", strAddress);
                getHashMapStep1.setArguments(argsFrag1);
                getHashMapStep2.setArguments(argsFrag2);
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.fragmentPersonal, getHashMapStep1);
                transaction.replace(R.id.fragment_correspondence, getHashMapStep2);
                transaction.addToBackStack(null);

                // Commit the transaction
                transaction.commit();
            } else {
                getEmailFromID = extras.getString("Email ID");
                strPlan_type = extras.getString("Plan_Type");
                strPlanPrice = extras.getString("Plan_Price");
            }
        }
        ......
        else {
            Intent confirmInsure = new Intent(/*main_activity*/.this, /*activity_with_edit_btn*/.class);
            Bundle extras = new Bundle();
            extras.putString("ConfirmFullName", strFullName);
            extras.putString("confirmDOB", strDOB);
            extras.putString("ConfirmIDNum", strIDNum);
            extras.putString("ConfirmPhone", strPhone);
            extras.putString("ConfirmEmail", strEmail);
            extras.putString("ConfirmAddress", strAddress);
            extras.putString("plan_type", strPlan_type);
            extras.putString("plan_price", strPlanPrice);
            confirmInsure.putExtras(extras);
            startActivity(confirmInsure);
        }
    }
......

}

Activity with "Edit" button:

......
btn_editInfo.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent confirmInsure = new Intent(/*activity_with_edit_btn*/.this, /*To_main_activity*/.class);
            Bundle extras = new Bundle();
            extras.putString("ConfirmFullName", CustName);
            extras.putString("ConfirmIDNum", IDNum);
            extras.putString("ConfirmDOB", strDOB);
            extras.putString("ConfirmPhone", PhoneNo);
            extras.putString("ConfirmEmail", email);
            extras.putString("ConfirmAddress", rAddress);
            extras.putString("ConfirmPlanType", formatPlanType);
            extras.putString("plan_price", planPrice);
            extras.putBoolean("checkReturn", fromConfirm);
            confirmInsure.putExtras(extras);
            startActivity(confirmInsure);
        }
    });
 ......

Fragment 1 & 2:

......
@Override   //SHOULD I GET VALUES ON THIS METHOD?
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
        Bundle args = this.getArguments();
        if (args != null) {
            strName = args.getString("ConfirmFullName");
            strHKID = args.getString("ConfirmIDNum");
            strTel = args.getString("ConfirmPhone");
            strEmail = args.getString("ConfirmEmail");
            name.setText(strName);
            HKIDNumber.setText(strHKID);
            getEmail.setText(strEmail);
            phone.setText(strTel);
        }
        //REMAIN TWO VALUES ARE GETTING ON FRAGMENT_2
}
......

Solution

  • You can use DataHolder(Singleton) to hold the values. You can set value from your second activity and you can get in your fragments(or in in whole application-wherever you want). Singletons have one instance all over the application. It can hold throughout your application. You can access them from activity, fragment, interfaces,etc., It will be helpful to hold data and pass data between activity-fragment, fragment-activity, fragment-fragment.

    Create DataHolder.java

    public class DataHolder {
    
    private static DataHolder mInstance;
    private String name, idNumber, dob, address, planType; //fields you want
    
    //add all the fields you want--like email,phoneNUmber,etc.,
    
    public static DataHolder getInstance() {
        if (mInstance == null)
            return mInstance = new DataHolder();
        else
            return mInstance;
    }
    
    //getters and setters for the fields
    
    public String getAddress() {
        return address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    
    public String getDob() {
        return dob;
    }
    
    public void setDob(String dob) {
        this.dob = dob;
    }
    
    public String getIdNumber() {
        return idNumber;
    }
    
    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getPlanType() {
        return planType;
    }
    
    public void setPlanType(String planType) {
        this.planType = planType;
    }
    
    //define getters and setters for all defined fields
    }
    

    In your Activity2,

        DataHolder holder;
        btn_editInfo.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            holder = DataHolder.getInstance(); //Getting DataHolder Instance
            holder.setName(CustName);
            holder.setIdNumber(IDNum);
            //set values for all fields using setters
            //holder.setSomething(something);
    
            //Start your first activity
            Intent confirmInsure = new Intent(/*activity_with_edit_btn*/.this, /*To_main_activity*/.class);
            startActivity(confirmInsure);
        }});
    

    In your Fragment 1 and 2,

        DataHolder holder;
        @Override
        public void onActivityCreated(Bundle savedInstanceState){
          super.onActivityCreated(savedInstanceState);
          holder = DataHolder.getInstance();   //get instance of DataHolder
          name.setText(holder.getName());     //get customer name by getName()
          // do the same for all fields
          HKIDNumber.setText(holder.getIdNumber());
          getEmail.setText(holder.getEmail());
          phone.setText(holder.getPhNumber());
        }
    

    Hope it will help you.