Parsing XML File stored in raw folder using XPath

Following code demonstrates how to parse XML file stored in res/raw folder using XPath

Save following file in res – raw folder as data.xml

<?xml version="1.0" encoding="UTF-8"?>
<sample>
    <info>
        <title>Using XPath to parse XML</title>
        <author>Pete Houston</author>
    <list>
        <person id="1">
            <name>abc</name>
            <age>22</age>
        </person>
 
        <person id="2">
            <name>def</name>
            <age>27</age>
        </person>
 
        <person id="3">
            <name>ghi</name>
            <age>22</age>
        </person>
    </list>
    </info>
</sample>

XMLParse.java

package com.example.xmlparsing;

import java.util.ArrayList;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MainActivity extends ListActivity {

	ArrayList<String> mPeople = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            parseData();
        } catch(Exception ex) {
            Toast.makeText(this, "Exception: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        }
 
        // pass adapter w/ data queried through XPath to ListView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPeople);
        setListAdapter(adapter);
    }
    private void parseData() throws Exception {
        // create an InputSource object from /res/raw
        InputSource inputSrc = new InputSource(getResources().openRawResource(R.raw.data));
        // query XPath instance, this is the parser
        XPath xpath = XPathFactory.newInstance().newXPath();
        // specify the xpath expression
        String expression = "//name";
        // list of nodes queried
        NodeList nodes = (NodeList)xpath.evaluate(expression, inputSrc, XPathConstants.NODESET);
 
        //Toast.makeText(this, "count: " + String.valueOf(nodes.getLength()),Toast.LENGTH_SHORT).show();
        // if node found
        if(nodes != null && nodes.getLength() > 0) {
            mPeople.clear();
            int len = nodes.getLength();
            for(int i = 0; i < len; ++i) {
                // query value
                Node node = nodes.item(i);
                mPeople.add(node.getTextContent());
            }
        }
    }
    
}

XMLParsing1

Advertisements

Testing Network ( Wifi and Mobile) Connection

Following code tests whether network is available and/or connected?

package com.example.networkapidemo5b;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		try
		{
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			String s = "Available : " + ni.isAvailable() + "Connected : " + ni.isConnected();
			Toast.makeText(getApplicationContext(), s, 100).show();

                        ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			s = "Available : " + ni.isAvailable() + "Connected : " + ni.isConnected();
			Toast.makeText(getApplicationContext(), s, 100).show();

		}	
		catch(Exception e)
		{
			Toast.makeText(getApplicationContext(), e.getMessage(), 50).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

File Read – Write Example

Following Code demonstrates how to read data from file and write data to file.

layout – activity_main.xml

<RelativeLayout 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"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="68dp"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="45dp"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_centerVertical="true"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="58dp"
        android:text="TextView" />

</RelativeLayout>

FileReadWrite.java

package com.example.filereadwrite5a;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button bwrite = (Button)findViewById(R.id.button1);
		Button bread = (Button)findViewById(R.id.button2);
		final EditText ed = (EditText)findViewById(R.id.editText1);
		final TextView tv = (TextView)findViewById(R.id.textView1);
//		
//		
		bwrite.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				File f = getCacheDir();
				File newfile = new File(f,"mca5.abc");
				try
				{
				newfile.createNewFile();
				//newfile.
				FileOutputStream fos = new FileOutputStream(newfile.getAbsolutePath());
				fos.write(ed.getText().toString().getBytes());
				fos.close();
				}
				catch(Exception e)
				{}
//				File f = getFilesDir();
//				String filelist[] = f.list();
//				String s;
//				for (int i=0;i<filelist.length;i++)
//				{
//					Toast.makeText(getApplicationContext(),filelist[i], 50).show();
//				}
//				try 
//				{
//					String s = ed.getText().toString();
//					FileOutputStream fos = openFileOutput("test.txt", MODE_APPEND);
//					fos.write(s.getBytes());
//					fos.close();
//				} 
//				catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				
			}
		});
		bread.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{
					FileInputStream fis = openFileInput("mca5a.txt");
					DataInputStream dis = new DataInputStream(fis);
					String s="";
					String s1 = "";
					while ((s=dis.readLine())!=null)
					{
						s1 += s;
					}
					tv.setText(s1.toString());
				} 
				catch (Exception 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.activity_main, menu);
		return true;
	}

}