Android XML Parsing using DOM Parser

 Generally, XML (Extensible Mark-up Language) is one of the commonly used data exchange formats to interchange the data between servers.

 

In android, we have three types of XML parsers to parse the XML data to get the required information in android applications, those are

 

Now we will see how to use DOM parser in android applications to parse the XML document to get the required information.

Android DOM Parser

In android, DOM parser will use an object-based approach to create and parse the XML files in android applications.

 

Generally, the DOM parser will load the XML file into memory to parse the XML document, due to that it will consume more memory and it will parse the XML document from starting node to end node.

 

Basically, the XML file will contain a following 4 main components.

 

ComponentDescription
PrologGenerally, the XML file will start with a prolog. The first line that contains the information about a file is prolog.
EventsGenerally, the XML file will contain many events that include document start and end, tag start and end, etc.
TextIt's a simple text in XML tag elements.
AttributesAttributes are the additional properties of a tag such as value etc. present within the tag.

Following is the sample structure of the XML file with user details in android applications.

 

<?xml version="1.0encoding="utf-8"?>

<users>

<user>

<name>Suresh Dasari</name>

<designation>Team Leader</designation>

<loation>Hyderabad</loation>

</user>

<user>

<name>Rohini Alavala</name>

<designation>Agricultural Officer</designation>

<loation>Guntur</loation>

</user>

</users>

If you observe above xml structure it contains a different type of components such as prolog, events, text and attributes.

Android DOM XML Parsing

To read and parse the XML data using DOM parser in android, we need to create an instance of DocumentBuilderFactoryDocumentBuilder and Document objects in android applications.

 

Following is the code snippet of reading and parsing the XML data using DOM parser in android applications with DocumentBuilderFactoryDocumentBuilder, and Document objects to get the required information from XML objects.

 

InputStream istream = getAssets().open("userdetails.xml");
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(istream);
NodeList nList = doc.getElementsByTagName(
"user");
for(int i =0;i<nList.getLength();i++){
    
if(nList.item(0).getNodeType() == Node.ELEMENT_NODE){
        HashMap<String,String> user = 
new HashMap<>();
        Element elm = (Element)nList.item(i);
        user.put(
"name", getNodeValue("name",elm));
        user.put(
"designation", getNodeValue("designation",elm));
        user.put(
"location", getNodeValue("location",elm));
        userList.add(user);
    }
}

If you observe above code snippet, we used DocumentBuilderFactoryDocumentBuilder and Document objects to parse the XML data to get required information.

 

Now we will see how to parse XML data using DOM parser and bind the parsed XML data to Listview in android application with examples.

Android XML Parsing with DOM Parser Example

Following is the example of parsing the XML data and get the required information from it using DOM parser in android applications.

 

Create a new android application using android studio and give names as XMLParserExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Once we are done with creation of an application, create an assets folder under /src/main folder and add a new resource file (userdetails.xml), for that right click on assets folder à add new Android resource file à Give name as userdetails.xml like as shown below.

 

Android DOM Parser Example Add Assets Folder

 

Now open userdetails.xml file and write the code like as shown below.

userdetails.xml

<?xml version="1.0encoding="utf-8"?>

<users>

<user>

<name>Suresh Dasari</name>

<designation>Team Leader</designation>

<loation>Hyderabad</loation>

</user>

<user>

<name>Rohini Alavala</name>

<designation>Agricultural Officer</designation>

<loation>Guntur</loation>

</user>

<user>

<name>Trishika Dasari</name>

<designation>Charted Accountant</designation>

<loation>Guntur</loation>

</user>

</users>

Now open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
android:layout_width="fill_parent"
    
android:layout_height="fill_parent"
    
android:orientation="vertical" >
    <
ListView
        
android:id="@+id/user_list"
        
android:layout_width="fill_parent"
        
android:layout_height="wrap_content"
        
android:dividerHeight="1dp" />
</
LinearLayout>

After that create an another layout file (list_row.xml) in /res/layout folder to show the data in listview, for that right click on layout folder à add new Layout resource file à Give name as list_row.xml and write the code like as shown below.

list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
android:layout_width="fill_parent"
    
android:layout_height="wrap_content"
    
android:orientation="horizontal"
    
android:padding="5dip" >
    <
TextView
        
android:id="@+id/name"
        
android:layout_width="wrap_content"
        
android:layout_height="wrap_content"
        
android:textStyle="bold"
        
android:textSize="17dp" />
    <
