Android udacity sunshine应用程序即使在使用ASyncTask后也会崩溃

Android udacity sunshine应用程序即使在使用ASyncTask后也会崩溃,android,Android,在本节之前,该应用程序工作正常。但在插入网络代码后,它不会打开(崩溃) //这是fetchweathertask类,即使从上面的类中移动了网络代码,应用程序仍然无法在手机上启动 listView.setAdapter(mForecastAdapter); return rootView; } 公共类FetchWeatherTask扩展了AsyncTask{ 私有最终字符串LOG_TAG=FetchWeatherTask.class.getSimpl

在本节之前,该应用程序工作正常。但在插入网络代码后,它不会打开(崩溃) //这是fetchweathertask类,即使从上面的类中移动了网络代码,应用程序仍然无法在手机上启动

        listView.setAdapter(mForecastAdapter);

        return  rootView;

    }
公共类FetchWeatherTask扩展了AsyncTask{
私有最终字符串LOG_TAG=FetchWeatherTask.class.getSimpleName();
@凌驾
受保护的Void doInBackground(Void…参数){
//这两个需要在try/catch之外声明
//这样就可以在finally块中关闭它们。
HttpURLConnection-urlConnection=null;
BufferedReader reader=null;
//将以字符串形式包含原始JSON响应。
字符串forecastJsonStr=null;
试一试{
//构造OpenWeatherMap查询的URL
//可能的参数可在OWM的预测API页面上获得,网址为
// http://openweathermap.org/API#forecast
URL=新URL(“http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
//创建对OpenWeatherMap的请求,并打开连接
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod(“GET”);
urlConnection.connect();
//将输入流读入字符串
InputStream InputStream=urlConnection.getInputStream();
StringBuffer=新的StringBuffer();
如果(inputStream==null){
//无事可做。
forecastJsonStr=null;
}
reader=新的BufferedReader(新的InputStreamReader(inputStream));
弦线;
而((line=reader.readLine())!=null){
//因为它是JSON,所以不需要添加换行符(这不会影响解析)
//但是如果你打印出完成的代码,调试会变得容易得多
//用于调试的缓冲区。
buffer.append(第+行“\n”);
}
if(buffer.length()==0){
//流为空。在分析中没有意义。
forecastJsonStr=null;
}
forecastJsonStr=buffer.toString();
}捕获(IOE异常){
Log.e(“占位符片段”,“错误”,e);
//如果代码没有成功获取天气数据,那么尝试是没有意义的
//来解析它。
forecastJsonStr=null;
}最后{
if(urlConnection!=null){
urlConnection.disconnect();
}
if(读卡器!=null){
试一试{
reader.close();
}捕获(最终IOE例外){
Log.e(“占位符片段”,“错误关闭流”,e);
}
}
}
返回null;
}
}
}

您需要在manifest.xml文件中包含Internet权限

    public class FetchWeatherTask extends AsyncTask<Void, Void, Void> {

                private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

                        @Override
                protected Void doInBackground(Void... params) {
                        // These two need to be declared outside the try/catch
                                // so that they can be closed in the finally block.
                            HttpURLConnection urlConnection = null;
                            BufferedReader reader = null;

// Will contain the raw JSON response as a string.
                            String forecastJsonStr = null;

                            try {
                                // Construct the URL for the OpenWeatherMap query
                                // Possible parameters are available at OWM's forecast API page, at
                                // http://openweathermap.org/API#forecast
                                URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");

                                // Create the request to OpenWeatherMap, and open the connection
                                urlConnection = (HttpURLConnection) url.openConnection();
                                urlConnection.setRequestMethod("GET");
                                urlConnection.connect();

                                // Read the input stream into a String
                                InputStream inputStream = urlConnection.getInputStream();
                                StringBuffer buffer = new StringBuffer();
                                if (inputStream == null) {
                                    // Nothing to do.
                                    forecastJsonStr = null;
                                }
                                reader = new BufferedReader(new InputStreamReader(inputStream));

                                String line;
                                while ((line = reader.readLine()) != null) {
                                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                                    // But it does make debugging a *lot* easier if you print out the completed
                                    // buffer for debugging.
                                    buffer.append(line + "\n");
                                }

                                if (buffer.length() == 0) {
                                    // Stream was empty.  No point in parsing.
                                    forecastJsonStr = null;
                                }
                                forecastJsonStr = buffer.toString();
                            } catch (IOException e) {
                                Log.e("PlaceholderFragment", "Error ", e);
                                // If the code didn't successfully get the weather data, there's no point in attempting
                                // to parse it.
                                forecastJsonStr = null;
                            } finally{
                                if (urlConnection != null) {
                                    urlConnection.disconnect();
                                }
                                if (reader != null) {
                                    try {
                                        reader.close();
                                    } catch (final IOException e) {
                                        Log.e("PlaceholderFragment", "Error closing stream", e);
                                    }
                                }
                            }
                        return null;
                    }
    }
}

没有它,你的应用程序将崩溃

读这个

我未经允许测试了你的代码,它崩溃了。我还测试了它的许可,它并没有崩溃。从那开始


您还有其他事情要做,比如在url字符串中包含API键。请记住,您可以在Udacity论坛上发表文章,数百名学生目前正在从事同一项目。

stackoverflow新手。请遵守问题的格式
    public class FetchWeatherTask extends AsyncTask<Void, Void, Void> {

                private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

                        @Override
                protected Void doInBackground(Void... params) {
                        // These two need to be declared outside the try/catch
                                // so that they can be closed in the finally block.
                            HttpURLConnection urlConnection = null;
                            BufferedReader reader = null;

// Will contain the raw JSON response as a string.
                            String forecastJsonStr = null;

                            try {
                                // Construct the URL for the OpenWeatherMap query
                                // Possible parameters are available at OWM's forecast API page, at
                                // http://openweathermap.org/API#forecast
                                URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");

                                // Create the request to OpenWeatherMap, and open the connection
                                urlConnection = (HttpURLConnection) url.openConnection();
                                urlConnection.setRequestMethod("GET");
                                urlConnection.connect();

                                // Read the input stream into a String
                                InputStream inputStream = urlConnection.getInputStream();
                                StringBuffer buffer = new StringBuffer();
                                if (inputStream == null) {
                                    // Nothing to do.
                                    forecastJsonStr = null;
                                }
                                reader = new BufferedReader(new InputStreamReader(inputStream));

                                String line;
                                while ((line = reader.readLine()) != null) {
                                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                                    // But it does make debugging a *lot* easier if you print out the completed
                                    // buffer for debugging.
                                    buffer.append(line + "\n");
                                }

                                if (buffer.length() == 0) {
                                    // Stream was empty.  No point in parsing.
                                    forecastJsonStr = null;
                                }
                                forecastJsonStr = buffer.toString();
                            } catch (IOException e) {
                                Log.e("PlaceholderFragment", "Error ", e);
                                // If the code didn't successfully get the weather data, there's no point in attempting
                                // to parse it.
                                forecastJsonStr = null;
                            } finally{
                                if (urlConnection != null) {
                                    urlConnection.disconnect();
                                }
                                if (reader != null) {
                                    try {
                                        reader.close();
                                    } catch (final IOException e) {
                                        Log.e("PlaceholderFragment", "Error closing stream", e);
                                    }
                                }
                            }
                        return null;
                    }
    }
}
<uses-permission android:name="android.permission.INTERNET" />