在 Expandable ListView 中的 onCreate() 之前,系统服务对 Activity 不可用

System services not available to Activities before onCreate() in Expandable ListView

在我的应用程序中,我有 SearchView,单击它会在 Fragment 中打开一个 ExpandableListView,显示搜索查询的一些结果。现在我遇到的问题是每次我单击 searchIcon 应用程序都会崩溃。

MainActivity.Java:

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
{

    private ExpListAdapter listAdapter;
    private ExpandableListView expList;
    private ArrayList<parentClass> parentList = new ArrayList<>();

    private boolean b = true;
    sql sqlo = new sql();



   @Override
   protected void onCreate (Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);

       Intent sIntent = getIntent();
       if (Intent.ACTION_SEARCH.equals(sIntent.getAction())) {
           String query = sIntent.getStringExtra(SearchManager.QUERY);


       }}


    public void searchClick(MenuItem item){
        Fragment frag = new Results();

        FragmentTransaction ft  = getSupportFragmentManager().beginTransaction();

        ft.replace(R.id.FragFaecher,frag).commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);


        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);
        searchView.setOnQueryTextListener(this);

       searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
           @Override
           public void onViewAttachedToWindow(View v) {

           }

           @Override
           public void onViewDetachedFromWindow(View v) {
            Fragment frag = new FaecherFrag();
               FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
               ft.replace(R.id.FragFaecher,frag).commit();
           }
       });



        return true;
    }


        public void displayList(ExpandableListView expList){
        if(b){populateList();}

        listAdapter = new ExpListAdapter(MainActivity.this,parentList);
        expList.setAdapter(listAdapter);
        b = false;
    }

    private void populateList(){
        String[] cThema = sqlo.getAlleThemen(this);
        String[] cFormel = sqlo.getAlleFormeln(this);
        int cThemaLength = cThema.length;
        int cFormelLength = cFormel.length;
        childClass Child;

        ArrayList<childClass> childList = new ArrayList<>();

        for (int i=0; i<cThemaLength;i++){Child = new childClass(cThema[i]);childList.add(Child);}
        parentClass Parent = new parentClass("Themen",childList);
        parentList.add(Parent);

        childList = new ArrayList<>();

        for (int i=0;i<cFormelLength;i++){Child = new childClass(cFormel[i]);childList.add(Child);}
        Parent = new parentClass("Formeln",childList);

        parentList.add(Parent);

    }

    @Override
    public boolean onQueryTextSubmit(String query) {

        return false;
    }

    @Override
    public boolean onQueryTextChange(String query) {

        return false;
    }
}

ExpListAdapter.Java:

public class ExpListAdapter extends BaseExpandableListAdapter {

    private Context context;
    private ArrayList<parentClass> parentList;
    private ArrayList<parentClass> originalList;

    public ExpListAdapter(Context context, ArrayList<parentClass> parentList){
        this.context = context;
        this.parentList = new ArrayList<>();
        this.parentList.addAll(parentList);
        this.originalList = new ArrayList<>();
        this.originalList.addAll(parentList);
    }

    @Override
    public int getGroupCount() {
        return parentList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        ArrayList<childClass> childList = parentList.get(groupPosition).getChildList();
        return childList.size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return parentList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        ArrayList<childClass> childList = parentList.get(groupPosition).getChildList();
        return childList.get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {

        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }



    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        childClass child = (childClass) getChild(groupPosition,childPosition);
        if (convertView == null){
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.child_row,null);
        }
        TextView name = (TextView) convertView.findViewById(R.id.name);
        name.setText(child.getName().trim());

        return convertView;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup Parent) {
        parentClass parent = (parentClass) getGroup(groupPosition);
        if(convertView == null){
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.parent_row,null);

        }
        TextView heading = (TextView) convertView.findViewById(R.id.heading);
        heading.setText(parent.getName().trim());
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    public void filterData(String query){

    }
}

片段:

public class Results extends Fragment {

    ExpandableListView expList;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_results, container, false);

        return rootView;

    }

    public void onStart(){
        super.onStart();
        expList = (ExpandableListView) getView().findViewById(R.id.expList);
        MainActivity ma = new MainActivity();
        ma.displayList(expList);
    }
}

我在 getGroupView() 方法上收到错误 "java.lang.IllegalStateException: System services not available to Activities before onCreate()"。但是如果我没弄错的话,我已经调用了 MainActivity 的 onCreate。那么为什么会出现这个错误呢?

FATAL EXCEPTION: main Process: formelhelfer5_10.formelhelfer5_10, PID: 2301 java.lang.IllegalStateException: System services not available to Activities before onCreate() at android.app.Activity.getSystemService(Activity.java:5581) at formelhelfer5_10.formelhelfer5_10.ExpListAdapter.getGroupView(ExpListAdapter.java:86) at android.widget.ExpandableListConnector.getView(ExpandableListConnector.java:446) at android.widget.AbsListView.obtainView(AbsListView.java:2360) at android.widget.ListView.measureHeightOfChildren(ListView.java:1326) at android.widget.ListView.onMeasure(ListView.java:1233) at android.view.View.measure(View.java:19731) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464) at android.widget.LinearLayout.measureVertical(LinearLayout.java:758) at android.widget.LinearLayout.onMeasure(LinearLayout.java:640) at android.view.View.measure(View.java:19731) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at android.view.View.measure(View.java:19731) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) at android.view.View.measure(View.java:19731) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668) at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90) at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1192) at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:733) at android.view.View.measure(View.java:19731) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135) at android.view.View.measure(View.java:19731) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464) at android.widget.LinearLayout.measureVertical(LinearLayout.java:758) at android.widget.LinearLayout.onMeasure(LinearLayout.java:640) at android.view.View.measure(View.java:19731) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at android.view.View.measure(View.java:19731) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464) at android.widget.LinearLayout.measureVertical(LinearLayout.java:758) at android.widget.LinearLayout.onMeasure(LinearLayout.java:640) at android.view.View.measure(View.java:19731) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at com.android.internal.policy.DecorView.onMeasure(DecorView.java:687) at android.view.View.measure(View.java:19731) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871) at android.view.Choreographer.doCallbacks(Choreographer.java:683) at android.view.Choreographer.doFrame(Choreographer.java:619) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857) at android.os.Handler.handleCallback(Handler.java:751) 09-06 13:13:20.688 2301-2301/formelhelfer5_10.formelhelfer5_10 E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

使用这个:

View.inflate(ctx, R.layout.parent_row, null);

里面:

 @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup Parent) {
        parentClass parent = (parentClass) getGroup(groupPosition);
        if(convertView == null){
            convertView = View.inflate(ctx, R.layout.parent_row, null); 

        }
        TextView heading = (TextView) convertView.findViewById(R.id.heading);
        heading.setText(parent.getName().trim());
        return convertView;
    }
MainActivity ma = new MainActivity();
ma.displayList(expList);

切勿使用 new 实例化活动。此类实例不会针对您使用 Activity 的任何内容进行初始化,例如用作可以访问系统服务的 Context

在片段中,您可以使用 getActivity() 访问附加主机 activity。使用它而不是实例化一个新的 activity.

1) 如 laalto 所示 - 切勿使用 new 实例化活动。

改变

 public void onStart(){
    super.onStart();
    expList = (ExpandableListView) getView().findViewById(R.id.expList);
    MainActivity ma = new MainActivity();
    ma.displayList(expList);
}

 public void onStart(){
    super.onStart();
    expList = (ExpandableListView) getView().findViewById(R.id.expList);
    MainActivity ma = (MainActivity) getActivity();
    ma.displayList(expList);
}

2) 建立如此深的依赖关系不是个好主意