0

I have 2 different Fragments and in first Fragment, I am adding a new student entry to my custom Student ArrayList. I also have a ListView to show my student list in my second Fragment. However, when I go to my second Fragment, it doesn't update the latest ListView. So my question is that how can I update my ListView after I change my Fragment tab?

registerBtn simply adds a new entry to my studentsArrayList.

At first, I tried to use "Get" button to update my ListView but it didn't work. What I want to do is that refreshing my ListView whenever I pass to my StudentsFragment.

RegisterFragment.java:

package com.rawsly.android.schoolprogram;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Random;

public class RegisterFragment extends Fragment {
    private static final String TAG = "RegisterFragment";
    public ArrayList<Students> studentsArrayList = new ArrayList<>();
    private ArrayList<Long> idList = new ArrayList<>();
    private TextView studentID;
    private Button registerBtn, clearBtn, exitBtn;
    private EditText editName, editLastName, editGender, editFaculty, editDepartment, editAdvisor;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.register_fragment, container, false);

        studentID = (TextView) view.findViewById(R.id.studentID);
        studentID.setText(String.valueOf(generateID()));
        editName = (EditText) view.findViewById(R.id.editName);
        editLastName = (EditText) view.findViewById(R.id.editLastName);
        editGender = (EditText) view.findViewById(R.id.editGender);
        editFaculty = (EditText) view.findViewById(R.id.editFaculty);
        editDepartment = (EditText) view.findViewById(R.id.editDepartment);
        editAdvisor = (EditText) view.findViewById(R.id.editAdvisor);

        registerBtn = (Button) view.findViewById(R.id.registerBtn);
        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String id = studentID.getText().toString();
                String name = editName.getText().toString();
                String lastName = editLastName.getText().toString();
                String gender = editGender.getText().toString();
                String faculty = editFaculty.getText().toString();
                String department = editDepartment.getText().toString();
                String advisor = editAdvisor.getText().toString();

                studentsArrayList.add(new Students(id, name, lastName, gender, faculty, department, advisor));
                Toast.makeText(getContext(), "New entry added.", Toast.LENGTH_SHORT).show();
            }
        });

        clearBtn = (Button) view.findViewById(R.id.clearBtn);
        clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editName.setText(null);
                editLastName.setText(null);
                editGender.setText(null);
                editFaculty.setText(null);
                editDepartment.setText(null);
                editAdvisor.setText(null);
                studentID.setText(String.valueOf(generateID()));
            }
        });

        exitBtn = (Button) view.findViewById(R.id.exitBtn);
        exitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.exit(1);
            }
        });

        return view;
    }

    // Generates a random ID.
    public long generateID() {
        Random rnd = new Random();
        char [] digits = new char[11];
        digits[0] = (char) (rnd.nextInt(9) + '1');
        for(int i=1; i<digits.length; i++) {
            digits[i] = (char) (rnd.nextInt(10) + '0');
        }
        long result = Long.parseLong(new String(digits));
        if(idList.contains(result)) {
            return generateID();
        } else {
            return result;
        }
    }
}

StudentsFragment.java:

