How to refresh RecyclerView in one fragment when data changed in another fragment

10,003

Solution 1

Try this,

Create an Interface in EngagedFragment say,

public interface SubmitListener {

    void onSubmit();
}

private SubmitListener onSubmitListener;

public void setSubmitListener(SubmitListener onSubmitListener){
        this.onSubmitListener = onSubmitListener;
}

public SubmitListener getOnSubmitListener(){
        return onSubmitListener;
}

In saveToLocalDB(...) method

call

onSubmitListener.onSubmit();

In MainActivity:

1) Update the below statement:

public class MainActivity extends AppCompatActivity implements EngagedFragment.SubmitListener

2) Make your ViewPagerAdapter adapter; variable as Global variable;

while adding fragment:

EngagedFragment engagedFrag = new EngagedFragment();
adapter.addFrag(engagedFrag, "ENGAGED ID");

...
viewPager.setAdapter(adapter);

3) add this after setting adapter

engagedFrag.setSubmitListener(this);

4) Override onSubmit() method and try the below code in that method

if(viewPager != null){

    if(adapter != null){
        Fragment fragment = adapter.getItem(2);
        if(fragment != null){
            RequestFragment requestFragment = (RequestFragment) fragment;
            requestFragment.setRecyclerView();
        }
    }
}

Solution 2

try this

mViewPager.setOffscreenPageLimit(0); 

if that doesnt help, please check below SO question:

fragment refresh On Swip

and about : mViewPager.setOffscreenPageLimit(0); this might not work as i found in one of @commonware 's answer's, the following :-

"Does ViewPager require a minimum of 1 offscreen pages Yes. If I am reading the source code correctly, you should be getting a warning about this in LogCat, something like:

Requested offscreen page limit 0 too small; defaulting to 1"
Share:
10,003
Bertho Joris
Author by

Bertho Joris

My Life Is My Adventure

Updated on June 05, 2022

