0

I am getting this NullPointerException from the code that I got online for plotting a line graph using JSON.problem is I am an absolute beginner to android and I couldn't fix it please help. the code is as follow

JSON file

{
  "id": 1,
  "coffee": [
    {
      "Date": "18:25:43",
      "Estimate": 25.4
    },
    {
      "Date": "18:35:43",
      "Estimate": 27.3
    },
    {
      "Date": "18:45:21",
      "Estimate": 26.3
    },
    {
      "Date": "18:55:43",
      "Estimate": 25.2
    }
  ]
}

AppController.java file

    public class AppController extends Application {
    public static final String TAG = AppController.class.getSimpleName();
    private RequestQueue mRequestQueue;
    private static AppController mInstance;
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }
}

MainActivity.java file

public class MainActivity extends AppCompatActivity {
    Button button;
    ArrayList<Entry> x;
    ArrayList<String> y;
    private LineChart mChart;
    public String TAG = "AppController";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.click);


        x = new ArrayList<Entry>();
        y = new ArrayList<String>();
        mChart = (LineChart)findViewById(R.id.chart1);
        mChart.setDrawGridBackground(false);
        mChart.setDescription("");
        mChart.setTouchEnabled(true);
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        mChart.setPinchZoom(true);
        //mChart.setMarkerView(mv);
        XAxis xl = mChart.getXAxis();
        xl.setAvoidFirstLastClipping(true);
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setInverted(true);
        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);
        Legend l = mChart.getLegend();
        l.setForm(Legend.LegendForm.LINE);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawChart();
            }
        });
    }
    private void drawChart() {

        String tag_string_req = "req_chart";


        StringRequest strReq = new StringRequest(Request.Method.POST, "https://api.myjson.com/bins/10w5bk",
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {

                        Log.d(TAG, "Response: " + response);

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String id = jsonObject.getString("id");
                            JSONArray jsonArray = jsonObject.getJSONArray("coffee");
                            for (int i = 0; i < jsonArray.length(); i++) {


                               /* int value = jsonObject.getInt("value");
                                String date = jsonObject.getString("time");*/
                                int Estimate = jsonObject.getInt("Estimate");
                                String Date = jsonObject.getString("Date");
                                x.add(new Entry(Estimate, i));
                                y.add(Date);

                            }
                            LineDataSet set1 = new LineDataSet(x, "NAV Data Value");
                            set1.setLineWidth(1.5f);
                            set1.setCircleRadius(4f);
                            LineData data = new LineData(y, set1);
                            mChart.setData(data);
                            mChart.invalidate();

                        }

                        catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
            }
        });
        strReq.setRetryPolicy(new RetryPolicy() {

            @Override
            public void retry(VolleyError arg0) throws VolleyError {
            }

            @Override
            public int getCurrentTimeout() {
                return 0;
            }

            @Override
            public int getCurrentRetryCount() {
                return 0;
            }
        });
        strReq.setShouldCache(false);
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

}

activity_mmain.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/chart1"
        android:layout_width="match_parent"
        android:layout_height="484dp" />
    <Button
        android:id="@+id/click"
        android:layout_below="@+id/chart1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

the Error Logcat message

Process: com.example.stackoverflowtry, PID: 32279 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.stackoverflowtry.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference at com.example.stackoverflowtry.MainActivity.drawChart(MainActivity.java:139) at com.example.stackoverflowtry.MainActivity.access$000(MainActivity.java:30) at com.example.stackoverflowtry.MainActivity$1.onClick(MainActivity.java:66)

tsion
  • 1
  • 1

1 Answers1

2

The NullPointerException is thrown here:

AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

trying to invoke the method addToRequestQueue. Apparently getInstance() is returning null. It looks like your onCreate method is never invoked, or mInstance is set to null anywhere else in your class MainActivity.

You should make sure, the method is really called. Maybe try setting some breakpoints to see your program flow.

Jan Held
  • 634
  • 4
  • 14
  • hello brother, the thing is I already understand the problem but I couldn't find anything that set to null you can check the code I posted all parts of the code and as I mentioned I am an absolute beginner maybe there is something that I didn't understand – tsion Feb 09 '20 at 19:35
  • Since I have no real knowledge regarding Android development I had to look a bit. I think the problem has already been addressed an solved here: https://stackoverflow.com/questions/34479808/volley-appcontroller-class-object-returning-null Hope this helps. – Jan Held Feb 09 '20 at 21:47
  • 1
    thanks, it really helps – tsion Feb 11 '20 at 10:05