TextView
        
android:id="@+id/designation"
        
android:layout_width="wrap_content"
        
android:layout_height="wrap_content"
        
android:layout_below="@id/name"
        
android:layout_marginTop="7dp"
        
android:textColor="#343434"
        
android:textSize="14dp" />
    <
TextView
        
android:id="@+id/location"
        
android:layout_width="wrap_content"
        
android:layout_height="wrap_content"
        
android:layout_alignBaseline="@+id/designation"
        
android:layout_alignBottom="@+id/designation"
        
android:layout_alignParentRight="true"
        
android:textColor="#343434"
        
android:textSize="14dp" />
</
RelativeLayout>

Now open your main activity file MainActivity.java from \java\com.tutlane.xmlparserexample path and write the code like as shown below

MainActivity.java

package com.tutlane.xmlparserexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class MainActivity extends AppCompatActivity {
    
@Override
    
protected void onCreate(Bundle savedInstanceState) {
        
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        
try{
            ArrayList<HashMap<String, String>> userList = 
new ArrayList<>();
            ListView lv = (ListView) findViewById(R.id.
user_list);
            InputStream istream = getAssets().open(
"userdetails.xml");
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(istream);
            NodeList nList = doc.getElementsByTagName(
"user");
            
for(int i =0;i<nList.getLength();i++){
                
if(nList.item(0).getNodeType() == Node.ELEMENT_NODE){
                    HashMap<String,String> user = 
new HashMap<>();
                    Element elm = (Element)nList.item(i);
                    user.put(
"name", getNodeValue("name",elm));
                    user.put(
"designation", getNodeValue("designation",elm));
                    user.put(
"location", getNodeValue("location",elm));
                    userList.add(user);
                }
            }
            ListAdapter adapter = 
new SimpleAdapter(MainActivity.this, userList, R.layout.list_row,new String[]{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location});
            lv.setAdapter(adapter);
        }
        
catch (IOException e) {
            e.printStackTrace();
        } 
catch (ParserConfigurationException e) {
            e.printStackTrace();
        } 
catch (SAXException e) {
            e.printStackTrace();
        }
    }
    
protected String getNodeValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag);
        Node node = nodeList.item(
0);
        
if(node!=null){
            
if(node.hasChildNodes()){
                Node child = node.getFirstChild();
                
while (child!=null){
                    
if(child.getNodeType() == Node.TEXT_NODE){
                        
return  child.getNodeValue();
                    }
                }
            }
        }
        
return "";
    }
}

If you observe above code, we used DocumentBuilderFactoryDocumentBuilder and Document objects to get the required information from XML files.

Output of Android XML Parsing with DOM Parser Example

When we run above program in android studio we will get the result as shown below.

 

Android XML Parsing using DOM Parser Example Result

 

This is how we can parse the XML data using DOM parser in android applications to get the required information.

Android Send Email with Examples

 In android, we can easily send an email from our android application using existing email clients such as GMAIL, Outlook, etc. instead of building an email client from scratch.

 

Generally, the Intent object in android with proper action (ACTION_SEND) and data will help us to launch the available email clients to send an email in our application.

 

In android, Intent is a messaging object which is used to request an action from another app component such as activitiesservicesbroadcast receivers, and content providers. To know more about an Intent object in android check this Android Intents with Examples.

 

To send an email using the Intent object in android application, we need to write the code as shown below.

 

Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.
EXTRA_EMAILnew String[]{"support@tutlane.com"});
it.putExtra(Intent.
EXTRA_SUBJECT"Welcome to Tutlane");
it.putExtra(Intent.
EXTRA_TEXT"Hi Guest, Welcome to Tutlane Tutorial Site");
it.setType(
"message/rfc822");

If you observe above code we used multiple components to send email, those are

 

it - Our local implicit intent

 

ACTION_SEND - It’s an activity action that specifies that we are sending some data.

 

putExtra - we use this putExtra() method to add extra information to our Intent. Here we can add the following things.

 

  • EXTRA_EMAIL - It’s an array of email addresses
  • EXTRA_SUBJECT - The subject of the email that we want to send
  • EXTRA_TEXT - The body of the email 

The android Intent object is having different options such as EXTRA_CC, EXTRA_BCC, EXTRA_HTML_TEXT, EXTRA_STREAM, etc. to add different options for an email client.

 

setType - We use this property to set the MIME type of data that we want to send. Here we used “message/rfc822” and other MIME types are “text/plain” and “image/jpg”.

 

