Search code examples
androidandroid-fragmentsandroid-fragmentactivity

Pass data from fragment to activity and then to another fragment


I'm brand new to fragment communication so I really need your help. I have a fragment activity and two fragments.

In my Fragment A, I have an edittext (default value is null) where user has to input a number. So to capture the input value, I did this using the addTextChangedListener. And after capturing the new value of edittext, Fragment A has to pass that value (string) to the container activity and this activity has now received the value (string). Right now this activity has to pass the value (string) to Fragment B.

So far this is what I've tried

FragmentActivity:

  public String strDocNum;

  @Override
public void onDataPass(String data) {
    // TODO Auto-generated method stub
    Log.d("Document From", data);
    strDocNum = data;
}

Fragment A:

  OnDataPass dataPasser;

  private void getRecords() {
    // TODO getRecords

    // TODO To call methods from fragment to activity
    ((ReceivingStocks)getActivity()).dbConnect();

    strLastDocumentNumber = ((ReceivingStocks)getActivity()).dbHelper.getLastDocumentNumber();
    Log.d("Doc Num", "" + strLastDocumentNumber);
    etDocumentNumber.setText(strLastDocumentNumber);

    etDocumentFrom.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            // TODO afterTextChanged

        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            System.out.println("Before text changed " + new String(s.toString()));
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {

            System.out.println("Ontext changed " + new String(s.toString()));

            if(s.toString().isEmpty()){

            } else {
                strDocumentFrom = s.toString();
                strTransactionDate = 
                        ((ReceivingStocks)getActivity()).dbHelper.getTransactionDateByDocumentNumber(strDocumentFrom);
                strTotalAmount = 
                        ((ReceivingStocks)getActivity()).dbHelper.getTotalAmountByDocumentNumber(strDocumentFrom);
                strVan = 
                        ((ReceivingStocks)getActivity()).dbHelper.getVanByDocumentNumber(strDocumentFrom);

                etTransactionDate.setText(strTransactionDate);
                etTotalAmount.setText(strTotalAmount);
                Log.d("Van", "" + strVan);
                etVan.setText(strVan);

                // TODO TO PASS DATA FROM FRAGMENT TO ACTIVITY
                dataPasser.onDataPass(strDocumentFrom);

            }

        }     
    });
}


public interface OnDataPass {
    public void onDataPass(String data);
}

public void passData(String data) {
    dataPasser.onDataPass(data);
}

@Override
public void onAttach(Activity a) {
    super.onAttach(a);
    dataPasser = (OnDataPass) a;
}

Fragment B:

   private void getRecords() {
    // TODO getRecords

    // TODO To call methods from fragment to activity
    ((ReceivingStocks)getActivity()).dbConnect();
    String mLabel = ((ReceivingStocks)getActivity()).strDocNum;
    Log.d("Document Number From Header", "" + mLabel);
    strUnitOfMeasure = ((ReceivingStocks)getActivity()).dbHelper.getUnitOfMeasureByDocumentNumber(mLabel);
    strQTY = ((ReceivingStocks)getActivity()).dbHelper.getQTYByDocumentNumber(mLabel);
    strUnitPrice = ((ReceivingStocks)getActivity()).dbHelper.getUnitPriceByDocumentNumber(mLabel);
    strAmount = ((ReceivingStocks)getActivity()).dbHelper.getAmountByDocumentNumber(mLabel);

    try{

        if(mLabel.isEmpty()){

        } else {
            String str = ((ReceivingStocks)getActivity()).dbHelper.getItemCodeByDocumentNumber(mLabel);
            Log.d("Item Code", "" + str);
            etItemCode.setText(str);
            etUnitOfMeasure.setText(strUnitOfMeasure);
            etQuantity.setText(strQTY);
            etUnitPrice.setText(strUnitPrice);
            etAmount.setText(strAmount);
        } 


    } catch(SQLiteException e){
        Log.d("Error", "" + e);
    }


}

So far, I am successful at passing data from Fragment A to Activity. But from Activity to Fragment B it is passing the default value which is null so my logcat throws a NullPointerException. Any ideas? I really am lost. Your help will truly be appreciated by me. Thanks.


Solution

  • If your requirement is to pass value from one fragment to another then try using bundle

    For ex:

    TalkDetail fragment = new TalkDetail();
                            Bundle bundle = new Bundle();
    
                            bundle.putString("title", title);
                            bundle.putString("largeimg", largeimg);
                            bundle.putString("excert", excert);
                            bundle.putString("description",description);
                            bundle.putString("cat", cat);
                            bundle.putString("header_title", "Talk");
                            //bundle.putInt("postid", postid);
    
                            fragment.setArguments(bundle);
                            ((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
    

    Here's your BaseContainerFragment.java class that will help to get better back track and other good stuff

    public class BaseContainerFragment extends Fragment {
    
        public void replaceFragment(Fragment fragment, boolean addToBackStack) {
            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            if (addToBackStack) {
                transaction.addToBackStack(null);
            }
            transaction.replace(R.id.container_framelayout, fragment);
            transaction.commit();
            getChildFragmentManager().executePendingTransactions();
        }
    
        public boolean popFragment() {
            Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
            boolean isPop = false;
            if (getChildFragmentManager().getBackStackEntryCount() > 0) {
                isPop = true;
                getChildFragmentManager().popBackStack();
            }
            return isPop;
        }
    
    }