何时在片段中调用onEvent,是否有办法确定何时可以调用它?

时间:2016-12-06 10:36:10

标签: android android-fragments greenrobot-eventbus

我的印象是,如果片段放在onStart()和onResume方法中,一旦片段启动就可以触发onEvent。请看下面我的片段。这个方法prepareListData是在我显示它之前对列表进行排序但是onEvent(包含来自另一个片段的列表数据)由于某种原因在prepareListData()之后被调用,这意味着没有实际列表,因此我得到一个空指针。如何在prepareListData

之前调用onEvent
 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);

           }
        });


      };

}

1 个答案:

答案 0 :(得分:1)

只要您在代码中的某处执行以下操作,就会调用

onEvent

  

EventBus.getDefault()后(organisationDeviceSensorsEvent);

IFF EventBus已注册,因此,如果您的片段已启动并正在运行。 不,恢复片段时不会调用它。当您恢复片段时,您注册EventBus侦听器以等待事件。何时发布事件&#34; onEvent(){}&#34;正在被召唤。

如果发布粘性事件,您可以执行类似的操作(在EventBut文档中阅读如何发布以及如何获取它)。在这种情况下,您可以在某个随机时间点发布事件,如果您的片段正在运行或注册了侦听器,您的片段将同时接收它。但是,再次,

  

prepareSensorListData();

正在onCreateView上调用

,因此在EventBus注册之前将调用它。