2

I have a main activity with a view pager and a simple date picker.

   public static class MyPagerAdapter extends SmartFragmentStatePagerAdapter {
    private static int NUM_ITEMS = 3;
    private List<String> titleList = Arrays.asList("Week", "Month", "Year");

    public MyPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    // Returns total number of pages
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return graph_week.newInstance(0, "Week");
            case 1:
                return graph_month.newInstance(1, "Month");
            case 2:
                return graph_year.newInstance(2, "Year");
            default:
                return null;
        }
    }

    // Returns the page titles
    @Override
    public CharSequence getPageTitle(int position) {
         return titleList.get(position);
    }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dateSetter = new DateSetter();
    setContentView(R.layout.activity_graph);

    ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
    adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
    vpPager.setAdapter(adapterViewPager);
    PagerTabStrip strip = (PagerTabStrip) findViewById(R.id.pager_header);
    strip.setDrawFullUnderline(false);

    vpPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        // This method will be invoked when a new page becomes selected.
        @Override
        public void onPageSelected(int position) {

        }
        // This method will be invoked when the current page is scrolled
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }
        // Called when the scroll state changes:
        // SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    fragment = (graph_month) adapterViewPager.getItem(1);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}

When I select a date I call setCalendar in on of my fragments to change a value. In createChart i create a simple chart, exception turns up in first line so I cut off the rest of the code.

   public static graph_month newInstance(int page, String title) {
    graph_month fragment = new graph_month();
    Bundle args = new Bundle();
    args.putInt(PAGE, page);
    args.putString(TITLE, title);
    fragment.setArguments(args);
    return fragment;
}
public graph_month() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        page = getArguments().getInt(PAGE);
        title = getArguments().getString(TITLE);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_graph_month, container, false);

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
  this.createChart();
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}


public void setCalendar(Calendar cal) {
    this.cal = cal;
    maxMonth = cal.getActualMaximum(cal.DAY_OF_MONTH);
    this.createChart();
}

public void createChart() {
    lineChartW= (LineChart) getView().findViewById(R.id.lineChartW);

But now I get a NullPointerException on a null object reference) and my view is now null. I have no idea why and I can't think of any other way to update my fragments from my activity.

Full error code:

Process: com.example.snyap.graphdemo, PID: 1491 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.view.View.toString()' on a null object reference at com.example.snyap.graphdemo.graphs.graph_month.createChart(graph_month.java:125) at com.example.snyap.graphdemo.graphs.graph_month.setCalendar(graph_month.java:120) at com.example.snyap.graphdemo.Graph.setDate(Graph.java:138) at com.example.snyap.graphdemo.Graph.onDateSet(Graph.java:144) at android.app.DatePickerDialog.onClick(DatePickerDialog.java:134) at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:165) at android.os.Handler.dispatchMessage(Handler.java:111) at android.os.Looper.loop(Looper.java:194) at android.app.ActivityThread.main(ActivityThread.java:5549) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)

snyappy
  • 33
  • 5
  • Please post the full stack trace. – cyroxis May 31 '16 at 15:19
  • put this.createChart(); in onCreateView and instead of getView().findViewById(R.id.lineChartW); do view.findViewById(R.id.lineChartW); – Austi01101110 May 31 '16 at 15:37
  • @Austi01101110 same error – snyappy May 31 '16 at 15:58
  • I couldn't tell you then, the error is happening in the createChart method somewhere below the code you have shown us. – Austi01101110 May 31 '16 at 16:01
  • Still thanks for your help though, I'm just referring to my lineChart object and creating the chart like I said ( lineChartW.setDescription(""); lineChartW.setNoDataText(""); lineChartW.setTouchEnabled(true); lineChartW.setPinchZoom(true);) – snyappy May 31 '16 at 16:03
  • Whats happening is the fragment you are referencing from the datepicker is not the fragment that is being displayed. In other words the fragment that the datepicker is referencing has not yet been initialized and as such neither has the view thus causing a null pointer. – Austi01101110 May 31 '16 at 17:51

1 Answers1

0

This is a proper way to do this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_graph_month, container, false);
    lineChartW= (LineChart) view.findViewById(R.id.lineChartW);
    return view;
}

There's no need to override onViewCreated for something like this. You can access that view the moment you've inflated it. You can read a bit more about this here.

Community
  • 1
  • 1
Vucko
  • 7,371
  • 2
  • 27
  • 45
  • It works without using the setCalendar method, but if i use it the nullPointerException now refers to my lineChart object – snyappy May 31 '16 at 16:00
  • remove the line `this.createChart();` cause you don't need it anymore. – Vucko May 31 '16 at 16:03
  • If I remove it from the setCalendar method how else could I refresh my fragment? – snyappy May 31 '16 at 16:06
  • I'm sorry, I don't quite get the question. The method `createChart` does not refresh ANYTHING. All it does is initialize the lineChart. If you've been using it somewhere else since it is a public method, you would have gotten a null pointer exception at times because `getView` might return null. – Vucko May 31 '16 at 16:08
  • Thanks for your help so far, i can change values inside my fragment like this, but whenever i refer to a widget inside setCalendar, it's referenced as null. Example: txt_Test.setText("Test"); in setCalendar txt_Test = ((TextView) view.findViewById(R.id.txt_Test)); in onCreateView – snyappy May 31 '16 at 16:32
  • I don't quite get what more do you need? We've fixed the original error, and thus this question should be closed. It's up to **you** to fix other errors yourself :) – Vucko Jun 01 '16 at 18:54