-1

I tried to find the solution with several resources:

  1. Retrieve Context from a fragment
  2. Using context in a fragment

But I still got the following error:

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

Any help will be appreciated. Thanks!


My current codes:

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;
    }
}
Nere
  • 4,097
  • 5
  • 31
  • 71
  • 1
    You don't have access to a `Context` in the constructor, as the `Fragment` is not yet attached to one. Since you're using that `Context` to instantiate a `View`, why not move that to `onCreateView()`? Also, there's really no need to keep a `Context` field. Just call `getActivity()` wherever you need one. – Mike M. Feb 09 '18 at 02:00
  • Oh I see it.. thanks for the response! – Nere Feb 09 '18 at 02:05
  • 1
    Yep, that'll work. I would mention, though, that, in the code you've posted, you're not adding that `LineChartView` to anything on-screen, so you're not going to see it. I'm not sure if you just haven't gotten to that part yet. – Mike M. Feb 09 '18 at 02:06

2 Answers2

0

This exception occurred since you called the getActivity() in the construction method when the fragment is not attached to an activity. You may refer to the API guides about the lifecycle methods about fragment with activity. In your case, you may use getContext() instead of getActivity() method to get the context of fragment.

Shawn Wong
  • 554
  • 6
  • 15
0

getActivity() only available after Fragment is attached to activity. So, getActivity() in Fragment constructor will return null. Check fragment life cycle for more detail

Luc Le
  • 196
  • 9