簡體   English   中英

如何從解析的XML Android填充TextView

[英]How to populate textview from parsed xml android

因此,我有一個項目可以從網上下載並解析xml文件,但是我對如何使用從xml文件檢索的數據填充textveiws感到迷茫。 我只走了幾行代碼,我就知道,但是我很困惑...下面的代碼。 謝謝您的幫助。

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>

只需從代碼中取消注釋此部分:

             String temp = mWeather.obsevationTime;
             stationData.setText(mWeather.getStationId());
             observationData.setText(mWeather.getObsevationTime());
             weatherData.setText(mWeather.getWeather());
             temperatureData.setText(mWeather.getTemperature());
             windData.setText(mWeather.getWind());

另外,您可以創建一種方法,在其中可以傳遞天氣對象並在其中傳遞文本視圖的值,而不是在onPostExecute()中進行設置

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM