我刚刚尝试了从谷歌天气 xml 获取天气的示例代码,但代码给出了 IOException,但我不知道我刚刚和视频一样的原因:http://www.youtube.com/watch?v=Z1rtldBTzCE 这是我的代码:
public class MyProjectActivity extends Activity implements android.view.View.OnClickListene {
/** Called when the activity is first created. */
TextView tv;
EditText edt1,edt2;
Button btn;
String site="hhttp://www.google.com/ig/api?weather=Lincoln,Nebraska";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView) findViewById(R.id.TV);
edt1=(EditText) findViewById(R.id.et1);
edt2=(EditText) findViewById(R.id.et2);
btn=(Button) findViewById(R.id.b1);
btn.
setOnClickListener( this);
}
public void onClick(View V){
String c=edt1.getText().toString();
String s=edt2.getText().toString();
StringBuilder url=new StringBuilder();
url.append(c+","+s);
String fullUrl=url.toString();
try{
URL website=new URL(fullUrl);
SAXParserFactory spf=SAXParserFactory.newInstance();
SAXParser sp=spf.newSAXParser();
XMLReader xr=sp.getXMLReader();
handler work=new handler();
xr.setContentHandler(work);
xr.parse(new InputSource (website.openStream()));
String information=work.getInfo();
tv.setText(information);
}catch(Exception e)
{
tv.setText("error");
}
}
package com.myProject.pro;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class handler extends DefaultHandler {
geterSetter info=new geterSetter();
public String getInfo(){
return info.dataToString();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if(localName.equals("city")){
String city=attributes.getValue("data");
info.setCity(city);
}else if(localName.equals("temp_c")){
String t=attributes.getValue("data");
int temp=Integer.parseInt(t);
info.setTemp(temp);
}
}
}
//设置获取类包com.myProject.pro;
public class geterSetter {
int temp;
String city;
public void setCity(String c){
city=c;
}
public void setTemp(int t){
temp=t;
}
public String dataToString(){
return city+temp;
}
}