我正在学习关于udacity'开发Android应用程序'的课程。以下是ForecastFragment类的代码,它假定从url(http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric)获取json格式的数据。
public class ForecastFragment extends Fragment {
public ForecastFragment() {
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] data = {
"Today-Sunny-34", "Tommorow-Rainy-233", "Wednesday-Cloudy-21", "Thursday-Monayblue-18", "Frida-Rainy-23", "Saturday-Rainy-22", "Sunday-Strorm-100"
};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
inflater.inflate(R.menu.forecastfragment, menu);
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id==R.id.action_refresh){
FetchWeatherTask fetch = new FetchWeatherTask();
fetch.execute();
return true;}
return super.onOptionsItemSelected(item);
}
public class FetchWeatherTask extends AsyncTask<Void,Void,Void>{
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
@Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
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;
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG,"Forecast Json String" + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error", e);
return null;
} finally {
if (urlConnection != null) urlConnection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("placeholder fragment", "error closing stream", e);
}
}
}
return null;
}
}
}
但是,我反复收到此错误。
07-20 12:49:14.063 2392-2486/com.example.android.sunshine.app E/FetchWeatherTask﹕ Error
java.net.UnknownHostException: api.openweathermap.org
at java.net.InetAddress.lookupHostByName(InetAddress.java:512)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:300)
at java.net.InetAddress.getAllByName(InetAddress.java:259)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:119)
at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1027)
以下是我已经检查的内容: -
AndroidManifest.xml声明了互联网使用权限。
网址在浏览器中运行良好,但我对此错误的原因一无所知。
另外,我在Android手机上运行应用程序(api 10)。
如果有人能提供解决方案或指出我正确的方向,那就太棒了。谢谢。
答案 0 :(得分:1)
我有同样的问题。但我没有在手机上打开WiFi。激活wifi解决了我的问题。
答案 1 :(得分:0)
我按原样复制了Async类,并在Mac机器上的KitKat VM上的新项目中运行它。结果如下:
07-19 14:40:32.070 1670-1683/centerorbit.com.myapplication V/FetchWeatherTask﹕ Forecast Json String{"city":{"id":1273294,"name":"Delhi","coord":{"lon":77.216667,"lat":28.666668},"country":"IN","population":0},"cod":"200","message":0.0095,"cnt":7,"list":[{"dt":1437285600,"temp":{"day":29,"min":28.21,"max":29,"night":28.21,"eve":29,"morn":29},"pressure":984.15,"humidity":88,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"speed":1.66,"deg":64,"clouds":36},{"dt":1437372000,"temp":{"day":29.15,"min":25.17,"max":31.21,"night":27.92,"eve":31.21,"morn":26.55},"pressure":986.25,"humidity":95,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":3.22,"deg":86,"clouds":88,"rain":10.65},{"dt":1437458400,"temp":{"day":30.46,"min":25.15,"max":31.57,"night":27.94,"eve":31.1,"morn":25.15},"pressure":988.81,"humidity":83,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":6.41,"deg":111,"clouds":68,"rain":0.45},{"dt":1437544800,"temp":{"day":30.63,"min":26.12,"max":32.69,"night":28.12,"eve":32.69,"morn":26.12},"pressure":991.01,"humidity":81,"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"speed":3.57,"deg":118,"clouds":64},{"dt":1437631200,"temp":{"day":34.27,"min":25.81,"max":35.34,"night":27.1,"eve":33.11,"morn":25.81},"pressure":989.86,"humidity":78,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":2.06,"deg":74,"clouds":8,"rain":3.94},{"dt":1437717600,"temp":{"day":31.12,"min":25.71,"max":31.12,"night":26.68,"eve":30.83,"morn":25.71},"pressure":991.3,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.06,"deg":184,"clouds":13,"rain":7.82},{"dt":1437804000,"temp":{"day":31.68,"min":25.88,"max":32.17,"night":27.01,"eve":32.17,"morn":25.88},"pressure":989.57,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.28,"deg":226,"clouds":52,"rain":5.89}]}
您的代码似乎很好,而且您的系统/网络出现问题。我建议您重新启动手机/计算机以查看是否能解决问题。如果没有,请尝试使用其他网络(断开与家庭WiFi的连接并使用Cell网络)。
答案 2 :(得分:0)
您已在androidManifest中注册了访问Internet的权限
<uses-permission android:name="android.permission.INTERNET"/>
答案 3 :(得分:-1)
在URL末尾附加APIKey 要获得APIKey,您必须在 openweathermap.org 上创建帐户 例如http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric的&安培;的appid = yourapiid 强>“
获取APIKey的详细过程是