简体   繁体   中英

doInBackground throws NullPointerException for no reason

In here the code with BufferedReader and line = reader.readLine() works

public class WeatherService extends AsyncTask<TaskParams, Void, String> {
private WeatherServiceCallback callback;
private Exception exception;

public WeatherService(WeatherServiceCallback callback) {
    this.callback = callback;
}

@Override
protected String doInBackground(TaskParams... params) {
    try {
        URL url = new URL("http://api.openweathermap.org/data/2.5/weather?lat=" +
                params[0].getLat() + "&lon=" + params[0].getLon() +
                "&units=" + TaskParams.getUnits() +
                "&type=" + TaskParams.getAccuracy() + "&lang=" + TaskParams.getLanguage() +
                "&appid=10660a09a9fb335d72f576f7aa1bbe5b");

        URLConnection connection = url.openConnection();
        InputStream inputStream = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder builder = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        return builder.toString();
    } catch (MalformedURLException e) {
        exception = e;
    } catch (IOException e) {
        exception = e;
    }

    return null;
}

@Override
protected void onPostExecute(String s)
{
    if (s == null && exception != null)
    {
        callback.serviceFailure(exception);
        return;
    }

    try
    {
        JSONObject data = new JSONObject(s);
        Parameters parameters = new Parameters();
        parameters.poopulate(data);
        callback.serviceSuccess(parameters);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
}

I copy-pasted code to other class since it has very similar functionality and now for no reason I'm getting NullPointerException in while ((line = reader.readLine()) != null) and I have no idea why since as I said it's copy-pasted (I only changed URL and object returned if serivce succeeds)

public class PollutionService extends AsyncTask<TaskParams, Void, String>
{

private PollutionServiceCallback callback;
private Exception exception;
private URLConnection connection;
private InputStream inputStream;
private InputStreamReader streamReader;
private BufferedReader reader;

public PollutionService(PollutionServiceCallback callback) {
    this.callback = callback;
}

@Override
protected String doInBackground(TaskParams... params) {
    try
    {
        URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
                "," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");

        try
        {
            connection = url.openConnection();
        }

        catch (IOException e)
        {
            exception = new Exception("Connection error");
        }

        try
        {
            inputStream = connection.getInputStream();
        }

        catch (IOException e)
        {
            exception = new Exception("Input stream error");
        }

        try
        {
            streamReader = new InputStreamReader(inputStream);
        }

        catch (NullPointerException e)
        {
            exception = new Exception("Input stream reader error");
        }

        try
        {
            reader = new BufferedReader(streamReader);
        }

        catch (NullPointerException e)
        {
            exception = new Exception("Buffered reader error");
        }

        StringBuilder builder = new StringBuilder();
        String line;

        try
        {
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
        }

        catch (IOException e)
        {
            exception = e;
        }

        return builder.toString();
    }
    catch (MalformedURLException e)
    {
        exception = e;
    }

    return null;
}

@Override
protected void onPostExecute(String s)
{
    if (s == null && exception != null)
    {
        callback.pollutionServiceFailure(exception);
        return;
    }

    try
    {
        JSONObject data = new JSONObject(s);
        PollutionParameters parameters = new PollutionParameters();
        parameters.poopulate(data);
        callback.pollutionServiceSuccess(parameters);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
}

Any clue?

EDIT This is rewritten code for PollutionActivity . Callback function serviceFailure prints now the URL address on my phone's screen

public class PollutionService extends AsyncTask<TaskParams, Void, String>
{

private PollutionServiceCallback callback;
private Exception exception;

public PollutionService(PollutionServiceCallback callback) {
    this.callback = callback;
}

@Override
protected String doInBackground(TaskParams... params) {
    try
    {
        URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
                "," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");

        URLConnection connection = url.openConnection();
        InputStream inputStream = connection.getInputStream();
        InputStreamReader streamReader = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(streamReader);

        StringBuilder builder = new StringBuilder();
        String line;

        try
        {
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
        }

        catch (IOException e)
        {
            exception = e;
        }

        return builder.toString();
    }
    catch (MalformedURLException e)
    {
        exception = e;
    }

    catch (IOException e)
    {
        exception = e;
    }

    return null;
}

@Override
protected void onPostExecute(String s)
{
    if (s == null && exception != null)
    {
        callback.pollutionServiceFailure(exception);
        return;
    }

    try
    {
        JSONObject data = new JSONObject(s);
        PollutionParameters parameters = new PollutionParameters();
        parameters.poopulate(data);
        callback.pollutionServiceSuccess(parameters);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
}

Debugging showed me that code jumps to exception after InputStream inputStream = connection.getInputStream();

If you are getting NPE for reader then it means that reader is not getting initialized and going null.Your code is getting crash at line 23 and 89. So I believe that the problem is right at the start somewhere and not at the point itself, may be some object is going null like connection.Since line number is not displayed here.Check null pointer for every object like if (connection!=null). Since the initial data is coming null,maybe input stream or some other data,hence your reader object is not getting initialized.Also check if you are getting value for every object in debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM