无法在Fragment中检索上下文

时间:2018-02-09 01:43:28

标签: java android android-fragments

我试图找到具有多种资源的解决方案:

  1. Retrieve Context from a fragment
  2. Using context in a fragment
  3. 但我仍然遇到以下错误:

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
    

    任何帮助将不胜感激。谢谢!

    我目前的代码:

    AnalysisActivity.java:

    package com.app.component.fragment;
    
    import android.os.Bundle;
    import android.support.design.widget.TabLayout;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    
    import com.material.components.R;
    import com.material.components.fragment.FragmentTabsEvents;
    import com.material.components.fragment.FragmentTabsPerformance;
    import com.material.components.fragment.FragmentTabsRecommendation;
    import com.material.components.utils.Tools;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class AnalysisActivity extends AppCompatActivity {
    
    
        private ViewPager view_pager;
        private TabLayout tab_layout;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_analysis);
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            Tools.setSystemBarColor(this,R.color.black);
    
            view_pager = findViewById(R.id.view_pager);
            setupViewPager(view_pager);
    
            tab_layout = findViewById(R.id.tab_layout);
            tab_layout.setupWithViewPager(view_pager);
        }
    
        private void setupViewPager(ViewPager viewPager) {
            SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
            adapter.addFragment(FragmentTabsPerformance.newInstance(), "PERFORMANCE");
            adapter.addFragment(FragmentTabsRecommendation.newInstance(), "RECOMMENDATION");
            adapter.addFragment(FragmentTabsEvents.newInstance(), "EVENTS RELATED TO YOU");
            viewPager.setAdapter(adapter);
        }
    
        private class SectionsPagerAdapter extends FragmentPagerAdapter {
    
            private final List<Fragment> mFragmentList = new ArrayList<>();
            private final List<String> mFragmentTitleList = new ArrayList<>();
    
            public SectionsPagerAdapter(FragmentManager manager) {
                super(manager);
            }
    
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }
    
            @Override
            public int getCount() {
                return mFragmentList.size();
            }
    
            public void addFragment(Fragment fragment, String title) {
                mFragmentList.add(fragment);
                mFragmentTitleList.add(title);
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                return mFragmentTitleList.get(position);
            }
        }
    
        @Override
        public boolean onSupportNavigateUp() {
            onBackPressed();
            return  true;
        }
    }
    

    FragmentTabsPerformance.java:

    package com.app.component.fragment;
    
    import android.content.Context;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    
    import com.material.components.R;
    import com.material.components.utils.Tools;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import lecho.lib.hellocharts.model.Line;
    import lecho.lib.hellocharts.model.LineChartData;
    import lecho.lib.hellocharts.model.PointValue;
    import lecho.lib.hellocharts.view.LineChartView;
    
    public class FragmentTabsPerformance extends Fragment {
    
        private Context context;
        public FragmentTabsPerformance() {
            this.context = getActivity().getApplicationContext();
            List<PointValue> values = new ArrayList<>();
            values.add(new PointValue(0, 2));
            values.add(new PointValue(1, 4));
            values.add(new PointValue(2, 3));
            values.add(new PointValue(3, 4));
    
            //In most cased you can call data model methods in builder-pattern-like manner.
            Line line = new Line(values).setColor(Color.BLUE).setCubic(true);
            List<Line> lines = new ArrayList<>();
            lines.add(line);
    
            LineChartData data = new LineChartData();
            data.setLines(lines);
    
            LineChartView chart = new LineChartView(this.getContext());
            chart.setLineChartData(data);
        }
    
        public static FragmentTabsPerformance newInstance() {
            FragmentTabsPerformance fragment = new FragmentTabsPerformance();
            return fragment;
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View root = inflater.inflate(R.layout.fragment_tabs_performance, container, false);
    
            Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_1), R.drawable.image_8);
            Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_2), R.drawable.image_9);
            Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_3), R.drawable.image_15);
            Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_4), R.drawable.image_14);
            Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_5), R.drawable.image_12);
            Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_6), R.drawable.image_2);
            Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_7), R.drawable.image_5);
    
            return root;
        }
    }
    

2 个答案:

答案 0 :(得分:0)

当片段未附加到活动时,您在构造方法中调用了getActivity(),因此发生了此异常。您可以参考有关活动片段的生命周期方法的API guides。在您的情况下,您可以使用getContext()而不是getActivity()方法来获取片段的上下文。

答案 1 :(得分:0)

getActivity()仅在将Fragment附加到活动后才可用。因此,Fragment构造函数中的getActivity()将返回null。查看fragment life cycle了解更多详情