Comments

  • Bertho Joris
    Bertho Joris almost 2 years

    How do I refresh the data from a local database to RecyclerView when data was successfully submitted? I use the tabs on the application. 2nd-Tab functions to submit the data, and if successful, the data will be stored in localDB.

    Data on localDB I will present at the 3rd-Tab. But what happens, I have to swipe 1st-Tab, then swipe to the 2nd-Tab and then swipe to the new 3rd-Tab data on my localDB successfully displayed.

    If the 2nd-Tab me to submit the data, then I swipe to 3rd-Tab, the data will not appear on the list of data. How do I get the data directly displayed without the need to swipe to the first 1st-Tab and then to the 2nd-Tab and 3rd-Tab ??? 2nd-Tab

    MainActivity :

    import android.os.Bundle;
    import android.support.design.widget.TabLayout;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    
    import com.bertho.gmyl.fragments.EngagedFragment;
    import com.bertho.gmyl.fragments.RequestFragment;
    import com.bertho.gmyl.fragments.SigninFragment;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        private static final String TAG = MainActivity.class.getSimpleName();
    
        private Toolbar toolbar;
        private TabLayout tabLayout;
        private ViewPager viewPager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.engine_main);
    
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
            viewPager = (ViewPager) findViewById(R.id.viewpager);
            setupViewPager(viewPager);
    
            tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(viewPager);
        }
    
        private void setupViewPager(ViewPager viewPager) {
            ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
            adapter.addFrag(new SigninFragment(), "SIGN-IN");
            adapter.addFrag(new EngagedFragment(), "ENGAGED ID");
            adapter.addFrag(new RequestFragment(), "LOCATION");
            viewPager.setAdapter(adapter);
        }
    
        class ViewPagerAdapter extends FragmentPagerAdapter {
            private final List<Fragment> mFragmentList = new ArrayList<>();
            private final List<String> mFragmentTitleList = new ArrayList<>();
    
            public ViewPagerAdapter(FragmentManager manager) {
                super(manager);
            }
    
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }
    
            @Override
            public int getCount() {
                return mFragmentList.size();
            }
    
            public void addFrag(Fragment fragment, String title) {
                mFragmentList.add(fragment);
                mFragmentTitleList.add(title);
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                return mFragmentTitleList.get(position);
            }
        }
    
    }
    

    EngagedFragment (2nd-Tab) Form to save data

    import android.os.Bundle;
    import android.support.design.widget.Snackbar;
    import android.support.v4.app.Fragment;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.RelativeLayout;
    import android.widget.TextView;
    
    import com.bertho.gmyl.R;
    import com.bertho.gmyl.model.Engaged;
    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 com.bertho.gmyl.realm.RealmHelper;
    
    public class EngagedFragment extends Fragment implements View.OnClickListener {
    
        private static final String TAG = EngagedFragment.class.getSimpleName();
    
        private EditText nama, email, nohp;
        private Button btnSaveConnection;
        private DatabaseReference mFirebaseDatabase;
        private FirebaseDatabase mFirebaseInstance;
        private RelativeLayout mRoot;
        private View rootView;
        private String userId;
        private TextView lblNama, lblEmail, lblNohp;
        private RelativeLayout relativeLayout;
    
        private RealmHelper realmHelper;
    
    
        public EngagedFragment() {
            // Required empty public constructor
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            rootView = inflater.inflate(R.layout.fragment_engaged, container, false);
    
            realmHelper = new RealmHelper(getActivity());
    
            String appName = getResources().getString(R.string.app_name);
    
            loadLocalDB();
    
            nama = (EditText) rootView.findViewById(R.id.txtName);
            email = (EditText) rootView.findViewById(R.id.txtEmail);
            nohp = (EditText) rootView.findViewById(R.id.txtNoHp);
    
            lblNama = (TextView) rootView.findViewById(R.id.lblNameval);
            lblEmail = (TextView) rootView.findViewById(R.id.lblEmailval);
            lblNohp = (TextView) rootView.findViewById(R.id.lblNohpval);
            relativeLayout = (RelativeLayout) rootView.findViewById(R.id.panelLabelDetail);
            btnSaveConnection = (Button) rootView.findViewById(R.id.btnEngaged);
    
    
            mFirebaseInstance = FirebaseDatabase.getInstance();
    
            mFirebaseDatabase = mFirebaseInstance.getReference("tbl_engaged");
    
            mFirebaseInstance.getReference("titleapp").setValue(appName);
    
            mFirebaseInstance.getReference("titleapp").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Log.e(TAG, "TITLE UPDATED FROM FIREBASE");
                    String appTitle = dataSnapshot.getValue(String.class);
                    ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(appTitle);
                }
    
                @Override
                public void onCancelled(DatabaseError error) {
                    Log.e(TAG, "FAILED TO READ TITLE FROM FIREBASE.", error.toException());
                }
            });
    
            btnSaveConnection.setOnClickListener(this);
    
            return rootView;
        }
    
        private void showSnack(String notify) {
            mRoot = (RelativeLayout) rootView.findViewById(R.id.frag_engaged);
            Snackbar snackbar = Snackbar.make(mRoot, notify, Snackbar.LENGTH_LONG);
            snackbar.show();
        }
    
        public void onClick(View v) {
    
            if(v.getId() == R.id.btnEngaged) {
    
                String txtName = nama.getText().toString();
                String txtEmail = email.getText().toString();
                String txtNo = nohp.getText().toString();
    
                if(txtName.equals("") || txtName.isEmpty()) {
                    showSnack("Name must filled");
                    nama.requestFocus();
                } else if (txtEmail.equals("") || txtEmail.isEmpty()) {
                    showSnack("Email must filled");
                    email.requestFocus();
                } else if (txtNo.equals("") || txtNo.isEmpty()) {
                    showSnack("No.HP must filled");
                    nohp.requestFocus();
                } else {
                    createUser(txtName, txtEmail, txtNo);
                    saveToLocalDB(txtName, txtEmail, txtNo);
                }
            }
        }
    
        private void saveToLocalDB(String txtName, String txtEmail, String txtNo) {
            realmHelper.addEngaged(txtName, txtEmail, txtNo);
        }
    
        private void loadLocalDB() {
            realmHelper.getAllData();
        }
    
        private void createUser(String name, String email, String nohp) {
            userId = mFirebaseDatabase.push().getKey();
            Engaged user = new Engaged(name, email, nohp);
            mFirebaseDatabase.child(userId).setValue(user);
            addUserChangeListener();
        }
    
        private void addUserChangeListener() {
    
            mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Engaged user = dataSnapshot.getValue(Engaged.class);
    
                    if (user == null) {
                        Log.e(TAG, "ENGAGED DATA IS NULL");
                        return;
                    }
    
                    Log.e(TAG, "ENGAGED DATA IS CHANGED!" + user.name + ", " + user.email);
    
                    lblNama.setText(user.name);
                    lblEmail.setText(user.email);
                    lblNohp.setText(user.nohp);
    
                    //relativeLayout.setVisibility(View.VISIBLE);
    
                    nama.setText("");
                    email.setText("");
                    nohp.setText("");
                }
    
                @Override
                public void onCancelled(DatabaseError error) {
                    // Failed to read value
                    Log.e(TAG, "FAILED TO READ USER", error.toException());
                }
            });
        }
    }
    

    RequestFragment (3rd-Tab) To display localDB

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    
    import com.bertho.gmyl.R;
    import com.bertho.gmyl.adapter.AdapterEngaged;
    import com.bertho.gmyl.model.ModelEngaged;
    import com.bertho.gmyl.realm.RealmHelper;
    
    import java.util.ArrayList;
    
    public class RequestFragment extends Fragment {
    
        private static final String TAG = "RequestFragment";
        private RecyclerView recyclerView;
        private View rootView;
        private ArrayList<ModelEngaged> data;
        private RealmHelper helper;
    
        public RequestFragment() {
            // Required empty public constructor
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            rootView =  inflater.inflate(R.layout.fragment_request, container, false);
    
            data = new ArrayList<>();
            helper = new RealmHelper(getActivity());
    
            recyclerView = (RecyclerView) rootView.findViewById(R.id.rvArticle);
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    
            setRecyclerView();
    
            return rootView;
        }
    
        public void setRecyclerView() {
            try {
                data = helper.findAllArticle();
            } catch (Exception e) {
                e.printStackTrace();
            }
            AdapterEngaged adapter = new AdapterEngaged(data, new AdapterEngaged.OnItemClickListener() {
                @Override
                public void onClick(ModelEngaged item) {
                    Toast.makeText(getContext(), "LIST CLICKED", Toast.LENGTH_LONG).show();
                }
            });
            recyclerView.setAdapter(adapter);
        }
    
        @Override
        public void onResume() {
            super.onResume();
            try {
                data = helper.findAllArticle();
            } catch (Exception e) {
                e.printStackTrace();
            }
            setRecyclerView();
        }
    
    
    }
    

    Everything went smoothly, it's just that I hope the data can be displayed when the form is submitted and can be directly viewed on the 3rd-Tab

  • Bertho Joris
    Bertho Joris over 7 years
    Yes..not work with viewPager.setOffscreenPageLimit(0);
  • Bawa
    Bawa over 7 years
    Did you try the linked answer ?
  • Bertho Joris
    Bertho Joris over 7 years
    Not yet...But I will try after this
  • Bertho Joris
    Bertho Joris over 7 years
    Hai @Raghavendra, when I try your code, I found force close when button save clicked. Error java.lang.NullPointerException: Attempt to invoke interface method 'void com.bertho.gmyl.fragments.EngagedFragment$SubmitListener.onS‌​ubmit()' on a null object reference Maybe I miss something. But, when I check, data is saved. Only force close my app. This is MainActivity : pastebin.com/mnMVzkjr This is EngagedFragment : pastebin.com/bWgSGmuk
  • Bertho Joris
    Bertho Joris over 7 years
    Yeaahh.....perfect works..... :) Thanks @Raghavendra... Btw if I have a another tab, let say 5th tab, I must overide code inside onSubmit method again?
  • Raghavendra
    Raghavendra over 7 years
    @BerthoJoris Glad! that helped. I didn't get the qsn dude. Can u rephrase it what u want to do in 5th tab?
  • Raghavendra
    Raghavendra over 7 years
    @BerthoJoris okay if u have similar thing in 5th tab if u want to track some updates create another interface in 5th tab and follow the same steps.
  • Bertho Joris
    Bertho Joris over 7 years
    For example I want the same thing in the fifth tab (same as the third tab now). Data is submitted will go to the fifth tab without having to swipe it first to a few tabs. Everything can I modif in the onSubmit method like code above?
  • Silambarasan
    Silambarasan over 4 years
    Thank you @Raghavendra ...It's working perfectly. Thanks a lot