androidfragmentoncreatefragment-oncreateview

Perform network operations before onCreateView


In my application fragment i am setting values for arrayList by loading data for server in onCreate() method and then i want to display that data into listView with the help of adapter but when i run my program it executes onCreateView() first before network code that is in onCreate() method

onCreate()

ArrayList<ContactItem> contactsList = new ArrayList<ContactItem>();

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

    final QBUser qbUser = new QBUser("username", "password");
    QBAuth.createSession(qbUser).performAsync(new QBEntityCallback<QBSession>() {
        @Override
        public void onSuccess(QBSession qbSession, Bundle bundle) {
            Toast.makeText(getActivity(), "created", Toast.LENGTH_SHORT).show();

            for (int i = 0; i < contactName.size(); i++) {
                QBUsers.getUserByLogin(contactNumber.get(i).replaceAll(" ", "")).performAsync(new QBEntityCallback<QBUser>() {
                    @Override
                    public void onSuccess(QBUser qbUser, Bundle bundle) {
                        if (qbUser != null) {
                            final ContactItem contactItem = new ContactItem(qbUser.getFullName(), qbUser.getLogin(), R.drawable.profile);
                            contactsList.add(contactItem);

                        }

                    }

                    @Override
                    public void onError(QBResponseException e) {

                    }
                });
            }




        }

        @Override
        public void onError(QBResponseException e) {
            Toast.makeText(getActivity(), "failed " + e.toString(), Toast.LENGTH_LONG).show();
        }
    });

}

onCreateView()

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

    ListView listView = (ListView) rootView.findViewById(R.id.contacts_listview);

    contactItemAdapter = new ContactItemAdapter(getActivity(), contactsList);
    listView.setAdapter(contactItemAdapter);

    return rootView;
}

Solution

  • In your code, onCreate() is called then onCreateView() is called. But your API request runs in background, due to which before the response from server comes your onCreateView() is already called and hence, ther eis no data in contactsList.

    You can shift the below lines from onCreateView()

    contactItemAdapter = new ContactItemAdapter(getActivity(), contactsList);
    listView.setAdapter(contactItemAdapter);
    

    To onSuccess(), after you are putting data from server into contactsList, i.e. at the end of the outer onSuccess().