我正在尝试构建一个从Wunderground.com中提取数据的应用程序,并使用ListView将数据流式传输到Android应用程序中。我的合作伙伴和我已经成功地使ListView工作,但是从Wunderground流式传输数据会导致一些问题。
奇怪的是,如果我拉取获取数据的代码并将其粘贴到eclipse中,它就可以工作(偶尔会这样)。我在网上寻找解决方案,但似乎找不到任何有用的东西。我们正在尝试下拉以下天气数据:湿度,温度,条件,日期时间以及与数据相关的图像。
以下是代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
String sURL = "http://freegeoip.net/json/";
URL url = new URL(sURL);//Create a URL object
//Connect to the website with the url variable
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser jp = new JsonParser();//Create an object from the JsonParser class
JsonElement root = jp.parse(new BufferedReader(new InputStreamReader((InputStream) request.getContent())));
JsonObject rootobj = root.getAsJsonObject();//create an object for the element
String ZipCode = rootobj.get("zip_code").getAsString();
//Create a string for the web address with the key
String sURL1 = "http://api.wunderground.com/api/1e404159ad02dddd/conditions/hourly/q/" + ZipCode + ".json";
URL url1 = new URL(sURL1);//Create a URL object
//Connect to the website with the url variable
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.connect();
JsonParser jp1 = new JsonParser();//Create an object from the JsonParser class
JsonElement root1 = jp1.parse(new InputStreamReader((InputStream) request1.getContent()));
JsonObject rootobj1 = root1.getAsJsonObject();//create an object for the element
JsonArray printArray = rootobj1.get("hourly_forecast").getAsJsonArray();
//Add all Wunderground data to the List
for(int i = 0; i < printArray.size(); i++)
{
String dateTime = rootobj1.get("hourly_forecast").getAsJsonArray().get(i).getAsJsonObject().get("FCTTIME").getAsJsonObject().get("pretty").getAsString();
String condition = rootobj1.get("hourly_forecast").getAsJsonArray().get(i).getAsJsonObject().get("condition").getAsString();
String temp = rootobj1.get("hourly_forecast").getAsJsonArray().get(i).getAsJsonObject().get("temp").getAsJsonObject().get("english").getAsString();
String humidity = rootobj1.get("hourly_forecast").getAsJsonArray().get(i).getAsJsonObject().get("humidity").getAsString();
String image = rootobj1.get("hourly_forecast").getAsJsonArray().get(i).getAsJsonObject().get("icon_url").getAsString();
itemName[i] = "The date is " + dateTime + ". It is " + condition + " outside. It is " + temp + " degrees outside. The humidity is at " + humidity + " percent.";
}
}
catch(Exception e)
{
e.printStackTrace();
}
感谢任何帮助。谢谢。