Suppose we have an application for viewing notes using fragments and RecyclerView . Notes are stored in the database.
If we write the fragment code as follows:
private DataBase dataBase; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_notes, container, false); MainActivity activity = (MainActivity)getActivity(); dataBase = new DataBase(activity); activity.changeToolbarTitle(getText(R.string.notes_tabItem).toString()); getNotes(activity); return view; } private void getNotes(MainActivity activity){ RecyclerView recyclerView = (RecyclerView) activity.findViewById(R.id.recycleView); recyclerView.setLayoutManager(new LinearLayoutManager(activity)); recyclerView.setAdapter(new NotesAdapter(dataBase.getNotes())); } then after adding a new entry to another Activity and returning to MainActivity , where notes are displayed as RecyclerView , there will be no new note until you restart the application. It is logical: after returning to MainActivity , where the fragment is located, onCreateView() not called, therefore, the call to the getNotes(activity) method, which receives the latest information from the database, also does not.
However, if we consider that after onCreate() always called onResume() , then why not put the call to getNotes(activity) in onResume() ?
private DataBase dataBase; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_notes, container, false); MainActivity activity = (MainActivity)getActivity(); dataBase = new DataBase(activity); activity.changeToolbarTitle(getText(R.string.notes_tabItem).toString()); return view; } @Override public void onResume() { super.onResume(); getNotes(activity); } We still need one instance of activity in onCreateView for other purposes; we create it. But we also need it in onResume() to call getNotes() , and getNotes itself, to use findViewByID and create a new LinearLayoutManager .
Question: can you initialize MainActivity only once or will you have to do it again in onResume ? (As for getNotes , I passed the activity through the parameter, but this is probably not the best solution).
