0

I have this scenario where I have An Activity(A) which has 2 tabs (ie. two fragments FA1,FA2) . The appBar in Activity A has a filter button which opens different Activities(B & C) depending on which tab is selected. this has been handled by the following code in A.

  toolbar.findViewById(R.id.filterimage).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = null;
            if (tabLayout.getSelectedTabPosition() == 1) {
                i = new Intent(A.this, B.class);

            } else {
                i = new Intent(A.this, C.class);
            }
            startActivityForResult(i, 221);

        }
    });

all the api hits to show data in two fragments are made in the respective fragments. Filter which has been selected from Activity B or C is returned to activity A . Now depending on the filters selected I want to refresh the fragment(FA1 or FA2) again from it's parent activity ie. A. But I am unable to do so . How can I do this?

Nikaido
  • 4,443
  • 5
  • 30
  • 47
rajat44
  • 4,941
  • 6
  • 29
  • 37

2 Answers2

2
@Override
protected void onResume() {
    super.onResume();

 // Where currentFragment is the fragment you want to refresh

 getSupportFragmentManager()
.beginTransaction()
.detach(currentFragment)
.commitNowAllowingStateLoss();

 getSupportFragmentManager()
.beginTransaction()
.attach(currentFragment)
.commitAllowingStateLoss();

 }

Here you have to check particular case when it comes from B or C activity, otherwise don't refresh.

Reporter
  • 3,897
  • 5
  • 33
  • 47
Nisarg
  • 1,358
  • 14
  • 30
  • It worked !! But what does above code do ? Can you please explain the code . Thanks!! – rajat44 May 18 '17 at 10:17
  • @rajat44 good to hear that, as name indicates using first 4 lines we detach your fragment and after that it attaches as if it loads at first time. and for commitAllowingStateLoss please check [this](http://stackoverflow.com/a/18345684/3117966) for more info – Nisarg May 18 '17 at 11:03
0

Use different request code for both like below:

toolbar.findViewById(R.id.filterimage).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent i = null;
        if (tabLayout.getSelectedTabPosition() == 1) {
            i = new Intent(A.this, B.class);
            startActivityForResult(i, 221);

        } else {
            i = new Intent(A.this, C.class);
            startActivityForResult(i, 222);
        }

    }
});

Then depends on request code get result and update fragments data.

Nitin Patel
  • 1,605
  • 13
  • 31