-3

I am trying to make some graphs in my android application but I am getting NullPointer Exception at findviewbyid(). Since I am plotting graphs at different tab so I have used a separate fragment for graphs.

EDIT: My question is different. I know where and how I am getting null pointer exception but as I am new to Android,I don't know how to remove it in this particular situation.

Code for the graph fragment:

public class Graphs_tab extends android.support.v4.app.Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.graphs_tab,container,false);
        GraphView graph = (GraphView) getView().findViewById(R.id.graph);
        LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[]{
                new DataPoint(0, 1),
                new DataPoint(1, 5),
                new DataPoint(2, 3),
                new DataPoint(3, 2),
                new DataPoint(4, 6)
        });
        graph.addSeries(series);
    return  rootView;
}}

Xml code :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <com.jjoe64.graphview.GraphView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/graph" />
</RelativeLayout>
mystic
  • 17
  • 7

1 Answers1

4

Change this

GraphView graph = (GraphView) getView().findViewById(R.id.graph);

to

GraphView graph = (GraphView) rootView.findViewById(R.id.graph);

or in onActivityCreated() initialize view using getView() or use view in onViewCreated() to initialize views.

And also check fragment lifecycle https://developer.android.com/guide/components/fragments.html#Creating to understand why getView() returns null in onCreateView()

Raghunandan
  • 129,147
  • 24
  • 216
  • 249