Now we will see how to send an email in android application using an Intent object with examples.

Android Send Email Example

Following is the example of sending an email with existing email clients using Intent in the android application.

 

Create a new android application using android studio and give names as SendMailExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
android:layout_width="match_parent"
    
android:layout_height="match_parent"
    
android:paddingLeft="20dp"
    
android:paddingRight="20dp"
    
android:orientation="vertical" >
    <
EditText
        
android:id="@+id/txtTo"
        
android:layout_width="match_parent"
        
android:layout_height="wrap_content"
        
android:hint="To"/>
    <
EditText
        
android:id="@+id/txtSub"
        
android:layout_width="match_parent"
        
android:layout_height="wrap_content"
        
android:hint="Subject"/>
    <
EditText
        
android:id="@+id/txtMsg"
        
android:layout_width="match_parent"
        
android:layout_height="0dp"
        
android:layout_weight="1"
        
android:gravity="top"
        
android:hint="Message"/>
    <
Button
        
android:layout_width="100dp"
        
android:layout_height="wrap_content"
        
android:layout_gravity="right"
        
android:text="Send"
        
android:id="@+id/btnSend"/>
</
LinearLayout>

Now open our main activity file MainActivity.java from \src\main\java\com.tutlane.sendmailexample path and write the code like as shown below

MainActivity.java

package com.tutlane.sendmailexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    
private EditText eTo;
    
private EditText eSubject;
    
private EditText eMsg;
    
private Button btn;
    
@Override
    
protected void onCreate(Bundle savedInstanceState) {
        
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        
eTo = (EditText)findViewById(R.id.txtTo);
        
eSubject = (EditText)findViewById(R.id.txtSub);
        
eMsg = (EditText)findViewById(R.id.txtMsg);
        
btn = (Button)findViewById(R.id.btnSend);
        
btn.setOnClickListener(new View.OnClickListener() {
            
@Override
            
public void onClick(View v) {
                Intent it = 
new Intent(Intent.ACTION_SEND);
                it.putExtra(Intent.
EXTRA_EMAILnew String[]{eTo.getText().toString()});
                it.putExtra(Intent.
EXTRA_SUBJECT,eSubject.getText().toString());
                it.putExtra(Intent.
EXTRA_TEXT,eMsg.getText());
                it.setType(
"message/rfc822");
                startActivity(Intent.createChooser(it,
"Choose Mail App"));
            }
        });
    }
}

If you observe above code we used multiple components to send email, those are

 

it - Our local implicit intent

 

ACTION_SEND - It’s an activity action that specifies that we are sending some data.

 

putExtra - we use this putExtra() method to add extra information to our Intent. Here we can add the following things.

 

  • EXTRA_EMAIL - It’s an array of email addresses
  • EXTRA_SUBJECT - The subject of the email that we want to send
  • EXTRA_TEXT - The body of the email 

setType - We use this property to set the MIME type of data that we want to send. Here we used “message/rfc822” and other MIME types are “text/plain” and “image/jpg”. 

 

We need to add MIME type in our android manifest file for that open android manifest file (AndroidManifest.xml) and write the code like as shown below

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tutlane.sendmailexample">
    <
application
        
android:allowBackup="true"
        
android:icon="@mipmap/ic_launcher"
        
android:label="@string/app_name"
        
android:roundIcon="@mipmap/ic_launcher_round"
        
android:supportsRtl="true"
        
android:theme="@style/AppTheme">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />
                <
category android:name="android.intent.category.LAUNCHER" />
                <
action android:name="android.intent.action.SEND"/>
                <
category android:name="android.intent.category.DEFAULT"/>
                <
data android:mimeType="message/rfc822"/>
            </
intent-filter>
        </
activity>
    </
application>
</
manifest>

If you observe above AndroidManifest.xml file we added following extra fields of Intent filters.

 

action - we use this property to define that the activity can perform SEND action.

 

category - we included the DEFAULT category for this activity to be able to receive implicit intents.

 

data - the type of data the activity can send.

Output of Android Send Email Example

When we run above program in the android studio we will get the result like as shown below.

 

Android Send Email Example Result

 

Once we enter all the details and click on Send button, it will display a dialog with the apps which are capable of sending an email. By selecting the required email client we can send an email without building our own email client like as shown below.

 

Android Select Required Email Client to Send Email Example Result

 

This is how we can send emails using intents in android applications based on our requirements. 

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...