Android weather Forecast method Based on HttpGet object parsing weather data _android

Source: Internet
Author: User
Tags getdate locale stringbuffer

The example described in this article is the code for the analysis of weather data for the Android weather forecast, which enables the acquisition of HttpGet objects to read weather data, and to parse weather data from the data, such as temperature, temperature, wind power, wind direction, weather trends for the next few days, weather conditions, air pollution indices, Also included is the call to the corresponding picture or weather animation file, for the development of the Android weather program can refer to the example of this article.

The specific function code is as follows:

Import java.io.IOException;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.Locale;
Import Net.tsz.afinal.FinalHttp;
Import Net.tsz.afinal.http.AjaxCallBack;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.HttpStatus;
Import org.apache.http.client.ClientProtocolException;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.util.EntityUtils;
Import org.json.JSONException;
Import Org.json.JSONObject;
Import org.lmw.weather.MyApp;
Import org.lmw.weather.entity.WeatherEntity;
Import android.app.Activity;
Import Android.os.Handler;
Import Android.os.Message;
 /** * Analysis of weather data * @author Dave/public class Weatherdata {The activity of private activity;
 Private Finalhttp FH;
 public static String def_weather_key= "Def_weather";
 Public Weatherdata (activity activity) {this.activity = activity;
 FH = new Finalhttp (); FH.configtimeout (1000 * 3);
 } public void GetData (final String cityid,final Handler HD) {stringbuffer sb_url = new StringBuffer ();
 Sb_url.append ("http://0.qnweather.duapp.com/weather.php?uri=");
 Sb_url.append ("http://m.weather.com.cn/data/");
 Sb_url.append (Cityid);
 Sb_url.append (". html");
 Final message Msg=new message ();
  Fh.get (Sb_url.tostring (), new Ajaxcallback () {@Override public void onsuccess (Object t) {super.onsuccess (t);
  Mysharedpreferences.writemessage (activity, "Def_weather", t.tostring ());
  msg.what=0;
  Msg.obj=parsejson (T.tostring ());
  Hd.sendmessage (msg);
  @Override public void OnFailure (Throwable t, int errorno, String strMsg) {super.onfailure (T, Errorno, STRMSG);
  System.out.println ("-------errorno---------" +errorno);
  Msg.what=-1;
  Msg.arg1=errorno;
  Msg.obj=mysharedpreferences.readmessage (activity, Def_weather_key, "");
  Hd.sendmessage (msg);
 }
 }); private string Connserverforresult (string strurl) {//Get HttpGet Object HttpGet httpRequest = new HttpGet (strURL);
 String strresult = "";
  try {//httpclient object HttpClient httpclient = new Defaulthttpclient ();
  Obtain HttpResponse object HttpResponse HttpResponse = Httpclient.execute (HttpRequest); if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {//get returned data Strresult = entityutils.tostring (HT
  Tpresponse.getentity ());
 } catch (Clientprotocolexception e) {e.printstacktrace ();
 catch (IOException e) {e.printstacktrace ();
 catch (Exception e) {e.printstacktrace ();
 } System.out.println ("Rresult" + strresult); return strresult;
 Return results}//Data resolution private weatherentity Parsejson (String strresult) {weatherentity weather = null;
  try {jsonobject jsonobj = new Jsonobject (Strresult.replace ("℃", "°")). Getjsonobject ("Weatherinfo");
  Weather = new weatherentity (); int ftime = Jsonobj.getint ("Fchh"); Update time (whole point) "Update time determines which day temp belongs to" int temp = 0;
  Offset if (ftime >= | | | Ftime < 8) {Weather.setnight (true); Temp = 1; } Myapp.week = Jsonobj.getstring ("Week");//day of the Week Weather.setcity (jsonobj.getstring ("City")); City Weather.setcomfortable (jsonobj.getstring ("index")); Comfort Degree Weather.setrefreshdate (GetDate ()); Update Date Weather.setrefreshtime (GetTime ()); Update Time Weather.setrefreshweek (Getweek ()); Update Week Weather.setpicindex (Jsonobj.getint ("IMG1")); Day weather picture number list<integer> toppic = new arraylist<integer> ();
  Picture number at the highest temperature if (temp = = 1) {toppic.add (getsavepic);
  else {Toppic.add (Getjsonpic (jsonobj, "img", 1 + temp));
  Savepic (activity, toppic.get (0));
  } toppic.add (Getjsonpic (jsonobj, "img", 3-temp));
  Toppic.add (Getjsonpic (jsonobj, "img", 5-temp));
  Toppic.add (Getjsonpic (jsonobj, "img", 7-temp));
  Weather.settoppic (Toppic); list<integer> lowpic = new arraylist<integer> ();
  The lowest temperature when the picture number Lowpic.add (Getjsonpic (jsonobj, "img", 2-temp));
  Lowpic.add (Getjsonpic (jsonobj, "img", 4-temp)); Lowpic.add (Getjsonpic (Jsonobj, "IMG ", 6-temp));
  Lowpic.add (Getjsonpic (jsonobj, "img", 8-temp));
  Weather.setlowpic (Lowpic); ---------------------------above to get the picture number, No matter----------------------------------------------------------------------list<string> templist = new Arraylist<string> ();
  The next five days temperature (first is today) Templist.add (jsonobj.getstring ("Temp1"));
  Templist.add (jsonobj.getstring ("Temp2"));
  Templist.add (jsonobj.getstring ("Temp3"));
  Templist.add (jsonobj.getstring ("Temp4"));
  Templist.add (jsonobj.getstring ("TEMP5"));
  Templist.add (jsonobj.getstring ("temp6"));
  MyApp.tempList.clear ();
  Myapp.templist = templist; list<string> weatherlist = new arraylist<string> ()//The weather for the next five days (the first is today) Weatherlist.add (Jsonobj.getstring ("
  Weather1 "));
  Weatherlist.add (jsonobj.getstring ("Weather2"));
  Weatherlist.add (jsonobj.getstring ("Weather3"));
  Weatherlist.add (jsonobj.getstring ("Weather4"));
  Weatherlist.add (jsonobj.getstring ("Weather5"));
 Weatherlist.add (jsonobj.getstring ("Weather6")); MyApp.weatherList.clear ();
  Myapp.weatherlist = weatherlist; list<string> Templistmax = new arraylist<string> ();
  Maximum temperature of the next five days set (with ° symbol) if (temp = 1) {Templistmax.add (Getsavetemperature (activity));
  else {Templistmax. Add (Gettemperaturemaxandmin (templist.get (0)) [0 + temp]);
  Savetemperature (activity, templistmax.get (0));
  } templistmax. Add (Gettemperaturemaxandmin (Templist.get (1-temp)) [0 + temp]);
  Templistmax. Add (Gettemperaturemaxandmin (Templist.get (2-temp)) [0 + temp]);
  Templistmax. Add (Gettemperaturemaxandmin (Templist.get (3-temp)) [0 + temp]);
  Weather.settemperaturemax (Templistmax); Weather.settodaytemperature (Gettemperaturemaxandmin (templist.get (0)) [0]); Day temperature (real time) Weather.settodayweather (jsonobj.getstring ("Img_title1")); Day weather Description (real time) list<string> templistmin = new arraylist<string> ();
  The next four days the lowest temperature set (with °c symbol) Templistmin.add (gettemperaturemaxandmin (templist.get (0)) [1-temp]); Templistmin.add (GettemperaturemaxanDMin (Templist.get (1)) [1-temp]);
  Templistmin.add (Gettemperaturemaxandmin (Templist.get (2)) [1-temp]);
  Templistmin.add (Gettemperaturemaxandmin (Templist.get (3)) [1-temp]);
  Weather.settemperaturemin (templistmin); Weather.settomorrowtemperature (Templist.get (1));
  Tomorrow's temperature (including the highest mild and lowest temperature) if (temp = 1) {weatherlist.add (getsaveweather);
  else {Weatherlist.add (jsonobj.getstring ("weather" + 1));
  Saveweather (activity, weatherlist.get (0));
  } weatherlist.add (Jsonobj.getstring ("Weather" + (2-temp)));
  Weatherlist.add (jsonobj.getstring ("Weather" + (3-temp)));
  Weatherlist.add (jsonobj.getstring ("Weather" + (4-temp)));
  Weather.setweather (weatherlist);
  Weather.settomorrowweather (Weatherlist.get (1)); list<string> windlist = new arraylist<string> ();
  The next four days Wind Windlist.add (jsonobj.getstring ("Wind1"));
  Windlist.add (jsonobj.getstring ("Wind2"));
  Windlist.add (jsonobj.getstring ("Wind3"));
  Windlist.add (jsonobj.getstring ("Wind4")); Weather.setwind (windlist); Weather.setmaxlist (Transplate (Templistmax)); The next four days the highest temperature set (no ° symbol) Weather.setminlist (transplate (templistmin));
 The next four days minimum temperature set (no ° symbol)} catch (Jsonexception e) {e.printstacktrace ();
 return weather; //Get the update date and convert to (x month X day week x) private String getDate () {SimpleDateFormat SDF = new SimpleDateFormat ("MM month DD day EEE", locale.c
 HINA);
 String date = Sdf.format (new java.util.Date ());
 SYSTEM.OUT.PRINTLN (date);
 return date; //Get update time and convert to (hour: minute update) Private String GetTime () {SimpleDateFormat SDF = new SimpleDateFormat ("hh:mm", Locale.chin
 A);
 String time = Sdf.format (new Java.util.Date ()) + "" + "Update";
 System.out.println (time);
 return time;
 Private String Getweek () {return null;
 //Get maximum temperature and minimum temperature, have ° symbol private string[] Gettemperaturemaxandmin (String str) {return str.split ("~"); //removal of the maximum temperature and minimum temperature in the ° symbol private list<integer> transplate (list<string> strlist) {list<integer> intlist
 = new Arraylist<integer> (); for (String Temp:strlIST) {Intlist.add (integer.valueof (Temp.split ("°") [0]);
 return intlist; //Get Picture number for example "IMG" + "1" private int getjsonpic (jsonobject jsonobj, String str, int index) throws jsonexception {in
 T result = jsonobj.getint (str + index);
  if (result = = && Index > 1) {index--;
 result = Jsonobj.getint (str + index);
 return result; } private void Savetemperature (activity activity, String value) {//Mysharedpreferences MP = new Mysharedpreferences (AC
 tivity);
 Mp.writemessage ("Temperature", value); ///Storage Temperature Private String getsavetemperature (activity activity) {return mysharedpreferences.readmessage (activity, "temp
 Erature "," 100 "); } private void Saveweather (activity activity, String value) {//Mysharedpreferences MP = new Mysharedpreferences (activi
 TY);
 Mp.writemessage ("Weather", value); }//Weather private String getsaveweather (activity activity) {return mysharedpreferences.readmessage (activity, "weather"
 , ""); } private void Savepic (Activity activity, int value) {//Mysharedpreferences MP = new mysharedpreferences (activity);
 Mp.writemessage ("Pic", value);
 ///Save weather Picture number private int getsavepic (activity activity) {return mysharedpreferences.readmessage (activity, "pic", 99);

 }
}

I hope this example will help you with the development of the Android weather program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.