Users Online

· Guests Online: 103

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

047 Java Android Program to Parse Xml Using Xml Pull Parser

Java Android Program to Parse Xml Using Xml Pull Parser

Here is source code of the Program demonstrate Parsing Xml using Xml pull 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 

 

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>

The XML Pull Parser API is available from the following libraries:
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
It enables you to parse an XML document in a single pass. Unlike the DOM parser, the Pull Parser presents the elements of your document in a sequential series of events and tags. Your location within the document is represented by the current event. You can determine the current event by calling getEventType. Each document begins at the START_DOCUMENT event and ends at END_DOCUMENT.

To proceed through the tags, simply call next, which causes you to progress through a series of
matched (and often nested) START_TAG and END_TAG events. You can extract the name of each tag by
calling getName and extract the text between each set of tags using getNextText.

This following short example demonstrates how to use the XML Pull Parser to extract details from the points of interest list returned by the Google Places API and after that we continue our class of getting xml from yahoo web service.

 

private void processStream(InputStream inputStream) {
// Create a new XML Pull Parser.
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
// Assign a new input stream.
xpp.setInput(inputStream, null);
int eventType = xpp.getEventType();
// Continue until the end of the document is reached.
while (eventType != XmlPullParser.END_DOCUMENT) {
// Check for a start tag of the results tag.
if (eventType == XmlPullParser.START_TAG &&
xpp.getName().equals(“result”)) {
eventType = xpp.next();
String name = “”;
// Process each result within the result tag.
while (!(eventType == XmlPullParser.END_TAG &&
xpp.getName().equals(“result”))) {
// Check for the name tag within the results tag.
if (eventType == XmlPullParser.START_TAG &&
xpp.getName().equals(“name”))
// Extract the POI name.
name = xpp.nextText();
 
// Move on to the next tag.
eventType = xpp.next();
}
// Do something with each POI name.
}
// Move on to the next result tag.
eventType = xpp.next();
}
} catch (XmlPullParserException e) {
Log.d(“PULLPARSER”, “XML Pull Parser Exception”, e);
} catch (IOException e) {
Log.d(“PULLPARSER”, “IO Exception”, e);
}
}

Main Activity

 
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;
    }
 
}

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.80 seconds
10,830,216 unique visits