I have four fragments in a tab layout. In one of the fragments, I am displaying 10 notes in a listview. In addition to that, I am giving the user the option to add new notes using a dialog box. So, on adding a new note, the listview gets refreshed to show the new note as well but when I switch to another tab and then get back to my original tab, the new note is not displayed in the listview. How to solve this problem?
This is my java code:
public class NoteFragment extends Fragment {
ListView lv_notes;
Button btn_newNote;
ArrayList<NotesModel> notesModelArrayList;
private static NotesAdapter notesAdapter;
NotesModel newNote;
public NoteFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_note, container, false);
lv_notes = (ListView)rootView.findViewById(R.id.lv_notes);
btn_newNote = (Button)rootView.findViewById(R.id.btn_newNote);
notesModelArrayList = new ArrayList<>();
for (int i = 1; i <= 10; i++){
notesModelArrayList.add(new NotesModel("Note " + i,"24/05/2017"));
}
notesAdapter = new NotesAdapter(notesModelArrayList, getContext());
lv_notes.setAdapter(notesAdapter);
btn_newNote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater newNoteInflater = LayoutInflater.from(getContext());
View newNoteView = newNoteInflater.inflate(R.layout.noteprompt,null);
final AlertDialog.Builder noteDialogBuilder = new AlertDialog.Builder(getContext());
noteDialogBuilder.setView(newNoteView);
final EditText et_newNote = (EditText)newNoteView.findViewById(R.id.et_newNote);
noteDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
newNote = new NotesModel(et_newNote.getText().toString(),LogFragment.day_d + "/" + (LogFragment.month_d + 1) + "/" + LogFragment.year_d);
notesModelArrayList.add(newNote);
notesAdapter = new NotesAdapter(notesModelArrayList, getContext());
lv_notes.setAdapter(notesAdapter);
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog newNoteDialog = noteDialogBuilder.create();
newNoteDialog.show();
}
});
return rootView;
}
}