0

I was under the impression that onEvent can be triggered as soon as the fragment starts if it is placed in the onStart() and onResume method . Please have a look at my fragment below . That method prepareListData is ment to sort the list before I display it but the onEvent(contains list data from another fragment) for some reason is being called after prepareListData() which means there is not actual list and hence I get a null pointer . How can I make onEvent to be called before prepareListData

 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
//import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.androidquery.AQuery;
import com.xera.deviceinsight.Errors;
import com.xera.deviceinsight.Globals;
import com.xera.deviceinsight.R;
import com.xera.deviceinsight.api.OrganisationDeviceSensorsResult;
import com.xera.deviceinsight.api.Results;
import com.xera.deviceinsight.net.Claritech;
import com.xera.deviceinsight.net.ClaritechClient;
import com.xera.deviceinsight.receivers.IEvent;
import com.xera.deviceinsight.sensors.IotTabFragment;
import com.xera.deviceinsight.sensors.ItemClickedEvent;
import com.xera.deviceinsight.structs.DistanceUpdatedEvent;
import com.xera.deviceinsight.structs.HelloWorldEvent;
import com.xera.deviceinsight.structs.OrganisationDeviceSensorsEvent;

    public class CostCentreListFragment  extends Fragment {

       public static final String TAG = Globals.TAG + ".ALF";
       ViewPager mViewPager;
       ExpandableListAdapter listAdapter;
       ExpandableListView expListView;
       List<String> listDataHeader;
       HashMap<String, List<String>> listDataChild;
       public static List<OrganisationDeviceSensorsResult> Items;
       public String currentReportingGroup;
       private ViewPager viewPager;
       private IEvent onDeviceSensorsObtained;
       private IEvent event;
       public List sensorList;

       @Nullable
       @Override
       public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
          //EventBus eventBus = EventBus.getDefault();
          //if (!eventBus.isRegistered(this)) eventBus.register(this);
          View view = inflater.inflate(R.layout.layout_expandable, container, false);
          AQuery aq = new AQuery(view);

          expListView = (ExpandableListView) view.findViewById(R.id.lvExp);
          //prepareListData();
         prepareSensorListData();
          listAdapter = new ExpandableListAdapter(this.getActivity(), listDataHeader, listDataChild);
          // setting list adapter

          listAdapter = new ExpandableListAdapter(this.getActivity(), listDataHeader, listDataChild);
          expListView.setAdapter(listAdapter);
          expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
             @Override
             public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                //Nothing here ever fires
                System.err.println("child clicked");
                Toast.makeText(getActivity(), "child clicked", Toast.LENGTH_SHORT).show();

                // Navigate to second tab
                EventBus.getDefault().post(new ItemClickedEvent(IotTabFragment.TAB_SENSOR));
                return true;
             }
          });
          return view;
       }

   @Override
   public void onStart() {
      super.onStart();
      EventBus.getDefault().register(this);

   }

   @Override
   public void onPause() {
      EventBus.getDefault().unregister(this);
      super.onPause();
   }
   private void getDeviceSensorCostCentres() {
      //int costCentreID =0
      final Context context = this.getActivity();
      ClaritechClient client = new ClaritechClient(context);

      Claritech.api(context).getDeviceSensorCostCentres(client.getCostCentreID()).enqueue(new Callback<Results<OrganisationDeviceSensorsResult>>() {
         @Override
         public void onResponse(Call<Results<OrganisationDeviceSensorsResult>> call, Response<Results<OrganisationDeviceSensorsResult>> response) {

            if (response.isSuccessful()) {
               // Reload data source
               Items.clear();
               Items.addAll(response.body());
               //ItemsAdapter.notifyDataSetChanged();
               Log.i(TAG, "onResponse: ");
            }
         }
         @Override
         public void onFailure(Call<Results<OrganisationDeviceSensorsResult>> call, Throwable t) {
            Errors.handleException(t);


         }
     });
    }

  public void onEvent(OrganisationDeviceSensorsEvent event){
       String Tag  ="";
       sensorList = event.deviceSensors;
       Log.i("EventBus",Tag);
       //prepareSensorListData();
        //Toast.makeText(getActivity(), event.deviceSensors, Toast.LENGTH_SHORT).show();
     };



     private void prepareSensorListData() {
        final Context context = this.getActivity();
        ClaritechClient client = new ClaritechClient(context);

        Claritech.api(context).getDeviceSensorCostCentres(client.getCostCentreID()).enqueue(new Callback<Results<OrganisationDeviceSensorsResult>>() {
           @Override
           public void onResponse(Call<Results<OrganisationDeviceSensorsResult>> call, Response<Results<OrganisationDeviceSensorsResult>> response) {

              if (response.isSuccessful()) {
                 // Reload data source
                 Items.clear();
                 Items.addAll(response.body());
                 //ItemsAdapter.notifyDataSetChanged();
                 Log.i(TAG, "onResponse: ");
                 String Tag  ="";
                 listDataHeader = new ArrayList<String>();
                 listDataChild = new HashMap<String, List<String>>();
                 Log.i("EventBus",Tag);
                 //List sensorList = event.deviceSensors;
                 int check = sensorList.size();
                 int check2 = Items.size();
                 List<String> top250 = new ArrayList<String>();
                 for (int i = 1; i < Items.size(); i++) {
                    //if(i!=1 && sensorList.get(i).= currentReportingGroup)
                    // do a check here to see if the reporting group has changed or not
                    {
                       listDataHeader.add(Items.get(i).ReportingGroup);
                       top250.add(Items.get(i).SensorLocation);
                       // top250.add(String.valueOf(Items.get(i).SensorID));
                    }
                 }
                 listDataChild.put(listDataHeader.get(0), top250);
              }
           }
           @Override
           public void onFailure(Call<Results<OrganisationDeviceSensorsResult>> call, Throwable t) {
              Errors.handleException(t);

           }
        });


      };

}
Surya Prakash Kushawah
  • 3,185
  • 1
  • 22
  • 42
Zidane
  • 1,696
  • 3
  • 21
  • 35

1 Answers1

1

onEvent will be called as soon as you do somewhere in your code the following

EventBus.getDefault().post(organisationDeviceSensorsEvent);

IFF EventBus is registered, so, if your fragment is up and running. No, it will not be called when you resume the fragment. When you resume the fragment you register the EventBus listener to wait for events. when event are being posted "onEvent(){}" is being called.

You can do something like the thing you want if you post a sticky event (read on EventBut documentation how to post it and how to get it). In that case you can post the event at some random point in time, and your fragment will receive it at the same time if its running or when you register the listener. But again,

prepareSensorListData();

is being called on your onCreateView, so it will be called before the EventBus is even registered.

Nikiforos
  • 154
  • 11
  • thanks that makes sense it explains a lot . Do you have any suggestions on how I can do this better – Zidane Dec 06 '16 at 10:53
  • I edited my answer. If you need a better suggestion you need to write when is the event getting posted because i cant really understand what you want :) Also, feel free to up vote or accept my answer :P – Nikiforos Dec 06 '16 at 10:58
  • prepareSensorListData() is getting data from the web, correct? Then you want to get some other data from the onEvent and then sort them and show the list, correct? – Nikiforos Dec 06 '16 at 11:05