所以我有一个从网上下载和解析xml文件的项目,但我对如何使用从xml文件中检索的数据填充文本信息感到茫然。我只知道它几行代码,但我在下面编写了代码。 谢谢你的帮助。
public class MainActivity extends Activity {
String stringURL = "http://w1.weather.gov/xml/current_obs/KORD.xml";
TextView station, stationData, observation, observationData, weather,
weatherData, temperature, temperatureData, wind, windData;
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTextViews();
pd = new ProgressDialog(this);
pd.setIndeterminate(true);
downloadXML();
}
public void initTextViews() {
station = (TextView) findViewById(R.id.station);
stationData = (TextView) findViewById(R.id.stationdata);
observation = (TextView) findViewById(R.id.observation);
observationData = (TextView) findViewById(R.id.observationdata);
weather = (TextView) findViewById(R.id.weather);
weatherData = (TextView) findViewById(R.id.weatherdata);
temperature = (TextView) findViewById(R.id.tempurature);
temperatureData = (TextView) findViewById(R.id.tempuraturedata);
wind = (TextView) findViewById(R.id.wind);
windData = (TextView) findViewById(R.id.winddata);
}
public void downloadXML() {
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.show();
pd.setTitle("Weather Data");
pd.setMessage("getting weather data");
}
@Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection httpConnection;
InputStream is;
try {
Looper.prepare();
url = new URL(stringURL);
httpConnection = (HttpURLConnection) url.openConnection();
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"KORD.xml");
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = httpConnection.getInputStream();
//Looper.loop();
//this is the total size of the file
int totalSize = httpConnection.getContentLength();
pd.setMax(totalSize);
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
parseWeatherXML();
}
};
task.execute();
}
public void parseWeatherXML() {
String station, observation, weather, temperature, wind;
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
try {
String path = Environment.getExternalStorageDirectory()+"/"+"KORD.xml";
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
//InputStream is = getAssets().open("KORD.xml");
SAXHandler sh = new SAXHandler();
parser.parse(fileInputStream, sh);
final Weather mWeather = sh.getWeather();
//populate your view here!
// !!!! populate tewxtviews here? !!!!
// i outcommented what i tried..
//String output = "";
//output += "station ID: " + mWeather.getStationId() + "\n";
//output += "obervation: " + mWeather.getObsevationTime() + "\n";
//output += "weather: " + mWeather.getWeather() + "\n";
//output += "temp: " + mWeather.getTemperature() + "\n";
//output += "wind: " + mWeather.getWind() + "\n";
//windData.setText(output);
/* String temp = mWeather.obsevationTime;
stationData.setText(mWeather.getStationId());
observationData.setText(mWeather.getObsevationTime());
weatherData.setText(mWeather.getWeather());
temperatureData.setText(mWeather.getTemperature());
windData.setText(mWeather.getWind());*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
downloadXML();
return true;
}
return super.onOptionsItemSelected(item);
}
public class SAXHandler extends DefaultHandler{
boolean stringTagStarted = false;
private String tempVal;
private Weather tempWeather;
public Weather getWeather(){
return tempWeather;
}
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
tempVal = "";
if (qName.equalsIgnoreCase("current_observation")) {
tempWeather = new Weather();
}
}
@Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
Log.i("", "End of element: " + qName + " , "
+ localName);
if(qName.equalsIgnoreCase("station_id")){
tempWeather.setStationId(tempVal);
}else if(qName.equalsIgnoreCase("observation_time")){
tempWeather.setObsevationTime(tempVal);
}else if(qName.equalsIgnoreCase("weather")){
tempWeather.setWeather(tempVal);
}else if(qName.equalsIgnoreCase("temperature_string")){
tempWeather.setTemperature(tempVal);
}else if(qName.equalsIgnoreCase("wind_string")){
tempWeather.setWind(tempVal);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
Log.i("Characters", new String(ch, start, length));
tempVal = new String(ch, start, length);
}
}
}
public class Weather {
public Weather() {
}
String stationId, obsevationTime, weather, temperature, wind;
public String getStationId() {
return stationId;
}
public void setStationId(String stationId) {
this.stationId = stationId;
}
public String getObsevationTime() {
return obsevationTime;
}
public void setObsevationTime(String obsevationTime) {
this.obsevationTime = obsevationTime;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.weatherdata.MainActivity"
android:orientation="vertical" >
<TextView
android:id="@+id/station"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Station: "
android:textSize="18dp" />
<TextView
android:id="@+id/stationdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:text="stationdata" />
<TextView
android:id="@+id/observation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Observation Time: "
android:textSize="18dp" />
<TextView
android:id="@+id/observationdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:text="observationdata" />
<TextView
android:id="@+id/weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Weather: "
android:textSize="18dp" />
<TextView
android:id="@+id/weatherdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:text="weatherdata" />
<TextView
android:id="@+id/tempurature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Temperature: "
android:textSize="18dp" />
<TextView
android:id="@+id/tempuraturedata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:text="temperaturedata" />
<TextView
android:id="@+id/wind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Wind: "
android:textSize="18dp" />
<TextView
android:id="@+id/winddata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:text="winddata" />
</LinearLayout>
答案 0 :(得分:0)
只需在代码中取消评论此部分:
String temp = mWeather.obsevationTime;
stationData.setText(mWeather.getStationId());
observationData.setText(mWeather.getObsevationTime());
weatherData.setText(mWeather.getWeather());
temperatureData.setText(mWeather.getTemperature());
windData.setText(mWeather.getWind());
此外,您可以创建一个方法,您可以在其中传递天气对象并在其中设置textview的值,而不是在onPostExecute()