package com.example.weatherforecast;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.util.Log;
public class WeatherForecast {
public final static String SONLA = "Sonla.xml";
public final static String VIETTRI = "Viettri.xml";
public final static String HAIPHONG = "Haiphong.xml";
public final static String HANOI = "Hanoi.xml";
public final static String VINH = "Vinh.xml";
public final static String DANANG = "Danang.xml";
public final static String NHATRANG = "Nhatrang.xml";
public final static String PLEICU = "Pleicu.xml";
public final static String HOCHIMINH = "HCM.xml";
private final String URL = "http://vnexpress.net/ListFile/Weather/";
private final String LOG_EXCEPTION = "log exception";
public ArrayList<WeatherObject> getAllWeatherOfCity() {
ArrayList<WeatherObject> arrWeatherObject = new ArrayList<WeatherObject>();
arrWeatherObject.add(getWeatherForecase(WeatherForecast.SONLA));
arrWeatherObject.add(getWeatherForecase(WeatherForecast.VIETTRI));
arrWeatherObject.add(getWeatherForecase(WeatherForecast.HAIPHONG));
arrWeatherObject.add(getWeatherForecase(WeatherForecast.HANOI));
arrWeatherObject.add(getWeatherForecase(WeatherForecast.VINH));
arrWeatherObject.add(getWeatherForecase(WeatherForecast.DANANG));
arrWeatherObject.add(getWeatherForecase(WeatherForecast.NHATRANG));
arrWeatherObject.add(getWeatherForecase(WeatherForecast.PLEICU));
arrWeatherObject.add(getWeatherForecase(WeatherForecast.HOCHIMINH));
return arrWeatherObject;
}
private String convertStatusWeather(String statusWeather) {
int index1 = statusWeather.indexOf('>');
int index2 = statusWeather.indexOf('<', index1);
if (index1 >= 0 && index2 >= 0) {
return statusWeather.substring(index1 + 1, index2);
}
return statusWeather;
}
private String convertCityToVNI(String cityXML) {
if (cityXML.equals(SONLA))
return "Sơn La";
else if (cityXML.equals(VIETTRI))
return "Việt Trì";
else if (cityXML.equals(HAIPHONG))
return "Hải Phòng";
else if (cityXML.equals(HANOI))
return "Hà Nội";
else if (cityXML.equals(VINH))
return "Vinh";
else if (cityXML.equals(DANANG))
return "Đà Nẵng";
else if (cityXML.equals(NHATRANG))
return "Nha Trang";
else if (cityXML.equals(PLEICU))
return "Pleicu";
else if (cityXML.equals(HOCHIMINH))
return "Hồ Chí Minh";
return null;
}
public WeatherObject getWeatherForecase(String city) {
try {
HttpGet uri = new HttpGet(URL + city);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(uri);
StatusLine status = resp.getStatusLine();
if (status.getStatusCode() != 200) {
Log.d(LOG_EXCEPTION, "HTTP error, invalid server status code: "
+ resp.getStatusLine());
}
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(resp.getEntity().getContent());
NodeList weatherTag = doc.getElementsByTagName("Weather");
Node weatherNode = weatherTag.item(0);
String statusWeather = weatherNode.getTextContent();
String temperatureStr = "";
for (int i = 1; i <= 5; i++) {
NodeList adImgTag = doc.getElementsByTagName("AdImg" + i);
Node temperatureNode = adImgTag.item(0);
String temperatureContent = temperatureNode.getTextContent();
if (!temperatureContent.equals("")) {
String str = temperatureContent.substring(0,
temperatureContent.indexOf('.'));
if (checkDigit(str))
temperatureStr += str;
}
}
String imageStatusWeather = "";
NodeList adImgTag = doc.getElementsByTagName("AdImg");
Node imgStatusWeather = adImgTag.item(0);
imageStatusWeather = imgStatusWeather.getTextContent();
WeatherObject weatherObject = new WeatherObject(
convertCityToVNI(city),
convertStatusWeather(statusWeather),
Integer.parseInt(temperatureStr), imageStatusWeather);
return weatherObject;
} catch (Exception e) {
Log.d(LOG_EXCEPTION, e.getMessage());
return null;
}
}
private boolean checkDigit(String digit) {
char[] arr = digit.toCharArray();
for (char c : arr) {
if (!Character.isDigit(c))
return false;
}
return true;
}
}
1 class tên WeatherApdater.java để tùy biến adapter khi bind vào listactivity
package com.example.weatherforecast;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class WeatherAdapter extends ArrayAdapter<WeatherObject> {
private final String URL = "http://vnexpress.net/Images/Weather/";
private Context mContext;
private ArrayList<WeatherObject> mArrayWeatherObject;
public WeatherAdapter(Context context, int textViewResourceId,
ArrayList<WeatherObject> arrayWeatherObject) {
super(context, textViewResourceId, arrayWeatherObject);
this.mContext = context;
this.mArrayWeatherObject = arrayWeatherObject;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
WeatherObject weatherObject = (WeatherObject) getItem(position);
if (weatherObject != null) {
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.listview_child, null);
}
ImageView imgStatusWeather = (ImageView) convertView
.findViewById(R.id.imgStatusWeather);
TextView txtCity = (TextView) convertView
.findViewById(R.id.txtCity);
TextView txtTemperature = (TextView) convertView
.findViewById(R.id.txtTemperature);
TextView txtStatusWeather = (TextView) convertView
.findViewById(R.id.txtStatusWeather);
txtCity.setText(weatherObject.getCity());
txtTemperature.setText(String.valueOf(weatherObject
.getTemperature()) + " *C");
txtStatusWeather.setText(weatherObject.getStatusWeather());
new DownloadImageTask(imgStatusWeather).execute(URL
+ weatherObject.getImageStatusWeather());
}
return convertView;
}
@Override
public WeatherObject getItem(int position) {
return mArrayWeatherObject.get(position);
}
}
Cuối cùng là MainActivity.java
package com.example.weatherforecast;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class MainActivity extends ListActivity {
private WeatherAdapter mWeatherAdapter;
private ArrayList<WeatherObject> mArrWeather;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mArrWeather = new WeatherForecast().getAllWeatherOfCity();
mWeatherAdapter = new WeatherAdapter(this,
android.R.layout.simple_list_item_1, mArrWeather);
setListAdapter(mWeatherAdapter);
Thread thread = new Thread(new ThreadLoop());
thread.start();
}
public Handler updateHandler = new Handler() {
public void handleMessage(Message msg) {
mArrWeather = new WeatherForecast().getAllWeatherOfCity();
mWeatherAdapter.notifyDataSetChanged();
super.handleMessage(msg);
}
};
public class ThreadLoop implements Runnable {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10000);
MainActivity.this.updateHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
}
}
}
}
}
Trong file Manifest.xml nhớ thêm
<uses-permission android:name="android.permission.INTERNET" />
để cho kết nối internet nhé