doInBackground无缘无故地抛出NullPointerException

时间:2016-06-25 18:00:58

标签: android android-asynctask nullpointerexception

此处包含BufferedReaderline = reader.readLine()的代码

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();
    }
}
}

我将代码复制粘贴到其他类,因为它具有非常相似的功能,现在无缘无故我在NullPointerException得到while ((line = reader.readLine()) != null),我不知道为什么因为我说它的副本 - 粘贴(如果serivce成功,我只更改了URL和对象返回)

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();
    }
}
}

有任何线索吗?

修改 这是PollutionActivity的重写代码。回调函数serviceFailure现在打印手机屏幕上的URL地址

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();
    }
}
}

调试向我展示了代码跳转到异常之后 InputStream inputStream = connection.getInputStream();

1 个答案:

答案 0 :(得分:0)

如果你正在为读者获取NPE,那么这意味着读者没有被初始化并且变为空。你的代码在第23和89行崩溃了。所以我认为这个问题在某个地方是正确的,而不是在指向它本身,可能是某些对象像连接一样变为空。此处不显示行号。检查每个对象的空指针,如if(connection!= null)。由于初始数据为空,可能是输入流或其他一些数据,因此您的读取器对象未初始化。还要检查您是否在调试中获取每个对象的值。