Android Weather forecast based on HttpGet object analysis of weather data

  • 2020-06-07 05:17:00
  • OfStack

Mentioned in this instance the parsing of Android weather forecast weather data code, which can realize gain HttpGet object read weather site weather data, and analyze the weather data from the data, such as temperature, temperature, wind, wind direction, the next few days the weather trend, the information such as weather conditions, the air pollution index in the day, also includes the file, call the corresponding picture or the weather animation for developing android can refer to the weather forecast program examples in this paper.

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;
/**
 *  Parsing weather data 
 * @author Dave
 */
public class WeatherData {
 private Activity 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) {
 //  To obtain HttpGet object 
 HttpGet httpRequest = new HttpGet(strUrl);
 String strResult = "";
 try {
  // HttpClient object 
  HttpClient httpClient = new DefaultHttpClient();
  //  To obtain HttpResponse object 
  HttpResponse httpResponse = httpClient.execute(httpRequest);
  if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  //  Gets the returned data 
  strResult = EntityUtils.toString(httpResponse.getEntity());
  }
 } catch (ClientProtocolException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 } catch (Exception e) {
  e.printStackTrace();
 }
 System.out.println("rresult" + strResult);
 return strResult; //  Returns the result 
 }
 //  Data parsing 
 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 (on the hour) [Update time determined temp Which day is it? 
  int temp = 0; //  The offset 
  if (ftime >= 18 || ftime < 8) {
  weather.setNight(true);
  temp = 1;
  }
  MyApp.week = jsonObj.getString("week");//  What day is it today 
  weather.setCity(jsonObj.getString("city")); //  city 
  weather.setComfortable(jsonObj.getString("index")); //  comfort 
  weather.setRefreshDate(getDate()); //  Updated date 
  weather.setRefreshTime(getTime()); //  Update time 
  weather.setRefreshWeek(getWeek()); //  Update the week 
  weather.setPicIndex(jsonObj.getInt("img1")); //  Weather picture no 
  List<Integer> topPic = new ArrayList<Integer>(); //  The image number at the highest temperature 
  if (temp == 1) {
  topPic.add(getSavePic(activity));
  } 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>(); //  Picture number at the lowest temperature 
  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 is to get the picture number, leave aside ----------------------------------------------------------------------
  List<String> tempList = new ArrayList<String>(); //  In the future 5 Day temperature (S 1 It's 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>();//  In the future 5 The weather (No 1 It's 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>(); //  In the future 5 Maximum daily temperature 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]); //  Daily temperature (real-time) 
  weather.setTodayWeather(jsonObj.getString("img_title1")); //  Daily weather description (real-time) 
  List<String> tempListMin = new ArrayList<String>(); //  In the future 4 Minimum temperature set (with  °  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)); //  Temperature tomorrow (including maximum temperature and lowest temperature) 
  if (temp == 1) {
  weatherList.add(getSaveWeather(activity));
  } 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>(); //  In the future 4 Days the 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)); //  In the future 4 Maximum daily temperature set (no  °  Symbol) 
  weather.setMinlist(transplate(tempListMin)); //  In the future 4 Daily minimum temperature set (no  °  Symbol) 
 } catch (JSONException e) {
  e.printStackTrace();
 }
 return weather;
 }
 //  Get update date   And convert to ( X month X day   weeks X ) 
 private String getDate() {
 SimpleDateFormat sdf = new SimpleDateFormat("MM month dd day  EEE", Locale.CHINA);
 String date = sdf.format(new java.util.Date());
 System.out.println(date);
 return date;
 }
 //  Get update time   And converted into   (Hours: minutes   Update) 
 private String getTime() {
 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.CHINA);
 String time = sdf.format(new java.util.Date()) + " " + " update ";
 System.out.println(time);
 return time;
 }
 private String getWeek() {
 return null;
 }
 //  Get the highest temperature and the lowest temperature, with the degree sign 
 private String[] getTemperatureMaxAndMin(String str) {
 return str.split("~");
 }
 //  Remove the degrees from the highest and lowest temperatures 
 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 {
 int result = jsonObj.getInt(str + index);
 if (result == 99 && index > 1) {
  index--;
  result = jsonObj.getInt(str + index);
 }
 return result;
 }
 private void saveTemperature(Activity activity, String value) {
 // MySharedPreferences mp = new MySharedPreferences(activity);
 // mp.writeMessage("temperature", value);
 }
 //  Temperature of preservation 
 private String getSaveTemperature(Activity activity) {
 return MySharedPreferences.readMessage(activity,"temperature", "100");
 }
 private void saveWeather(Activity activity, String value) {
 // MySharedPreferences mp = new MySharedPreferences(activity);
 // mp.writeMessage("weather", value);
 }
 //  Preserved 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 the weather picture number 
 private int getSavePic(Activity activity) {
 return MySharedPreferences.readMessage(activity,"pic", 99);
 }
}

It is hoped that the examples in this paper will be helpful to the development of Android weather forecasting program.


Related articles: