Java Android Program to Parse Xml Using Dom Parser

«
»
Here is source code of the Program demonstrate Parsing Xml using Dom parser in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

In this example we are going to parse an Xml that we receive from the internet particularly from http://developer.yahoo.com/yql/console/ from here go to the bottom right corner in DATA TABLES and select Show Community Table and scroll dowm to yahoo and click on yahoo.finance.quote in the console that appears and type the following sql statement – select * from yahoo.finance.quote where symbol in (“MSFT”) , and uncheck Diagnostics and click on test , now u will get the following shown output –

yahoo

advertisement

Now the Xml that appears in the console we actually have to download and parse in our code so that we can have our activity show us the live stocks .

Below is the Xml file that appears in the Console –

<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
    yahoo:count="1" yahoo:created="2013-07-18T17:45:46Z" yahoo:lang="en-US">
    <results>
        <quote symbol="MSFT">
            <AverageDailyVolume>49993000</AverageDailyVolume>
            <Change>-0.366</Change>
            <DaysLow>35.34</DaysLow>
            <DaysHigh>35.89</DaysHigh>
            <YearLow>26.26</YearLow>
            <YearHigh>36.43</YearHigh>
            <MarketCapitalization>295.4B</MarketCapitalization>
            <LastTradePriceOnly>35.374</LastTradePriceOnly>
            <DaysRange>35.34 - 35.89</DaysRange>
            <Name>Microsoft Corpora</Name>
            <Symbol>MSFT</Symbol>
            <Volume>22859948</Volume>
            <StockExchange>NasdaqNM</StockExchange>
        </quote>
    </results>
</query>

Main Activity

advertisement
 
package com.example.stockquote;
 
import java.util.Arrays;
 
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
 
public class MainActivity extends Activity implements OnClickListener {
 
    public final static String STOCK_SYMBOL = "com.example.stockquotes.STOCK";
 
    private SharedPreferences stockSymbolsEntered;
 
    private TableLayout stockTableScrollView;
 
    private EditText stockSymbolEditText;
    Button enterStockSymbol;
    Button deleteStocksdata;
 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        stockSymbolsEntered = getSharedPreferences("stockList", MODE_PRIVATE);
 
        stockTableScrollView = (TableLayout) findViewById(R.id.stockTableScrollView);
        stockSymbolEditText = (EditText) findViewById(R.id.stockSymbolEditText);
        enterStockSymbol = (Button) findViewById(R.id.enterStockSymbolButton);
        deleteStocksdata = (Button) findViewById(R.id.deleteStocksButton);
 
        enterStockSymbol.setOnClickListener(this);
        deleteStocksdata.setOnClickListener(this);
 
        updateSavedStockList(null);
    }
 
    private void updateSavedStockList(String newStockSymbol) {
 
        String[] stocks = stockSymbolsEntered.getAll().keySet()
                .toArray(new String[0]);
        Arrays.sort(stocks, String.CASE_INSENSITIVE_ORDER);
 
        if (newStockSymbol != null) {
            insertStockInScrollView(newStockSymbol,
                    Arrays.binarySearch(stocks, newStockSymbol));
 
        } else {
            for (int i = 0; i < stocks.length; ++i) {
 
                insertStockInScrollView(stocks[i], i);
 
            }
 
        }
 
    }
 
    private void saveStockSymbol(String newstock) {
        String isTheStockNew = stockSymbolsEntered.getString(newstock, null);
 
        SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
        preferencesEditor.putString(newstock, newstock);
        preferencesEditor.apply();
 
        if (isTheStockNew == null) {
            updateSavedStockList(newstock);
        }
 
    }
 
    private void insertStockInScrollView(String stock, int arrayIndex) {
 
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View newStockRow = inflater.inflate(R.layout.stock_quote_row, null);
 
        TextView newStockTextView = (TextView) newStockRow
                .findViewById(R.id.stockSymbolTextView);
 
        newStockTextView.setText(stock);
 
        Button stockQuoteButton = (Button) newStockRow
                .findViewById(R.id.stockQuoteButton);
        stockQuoteButton.setOnClickListener(getStockActivityListener);
 
        Button quoteFromWebButton = (Button) newStockRow
                .findViewById(R.id.quoteFromWebButton);
        quoteFromWebButton.setOnClickListener(getStockFromWebsiteListener);
 
        stockTableScrollView.addView(newStockRow, arrayIndex);
 
    }
 
    private void deleteAllStocks() {
        stockTableScrollView.removeAllViews();
    }
 
    public OnClickListener getStockFromWebsiteListener = new OnClickListener() {
 
        public void onClick(View v) {
 
            TableRow tableRow = (TableRow) v.getParent();
            TextView stockTextView = (TextView) tableRow
                    .findViewById(R.id.stockSymbolTextView);
            String stockSymbol = stockTextView.getText().toString();
            String stockURL = getString(R.string.yahoo_stock_url) + stockSymbol;
 
            Intent getStockWebPage = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(stockURL));
 
            startActivity(getStockWebPage);
 
        }
 
    };
 
    public OnClickListener getStockActivityListener = new OnClickListener() {
 
        public void onClick(View v) {
 
            TableRow tableRow = (TableRow) v.getParent();
            TextView stockTextView = (TextView) tableRow
                    .findViewById(R.id.stockSymbolTextView);
            String stockSymbol = stockTextView.getText().toString();
            Intent intent = new Intent(MainActivity.this,
                    StockInfoActivity.class);
 
            intent.putExtra(STOCK_SYMBOL, stockSymbol);
 
            startActivity(intent);
 
        }
 
    };
 
    @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 void onClick(View arg0) {
        // TODO Auto-generated method stub
 
        switch (arg0.getId()) {
        case R.id.enterStockSymbolButton:
            if (stockSymbolEditText.getText().length() > 0) {
 
                saveStockSymbol(stockSymbolEditText.getText().toString());
 
                stockSymbolEditText.setText(""); // Clear EditText box
 
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(
                        stockSymbolEditText.getWindowToken(), 0);
            } else {
 
                // Create an alert dialog box
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        MainActivity.this);
 
                builder.setTitle(R.string.invalid_stock_symbol);
                builder.setMessage(R.string.missing_stock_symbol);
                AlertDialog theAlertDialog = builder.create();
                theAlertDialog.show();
 
            }
            break;
 
        case R.id.deleteStocksButton:
            deleteAllStocks();
 
            SharedPreferences.Editor preferencesEditor = stockSymbolsEntered
                    .edit();
            preferencesEditor.clear();
            preferencesEditor.apply();
 
            break;
        }
    }
}

StockInfo

 
package com.example.stockquote;
 
public class StockInfo {
 
    private String daysLow = "";
    private String daysHigh = "";
    private String yearLow = "";
    private String yearHigh = "";
    private String name = "";
    private String lastTradePriceOnly = "";
    private String change = "";
    private String daysRange = "";
 
    public String getDaysLow() {
        return daysLow;
    }
 
    public String getDaysHigh() {
        return daysHigh;
    }
 
    public String getYearLow() {
        return yearLow;
    }
 
    public String getYearHigh() {
        return yearHigh;
    }
 
    public String getName() {
        return name;
    }
 
    public String getLastTradePriceOnly() {
        return lastTradePriceOnly;
    }
 
    public String getChange() {
        return change;
    }
 
    public String getDaysRange() {
        return daysRange;
    }
 
    public StockInfo(String daysLow, String daysHigh, String yearLow,
            String yearHigh, String name, String lastTradePriceOnly,
            String change, String daysRange) {
        this.daysLow = daysLow;
        this.daysHigh = daysHigh;
        this.yearLow = yearLow;
        this.yearHigh = yearHigh;
        this.name = name;
        this.lastTradePriceOnly = lastTradePriceOnly;
        this.change = change;
        this.daysRange = daysRange;
    }
 
}

StockInfoActivity

 
package com.example.stockquote;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
 
public class StockInfoActivity extends Activity {
 
 
    private static final String TAG = "STOCKS";
 
    TextView companyNameTextView;
    TextView yearLowTextView;
    TextView yearHighTextView;
    TextView daysLowTextView;
    TextView daysHighTextView;
    TextView lastTradePriceOnlyTextView;
    TextView changeTextView;
    TextView daysRangeTextView;
 
    static final String KEY_ITEM = "quote";
    static final String KEY_NAME = "Name";
    static final String KEY_YEAR_LOW = "YearLow";
    static final String KEY_YEAR_HIGH = "YearHigh";
    static final String KEY_DAYS_LOW = "DaysLow";
    static final String KEY_DAYS_HIGH = "DaysHigh";
    static final String KEY_LAST_TRADE_PRICE = "LastTradePriceOnly";
    static final String KEY_CHANGE = "Change";
    static final String KEY_DAYS_RANGE = "DaysRange";
 
    // XML Data to Retrieve
    String name = "";
    String yearLow = "";
    String yearHigh = "";
    String daysLow = "";
    String daysHigh = "";
    String lastTradePriceOnly = "";
    String change = "";
    String daysRange = "";
 
    // Used to make the URL to call for XML data
    String yahooURLFirst = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22";
    String yahooURLSecond = "%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.activity_stock_info);
        Intent intent = getIntent();
        String stockSymbol = intent.getStringExtra(MainActivity.STOCK_SYMBOL);
        companyNameTextView = (TextView) findViewById(R.id.companyNameTextView);
        yearLowTextView = (TextView) findViewById(R.id.yearLowTextView);
        yearHighTextView = (TextView) findViewById(R.id.yearHighTextView);
        daysLowTextView = (TextView) findViewById(R.id.daysLowTextView);
        daysHighTextView = (TextView) findViewById(R.id.daysHighTextView);
        lastTradePriceOnlyTextView = (TextView) findViewById(R.id.lastTradePriceOnlyTextView);
        changeTextView = (TextView) findViewById(R.id.changeTextView);
        daysRangeTextView = (TextView) findViewById(R.id.daysRangeTextView);
 
        Log.d(TAG, "Before URL Creation " + stockSymbol);
        final String yqlURL = yahooURLFirst + stockSymbol + yahooURLSecond;
        new MyAsyncTask().execute(yqlURL);
 
    }
 
    private class MyAsyncTask extends AsyncTask<String, String, String> {
 
        protected String doInBackground(String... args) {
 
            try {
                URL url = new URL(args[0]);
                URLConnection connection;
                connection = url.openConnection();
 
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
 
                int responseCode = httpConnection.getResponseCode();
 
                if (responseCode == 200) {
 
                    InputStream in = httpConnection.getInputStream();
                    // Here goes the DOM pull parser
                    DocumentBuilderFactory dbf = DocumentBuilderFactory
                            .newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
 
                    Document dom = db.parse(in);
 
                    Element docEle = dom.getDocumentElement();
 
                    NodeList nl = docEle.getElementsByTagName("quote");
 
                    if (nl != null && nl.getLength() > 0) {
                        for (int i = 0; i < nl.getLength(); i++) {
 
                            StockInfo theStock = getStockInformation(docEle);
                            daysLow = theStock.getDaysLow();
                            daysHigh = theStock.getDaysHigh();
                            yearLow = theStock.getYearLow();
                            yearHigh = theStock.getYearHigh();
                            name = theStock.getName();
                            lastTradePriceOnly = theStock
                                    .getLastTradePriceOnly();
                            change = theStock.getChange();
                            daysRange = theStock.getDaysRange();
 
                            // Outputs information for tracking reasons only
                            Log.d(TAG, "Stock Name " + name);
                            Log.d(TAG, "Stock Year High " + yearHigh);
                            Log.d(TAG, "Stock Year Low " + yearLow);
                            Log.d(TAG, "Stock Days High " + daysHigh);
                            Log.d(TAG, "Stock Days Low " + daysLow);
 
                        }
                    }
                }
            } catch (MalformedURLException e) {
                Log.d(TAG, "MalformedURLException", e);
            } catch (IOException e) {
                Log.d(TAG, "IOException", e);
            } catch (ParserConfigurationException e) {
                Log.d(TAG, "Parser Configuration Exception", e);
            } catch (SAXException e) {
                Log.d(TAG, "SAX Exception", e);
            } finally {
            }
 
            return null;
        }
 
        protected void onPostExecute(String result) {
 
            companyNameTextView.setText(name);
            yearLowTextView.setText("Year Low: " + yearLow);
            yearHighTextView.setText("Year High: " + yearHigh);
            daysLowTextView.setText("Days Low: " + daysLow);
            daysHighTextView.setText("Days High: " + daysHigh);
            lastTradePriceOnlyTextView.setText("Last Price: "
                    + lastTradePriceOnly);
            changeTextView.setText("Change: " + change);
            daysRangeTextView.setText("Daily Price Range: " + daysRange);
 
        }
 
    }
 
    private StockInfo getStockInformation(Element entry) {
 
        String stockName = getTextValue(entry, "Name");
        String stockYearLow = getTextValue(entry, "YearLow");
        String stockYearHigh = getTextValue(entry, "YearHigh");
        String stockDaysLow = getTextValue(entry, "DaysLow");
        String stockDaysHigh = getTextValue(entry, "DaysHigh");
        String stocklastTradePriceOnlyTextView = getTextValue(entry,
                "LastTradePriceOnly");
        String stockChange = getTextValue(entry, "Change");
        String stockDaysRange = getTextValue(entry, "DaysRange");
 
        StockInfo theStock = new StockInfo(stockDaysLow, stockDaysHigh,
                stockYearLow, stockYearHigh, stockName,
                stocklastTradePriceOnlyTextView, stockChange, stockDaysRange);
 
        return theStock;
 
    }
 
    private String getTextValue(Element entry, String tagName) {
 
        String tagValueToReturn = null;
 
        NodeList nl = entry.getElementsByTagName(tagName);
 
        if (nl != null && nl.getLength() > 0) {
 
            Element element = (Element) nl.item(0);
 
            tagValueToReturn = element.getFirstChild().getNodeValue();
        }
 
        return tagValueToReturn;
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.stock_info, menu);
        return true;
    }
 
}