package com.rawsly.android.schoolprogram;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class StudentsFragment extends Fragment {
    private static final String TAG = "StudentsFragment";
    private EditText txtSearch;
    private ListView studentsListView;
    private Button getStudents, updateStudent, deleteStudent, exitBtn;
    public StudentsAdapter adapter;
    public ArrayList<Students> studentsArrayList = new ArrayList<>();;
    public int selectedItem = -1; // to update or delete the data

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.students_fragment, container, false);


        // Dummy Data
        studentsArrayList.add(new Students("1122334455", "Ahmet", "Özdemir", "Male", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
        studentsArrayList.add(new Students("1234567890", "Ezgi", "İmamoğlu", "Female", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
        studentsArrayList.add(new Students("0123456789", "Enise", "Usta", "Female", "Sosyal ve Beşeri Bilimler Fakültesi", "Uluslararası İlişkiler", "Murat Orhun"));
        studentsArrayList.add(new Students("1122445588", "Sinem", "Ünver", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Zehra Yılmaz"));
        studentsArrayList.add(new Students("2546882547", "Zehra", "Gürçay", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Şule Gündüz"));


        adapter = new StudentsAdapter(getContext(), studentsArrayList);

        studentsListView = (ListView) view.findViewById(R.id.studentsListView);
        studentsListView.setAdapter(adapter);

        studentsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                selectedItem = position;
                Toast.makeText(getContext(), "Selected entry: " + (selectedItem+1), Toast.LENGTH_LONG).show();
            }
        });

        // Opens a dialog window
        getStudents = (Button) view.findViewById(R.id.getStudents);
        getStudents.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adapter.notifyDataSetChanged();
                studentsListView.invalidate();
            }
        }); // end of the add action

        // To delete the selected School object
        deleteStudent = (Button) view.findViewById(R.id.deleteStudent);
        deleteStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(selectedItem == -1) {
                    Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
                } else {
                    studentsArrayList.remove(selectedItem);
                    selectedItem = -1;
                    adapter.notifyDataSetChanged();
                    Toast.makeText(getContext(), "Selected entry is deleted.", Toast.LENGTH_SHORT).show();
                }
            }
        }); // end of the delete action

        // To exit the program
        exitBtn = (Button) view.findViewById(R.id.exitBtn);
        exitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.exit(1);
            }
        }); // end of the exit action

        // To update the selected School object
        updateStudent = (Button) view.findViewById(R.id.updateStudent);
        updateStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(selectedItem == -1) {
                    Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
                } else {
                    final Dialog dialog = new Dialog(getContext());
                    dialog.setContentView(R.layout.update_student);
                    dialog.setTitle("Update An Entry");
                    // Dialog components - EditText, Button
                    String id = studentsArrayList.get(selectedItem).id;
                    String name = studentsArrayList.get(selectedItem).name;
                    String lastName = studentsArrayList.get(selectedItem).lastName;
                    String gender = studentsArrayList.get(selectedItem).gender;
                    String faculty = studentsArrayList.get(selectedItem).faculty;
                    String department = studentsArrayList.get(selectedItem).department;
                    String advisor = studentsArrayList.get(selectedItem).advisor;

                    final TextView studentID = (TextView) dialog.findViewById(R.id.studentID);
                    final EditText editName = (EditText) dialog.findViewById(R.id.editName);
                    final EditText editLastName = (EditText) dialog.findViewById(R.id.editLastName);
                    final EditText editGender = (EditText) dialog.findViewById(R.id.editGender);
                    final EditText editFaculty = (EditText) dialog.findViewById(R.id.editFaculty);
                    final EditText editDepartment = (EditText) dialog.findViewById(R.id.editDepartment);
                    final EditText editAdvisor = (EditText) dialog.findViewById(R.id.editAdvisor);

                    studentID.setText(id);
                    editName.setText(name);
                    editLastName.setText(lastName);
                    editGender.setText(gender);
                    editFaculty.setText(faculty);
                    editDepartment.setText(department);
                    editAdvisor.setText(advisor);

                    Button updateStudent = (Button) dialog.findViewById(R.id.updateStudent);
                    Button clearStudent = (Button) dialog.findViewById(R.id.clearStudent);
                    Button cancelStudent = (Button) dialog.findViewById(R.id.cancelStudent);

                    // Updates the selected School object
                    updateStudent.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String id = studentID.getText().toString();
                            String name = editName.getText().toString();
                            String lastName = editLastName.getText().toString();
                            String gender = editGender.getText().toString();
                            String faculty = editFaculty.getText().toString();
                            String department = editDepartment.getText().toString();
                            String advisor = editAdvisor.getText().toString();
                            studentsArrayList.get(selectedItem).setId(id);
                            studentsArrayList.get(selectedItem).setName(name);
                            studentsArrayList.get(selectedItem).setLastName(lastName);
                            studentsArrayList.get(selectedItem).setGender(gender);
                            studentsArrayList.get(selectedItem).setFaculty(faculty);
                            studentsArrayList.get(selectedItem).setDepartment(department);
                            studentsArrayList.get(selectedItem).setAdvisor(advisor);

                            adapter.notifyDataSetChanged();
                            Toast.makeText(getContext(), "An entry is updated.", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        }
                    });

                    // Clears all fields
                    clearStudent.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            editName.setText(null);
                            editLastName.setText(null);
                            editGender.setText(null);
                            editFaculty.setText(null);
                            editDepartment.setText(null);
                            editAdvisor.setText(null);
                        }
                    });

                    // Dismisses the dialog
                    cancelStudent.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                        }
                    });

                    dialog.show();
                    adapter.notifyDataSetChanged(); // notifying adapter about changes
                }
            }
        }); // end of the update action

        return view;
    }
}
rawsly
  • 372
  • 1
  • 5
  • 20
  • You could define a interface.. Please refer this https://developer.android.com/training/basics/fragments/communicating.html – Sivakumar S Dec 23 '17 at 14:16

1 Answers1

0

"Troubleshooting

If calling notifyDataSetChanged() doesn't work all the layout methods won't help either. Believe me the ListView was properly updated. If you fail to find the difference you need to check where the data in your adapter comes from.

If this is just a collection you're keeping in memory check that you actually deleted from or added the item(s) to the collection before calling the notifyDataSetChanged().

If you're working with a database or service backend you'll have to call the method to retrieve the information again (or manipulate the in memory data) before calling the notifyDataSetChanged().

The thing is this notifyDataSetChanged only works if the dataset has changed. So that is the place to look if you don't find changes coming through. Debug if needed."

duplicate: How to refresh Android listview?

no_fate
  • 1,625
  • 14
  • 22