0

So I am having some problems with getting this code to work, I found some of this code online but it won't work. I have tried adjusting some code but no matter what I am doing, the app just crashes with an error. I have been trying to get this to work for a few days now with hours of googling and watching YouTube tutorials and I cannot seem to get this to work.

Can someone shed some light on what I am doing wrong here?

CODE:

public class fetchJSON extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        URL url;
        try {
            url = new URL("www.link.to.json");
            urlConnection.setRequestMethod("GET"); //Your method here
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null)
                buffer.append(line + "\n");

            if (buffer.length() == 0)
                return null;

            return buffer.toString();
        } catch (IOException e) {
            Log.e(TAG, "IO Exception", e);
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(TAG, "Error closing stream", e);
                }
            }
        }
    }

    @Override
    protected void onPostExecute(String response) {
        if(response != null) {
            JSONObject json = null;
            try {
                json = new JSONObject(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject jsonResponse = null;
            try {
                jsonResponse = json.getJSONObject("Question1");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MainActivity.jsonPrint.setText((CharSequence) jsonResponse);
        }
    }
}

ERROR:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: uk.co.jrtevents.fetchjsonfromurltest, PID: 4019
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:318)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: java.lang.NullPointerException: Attempt to invoke a virtual method on a null object reference
        at uk.co.jrtevents.fetchjsonfromurltest.fetchJSON.doInBackground(fetchJSON.java:31)
        at uk.co.jrtevents.fetchjsonfromurltest.fetchJSON.doInBackground(fetchJSON.java:18)
        at android.os.AsyncTask$2.call(AsyncTask.java:304)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)

LINE 31: urlConnection.setRequestMethod("GET");

2
  • What is line 31 of fetchJSON.java? Commented Jan 11, 2020 at 22:00
  • Updated the question to reflect your request, it is: urlConnection.setRequestMethod("GET"); Commented Jan 11, 2020 at 22:01

1 Answer 1

3
HttpURLConnection urlConnection = null;

You never assign a value to urlConnection, and so it is null.

You would need to add:

urlConnection = url.openConnection();

before trying to use urlConnection.

URL and HttpURLConnection are very old, and very few developers use them anymore. You may have better luck using more modern HTTP client APIs, such as OkHttp.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.