Main.xml

advertisement
 
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/tableLayout"
    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"
    android:stretchColumns="yes"
    tools:context=".MainActivity" >
 
    <TableRow
        android:id="@+id/tableRow0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
 
        <TextView
            android:id="@+id/enterSymbolTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/stock_symbol" />
        <EditText
            android:id="@+id/stockSymbolEditText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="text"
            android:layout_weight="1" >
 
            <requestFocus />
        </EditText>
 
        <Button
            android:id="@+id/enterStockSymbolButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/enter_stock_symbol" />
 
    </TableRow>
 
    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/egg_shell" >
        <TextView
            android:id="@+id/stockSymbolTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:gravity="center_horizontal"
            android:padding="5dp"
            android:text="@string/stock_symbol_list"
            android:textColor="@color/black"
            android:textSize="@dimen/stock_list_text_size" />
 
    </TableRow>
 
    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@color/egg_shell" >
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:padding="5dp" >
 
            <TableLayout
                android:id="@+id/stockTableScrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:stretchColumns="yes" >
            </TableLayout>
        </ScrollView>
 
    </TableRow>
 
    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
 
        <Button
            android:id="@+id/deleteStocksButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/delete_all_symbols"
            android:layout_span="2" 
            android:layout_weight="1" />
 
    </TableRow>
 
</TableLayout>

Activity_stock.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
 
        <TextView
            android:id="@+id/companyNameTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="@dimen/activity_horizontal_margin"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />
 
    </TableRow>
 
    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
 
        <TextView
            android:id="@+id/yearLowTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="@dimen/activity_horizontal_margin"
            android:text="@string/stock_year_low" 
            android:layout_weight="1" />
 
        <TextView
            android:id="@+id/yearHighTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/stock_year_high" 
            android:layout_weight="1" />
 
    </TableRow>
 
    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_horizontal_margin" >
 
        <TextView
            android:id="@+id/daysLowTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/stock_days_low"
            android:layout_weight="1" />
 
        <TextView
            android:id="@+id/daysHighTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/stock_days_high"
            android:layout_weight="1" />
 
    </TableRow>
 
    <TableRow
        android:id="@+id/tableRow4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_horizontal_margin" >
 
        <TextView
            android:id="@+id/lastTradePriceOnlyTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/last_trade_price_only"
            android:layout_weight="1" />
 
        <TextView
            android:id="@+id/changeTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/change"
            android:layout_weight="1" />
 
    </TableRow>
 
    <TableRow
        android:id="@+id/tableRow5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_horizontal_margin" >
 
        <TextView
            android:id="@+id/daysRangeTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/days_range" />
 
    </TableRow>
 
</TableLayout>

Stock_quote

advertisement
 
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/stockQuoteRow"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:padding="@dimen/activity_horizontal_margin" >
 
    <TextView
        android:id="@+id/stockSymbolTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_span="2"
        android:layout_weight="1"
        android:textColor="@color/black"
        android:textIsSelectable="true" />
 
    <Button
        android:id="@+id/stockQuoteButton"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/get_stock_quote" />
 
    <Button
        android:id="@+id/quoteFromWebButton"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/go_to_website" />
 
</TableRow>

Note:
Remember to add uses Interner Permission in your AndroidManifest.xml

dom_parser1

dom_parser2

dom_parser3

dom_parser4

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

If you wish to look at all Tutorials, go to Java Android Tutorials.

Participate in the Sanfoundry Certification
contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn