Как обновить список фрагментов из активности в Android - PullRequest
0 голосов
/ 15 января 2019

Я пытаюсь обновить свой список, когда я добавляю данные из другого действия, которое я использовал onActivityResult(), но фрагмент не может обновить список, как обновить или обновить данные фрагмента из другого действия?.

Я также пытался использовать interface для обновления списка, он не может обновить список, есть ли другое решение? пожалуйста, дайте мне знать.

Это мой фрагмент

public class AllComplaints extends Fragment {

private FloatingActionButton fab_add_complaints;
private CoordinatorLayout coordinatorLayoutHome;
private ProgressBar pbAllcomplaintsFragment, pb_rv_all_complaint;
private SearchView searchViewAllcomplaints;
private RecyclerView recyclerViewAllcomplaints;
private AllComplaintAdapter allComplaintAdapter;
private CoordinatorLayout coordinatorLayout_home;
private String str_society_id = "", resident_id = "", wing_id = "", complaint_category_id = "", flat_id = "", complaint_type = "";
private SharedPreferencesDatabase sharedPreferencesDatabase;


public AllComplaints() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_all_complaints, container, false);
    initView(rootView);


    fab_add_complaints = rootView.findViewById(R.id.fab_add_complaints);
    pb_rv_all_complaint = rootView.findViewById(R.id.pb_rv_all_complaint);
    coordinatorLayout_home = rootView.findViewById(R.id.coordinatorLayout_home);
    fab_add_complaints.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), AddComplaintActivity.class);
            startActivity(intent);
        }
    });
    sharedPreferencesDatabase = new SharedPreferencesDatabase(getActivity());
    sharedPreferencesDatabase.createDatabase();
    if (sharedPreferencesDatabase != null) {
        str_society_id = sharedPreferencesDatabase.getData(Config.KEY_SOCIETY_ID);
        resident_id = sharedPreferencesDatabase.getData(Config.KEY_RESIDENT_ID);
        str_society_id = sharedPreferencesDatabase.getData(Config.KEY_SOCIETY_ID);
        wing_id = sharedPreferencesDatabase.getData(Config.KEY_WING_ID);
        flat_id = sharedPreferencesDatabase.getData(Config.KEY_FLAT_ID);


    }

    allComplaintAdapter = new AllComplaintAdapter(getActivity(), getAllComplaint(str_society_id, resident_id));
    Functions.setDatatoRecyclerView(recyclerViewAllcomplaints, allComplaintAdapter, getActivity());

    return rootView;
}


private void initView(View v) {
    coordinatorLayoutHome = (CoordinatorLayout) v.findViewById(R.id.coordinatorLayout_home);
    pbAllcomplaintsFragment = (ProgressBar) v.findViewById(R.id.pb_allcomplaints_fragment);
    searchViewAllcomplaints = (SearchView) v.findViewById(R.id.searchView_allcomplaints);
    recyclerViewAllcomplaints = (RecyclerView) v.findViewById(R.id.recycler_view_allcomplaints);
}


public ArrayList<AllComplaintItem> getAllComplaint(String society_id, String resident_id) {
    Functions.pbVisiblity(false, pb_rv_all_complaint);
    final ArrayList<AllComplaintItem> allComplaintItems = new ArrayList();
    AndroidNetworking.post(Config.get_all_complaint)
            .addBodyParameter("society_id", society_id)
            .addBodyParameter("resident_id", resident_id)
            .setTag("getData")
            .setPriority(Priority.MEDIUM)
            .build().getAsJSONObject(new JSONObjectRequestListener() {
        @Override
        public void onResponse(JSONObject response) {
            try {

                if (response.has("status") && response.getString("status").equals("1")) {

                    JSONArray complaints = response.getJSONArray("complaints");
                    for (int i = 0; i < complaints.length(); i++) {
                        JSONObject allcomplaints = complaints.getJSONObject(i);
                        String complaints_category = allcomplaints.getString("complaints_category");
                        String complaint_id = allcomplaints.getString("complaint_id");
                        String complaint_type = allcomplaints.getString("complaint_type");
                        String category_id = allcomplaints.getString("category_id");
                        String title = allcomplaints.getString("title");
                        String description = allcomplaints.getString("description");
                        String default_date = allcomplaints.getString("default_date");
                        String flat_name = allcomplaints.getString("flat_name");
                        String wing_name = allcomplaints.getString("wing_name");
                        String status = allcomplaints.getString("status");
                        String assign_staff_name = allcomplaints.getString("assign_staff_name");
                        //String last_name = allcomplaints.getString("last_name");
                        String str_name = sharedPreferencesDatabase.getData(Config.KEY_LOGIIN_NAME);
                        if (status.equals("0")) {
                            status = "Open";
                        }
                        allComplaintItems.add(new AllComplaintItem("", str_name, default_date, title, assign_staff_name, status, flat_name + " " + wing_name, "", "", "", "", complaints_category, R.mipmap.neighbours, R.mipmap.neighbours));
                    }

                    if (allComplaintAdapter != null) {
                        allComplaintAdapter.notifyDataSetChanged();
                    }
                } else {
                    String msg = response.get("msg").toString();
                    Snackbar.make(coordinatorLayout_home, msg, Snackbar.LENGTH_SHORT).show();
                    Functions.pbVisiblity(true, pb_rv_all_complaint);
                }

                Functions.pbVisiblity(true, pb_rv_all_complaint);
            } catch (Exception e) {
                Snackbar.make(coordinatorLayout_home, e.getMessage(), Snackbar.LENGTH_SHORT).show();


            }
        }

        @Override
        public void onError(ANError error) {
            if (TextUtils.equals(error.getErrorDetail(), "connectionError")) {
                Snackbar.make(coordinatorLayout_home, "No Internet Connection", Snackbar.LENGTH_SHORT).show();
            } else {
                Snackbar.make(coordinatorLayout_home, error.getErrorDetail(), Snackbar.LENGTH_SHORT).show();
            }
            Functions.pbVisiblity(true, pb_rv_all_complaint);

        }
    });

    return allComplaintItems;
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Fragment uploadType = getChildFragmentManager().findFragmentById(R.id.container_body);
    if (uploadType != null) {
        uploadType.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            Toast.makeText(getActivity(), "Done", Toast.LENGTH_SHORT).show();

        }
    }
    super.onActivityResult(requestCode, resultCode, data);
 }
}

В своей деятельности я назвал это так

Intent intent = new Intent();
startActivityForResult(intent, 1);

1 Ответ

0 голосов
/ 18 января 2019

Вы должны вызвать startActivityForResult() из фрагмента вместо действия, чтобы получить onActivityResult() обратный вызов в вашем фрагменте.

Если вы позвоните по номеру startActivityForResult(), будет вызвано onActivityResult() действия.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...