Monday, January 21, 2019

Working with Android Background Services


Working with Android Background Services


Networking


In all Android applications there is a main thread which is responsible for handling the UI, receiving lifecycle events and user interactions. If there is too much task load on the main thread, it will slow down the application leading to unsatisfying user experience. In order to maintain the performance levels, long running task such as accessing the disk, decoding a bitmap image, network requests are done in the background on a separate thread. In general, any task that requires more than a few milliseconds to complete is delegated to the background thread.

Networking plays a very important role in the smooth functioning of all Android applications. This is so because applications do not work in isolation, they have to connect to online services to retrieve information / data or to perform networking functions.

Fundamentals of Networking
Android applications need network connectivity to download content, give users control over the applications data usage, in minimizing network traffic and consumption of data.

Following are the fundamentals of networking:

Connecting to the Network - Applications may not be always connected to the network, so the foremost step is to check the connectivity. The applications should have the following permissions in their manifest/AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

The INTERNET permission is required by all applications to access internet connection.
The ACCESS_NETWORK_STATE is required to check the network of the device.

Let's take a look at the following code for checking WiFi and data connections:

Ø  To Check if WiFi or 3G/4G is Enabled by the User :
Wifi - ACCESS_WIFI_STATE permission must be added to AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
The checking code is very simple. In activity, WifiManager has a very handy method.
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
boolean wifiEnabled = wifiManager.isWifiEnabled();

Ø  To Check if 3G/4G is Enabled by the User :
This is a bit more complicated than the WiFi, the ACCESS_NETWORK_STATE  permission has to be granted.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then we get NetworkInfo from the ConnectivityManager.
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mobileInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
The code can return any of the following six types of NetworkInfo state:
·         Connected
·         Connecting
·         Disconnected
·         Disconnecting
·         Suspended
·         Unknown

Ø  To Check if WiFi or 3G/4G is Connected
WiFi or 3G/4G may not be always be  connected even if the user has enables them. Checking the connectivity of the device is always advisable doing network tasks.
·         WiFi
NetworkInfo wifiInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean wifiConnected = wifiInfo.getState() == NetworkInfo.State.CONNECTED;
·         3G/4G
NetworkInfo mobileInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean mobileConnected = mobileInfo.getState() == NetworkInfo.State.CONNECTED;

Design Secure Network Communication - Network functionality of Android applications requires network security practices to ensure that data within the application stays safe when its being transmitted over a network.

The following measures can minimize these risks:
·         Minimize the amount of personal user data.
·         Directing all network traffic from the application to Secure Sockets Layers ( SSL ), which is used for secure communication between client and server.
·         Creating a network security configuration for the Android application, this feature allows the application to customize their network security settings without altering the main application code.
Choose an HTTP Client -  Almost all network connected Android applications use HTTP to exchange data. Android platform provides HttpsURLConnection client, which supports streaming uploads and downloads, connection pooling, Transport Layer Security (for emails, internet faxing and other types of data transfer), Internet Protocol Version6 ( IPv6 ) and connection pooling.

Introducing Network Operations on a Separate Thread - By default the network operations are not performed on the main thread but on a separate thread to avoid unresponsive or slow user interface.

Managing Network Usage - Applications that perform a lot of network operation also provide flexible user settings, which allows the user to control the applications data habits. The user can control how often the application syncs data, using data on roaming and weather to upload / download only on Wi-Fi. These controls help in managing the amount of data used by the application.

Optimize Data Network Usage - It is always good for all applications to check if the user has enabled data saver option in order to control the foreground and background data usage. The data saver preferences can be of the following types:
·         RESTRICT_BACKGROUND_STATUS_DISABLED - This shows that the data saver has been disabled.
·         RESTRICT_BACKGROUND_STATUS_ENABLED - This show that the user has enabled the data save for any particular application.
·         RESTRICT_BACKGROUND_STATUS_WHITELISTED - This shows that the data saver for any particular application has been enabled, but the application is whitelisted. Whitelisted applications are those applications that need to use data in the background.

Parse XML Data - Extensible Markup Language ( XML ) enables  encoding of  document in a machine - readable form by providing a set of rules for encoding. XML is the most popular format for sharing information on the internet. Web pages and websites that regularly update their content also provide an XML feed, so that external programs can keep track of the changes in the content. Uploading and parsing XML data is a standard task for all network connected applications.


Web View

Web view is a view that enables display of web pages inside an application. The application should be network connected. It is basically a WebView class which is an extention of  the main View class of Android. It just simply allows the display of web pages as a part of the activity and does not have the features of web browser.
By Default, it does not provide browser - like functions, browser- like widgets, does not support JavaScript or web page errors. It just displays a web page with no interactive element for the user.
Any activity which has to load web pages in WebView must have INTERNET permission enabled in the Android Manifest file. It is done by using the following syntax :
<uses-permission android:name="android.permission.INTERNET" />
 This permission must be a child of the <manifest> element.
Adding a WebView to an Application
It's very simple to add WebView to an application. To start, include <WebView> element in the xml layout file. It is done by using the following syntax:
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/webview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
/>
Next,in order to use the WebView, a reference of this view has to be in the Java file. To get this reference, create an object of the WebView class.

The syntax for creating an object of the WebView class is −
WebView browser = (WebView) findViewById(R.id.webview);

Next, to load a web url into the WebView, loadUrl(String url) method of the WebView class has to be called, stating the required url.

 The syntax for calling LoadUrl method is:
browser.loadUrl("http://www.example.com");

Apart from loading the web Url, a few more controls can be added to the WebView by calling the following methods defined in the WebView class.
Method
Description
canGoBack ( )
This method specifies that the WebView has a back history item
canGoForward ( )
This method specifies that the WebView has a forward history item.
clearHistory ( )
This method will clear / delete the forward and backward history of the WebView.
Destroy ( )
This method destroys the internal state of WebView.
findAllAsync ( String find )
This method will find all instances of string and also highlight them.
getProgress ( )
This method will return the progress of the current page.
getTitle ( )
This method will get the title of the current page.
getUrl ( )
This method will get the url of the current page.

Async Task

In all Android applications, there is always one main thread that performs the most important tasks in the application like managing user interaction, launching activities and drawing pixels on the screen. This main thread is called the UI Thread or Main Thread. Since this thread executes the most crucial tasks of an application, it should never be kept blocked or loaded with other long running activities.
In order to keep the main thread free to perform the crucial tasks of an application, Android provides Android SDK and some tools for managing threads. Async Task is one such tool designed to offload some work off the main thread. To give a smooth user experience in all Android applications, it is best practice to make all slow running tasks or operations run asynchronously. Examples of some slow running tasks are:
·         Database operation
·         Accessing resources like MP3, Images or JSON from the internet
·         Complex logic that take long time
·         Webservice calls

What is Async Task?
AsyncTask is basically an abstract Android class which helps an Android application to handle its main thread in an easy and efficient manner. It is a mechanism for executing tasks in a background thread without making any changes to the main thread. The AsyncTask class executes long running tasks / background operations of the application and displays the result on the main thread.

When to use AsyncTask?
Let's consider a simple Android application which will download MP3 files from the internet once the application is launched. The following explanation gives a brief of the series of operations that will take place on the launch of the application.

While the MP3 is awaited from the server, the entire application becomes unresponsive as the main thread is waiting for the download task to complete. To overcome these issues Android created a dedicated class  called the 'Async Task' to perform such operations in the background asynchronously.

The 4 Background Steps of AsyncTask
 When an AsyncTask is started from the main thread, it goes through the four steps, as shown in the diagram below:

Figure : 4 Steps of AsyncTask

·         onPreExecute : This method is used to set up the task like showing the initial progress bar in the UI thread.
·         doInBackground : This method is used to perform the actual task. This step is executed in the background to handle the long running task.
·         onProgressUpdate : This step updated the current progress status of the task. This method is invoked by calling the publishProgress method from doInBackground method.
·         onPreExecute : This method is invoked after the process of doInBackground method is complete. The result of doInBackground is sent to this method, which is then displayed on the main UI thread and also stops the AsyncTask.

AsyncTask Generic Types
 An Asynctask accepts the following three generic types to inform that a background task is being done :
·         Params - These are parameters sent the task upon execution. These are passed to the execute ( ) method.
·         Progress - This type tracks the progress of the task running in the background and is used within the task.
·         Result - This is the type returned by doInBackground.

Basic Rules of AsyncTask
The following rules must be followed for Asynctask:
·         The Asynctask class has to be loaded on the UI thread.
·         The task instance must also be created on the UI thread.
·         The execute ( Params.... ) method has to be invoked on the UI thread.
·         The onPreExecute ( ), onPostExecute ( Result ), doInBackground ( Params... ), onProgressUpdate ( Progress... ) methods should never be called manually.
·         The task can be executed only one single time.

Cancelling a Task
An AsyncTask can be cancelled at anytime by calling the cancel ( boolean ) method.


Downloading Files

Downloading a file and saving the file is the most common task, the following sample code will help you in understanding how to download Doc file from URL or Server in Android.

Downloading Doc File from URL in Android Code Example
Step 1: Add a simple button in layout file for downloading Doc File from the server.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.nkdroid.doc.download.example.MainActivity">

    <Button
        android:id="@+id/btnDownload"
        android:layout_centerInParent="true"
        android:background="@color/colorPrimary"
        android:padding="16dp"
        android:textColor="#ffffff"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DOWNLOAD DOC" />
</RelativeLayout>


Step 2: This class contains the main logic of downloading a Doc file from URL
MainActivity.java
package com.nkdroid.doc.download.example;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button btnDownload;
    String URL="http://www.iiswc.org/iiswc2009/sample.doc";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnDownload= (Button) findViewById(R.id.btnDownload);

        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new DownloadTask(MainActivity.this,URL);
            }
        });
    }
}

Step 3: Add required files, this class is for checking SD card
CheckForSDCard.java
package com.nkdroid.doc.download.example;

import android.os.Environment;

public class CheckForSDCard {
    //Check If SD Card is present or not method
    public boolean isSDCardPresent() {
        if (Environment.getExternalStorageState().equals(

                Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }
}

Step 4: This class is for the downloading operation
DownloadTask.java
package com.nkdroid.doc.download.example;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Aptech on 29/04/18.
 */
public class DownloadTask {

    private static final String TAG = "Download Task";
    private Context context;

    private String downloadUrl = "", downloadFileName = "";
    private ProgressDialog progressDialog;
    public DownloadTask(Context context, String downloadUrl) {
        this.context = context;

        this.downloadUrl = downloadUrl;


        downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf( '/' ),downloadUrl.length());//Create file name by picking download file name from URL
        Log.e(TAG, downloadFileName);

        //Start Downloading Task
        new DownloadingTask().execute();
    }

    private class DownloadingTask extends AsyncTask<Void, Void, Void> {

        File apkStorage = null;
        File outputFile = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog=new ProgressDialog(context);
            progressDialog.setMessage("Downloading...");
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(Void result) {
            try {
                if (outputFile != null) {
                    progressDialog.dismiss();
                    Toast.makeText(context, "Downloaded Successfully", Toast.LENGTH_SHORT).show();
                } else {

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                        }
                    }, 3000);

                    Log.e(TAG, "Download Failed");

                }
            } catch (Exception e) {
                e.printStackTrace();

                //Change button text if exception occurs

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                    }
                }, 3000);
                Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());

            }


            super.onPostExecute(result);
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                URL url = new URL(downloadUrl);//Create Download URl
                HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
                c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
                c.connect();//connect the URL Connection

                //If Connection response is not OK then show Logs
                if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
                            + " " + c.getResponseMessage());

                }


                //Get File if SD card is present
                if (new CheckForSDCard().isSDCardPresent()) {

                    apkStorage = new File(
                            Environment.getExternalStorageDirectory() + "/"
                                    + "NKDROID FILES");
                } else
                    Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();

                //If File is not present create directory
                if (!apkStorage.exists()) {
                    apkStorage.mkdir();
                    Log.e(TAG, "Directory Created.");
                }

                outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File

                //Create New File if not present
                if (!outputFile.exists()) {
                    outputFile.createNewFile();
                    Log.e(TAG, "File Created");
                }

                FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location

                InputStream is = c.getInputStream();//Get InputStream for connection

                byte[] buffer = new byte[1024];//Set buffer type
                int len1 = 0;//init length
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);//Write new file
                }

                //Close all connection after doing task
                fos.close();
                is.close();

            } catch (Exception e) {

                //Read exception if something went wrong
                e.printStackTrace();
                outputFile = null;
                Log.e(TAG, "Download Error Exception " + e.getMessage());
            }

            return null;
        }
    }
}


Step 5: AndroidManifest.xml file
AndroidManifest.xml   
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nkdroid.doc.download.example">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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" />
            </intent-filter>
        </activity>
    </application>

</manifest>
The above steps on execution will download doc files from a URL in Android.

Downloading Images

Let's see the following sample code for downloading an image from a URL address into your Android application. This code has a button and button click the Asynctask class begins to download the image from a URL address.

Step 1 : Create a new project in Eclipse File > New > Android Application Project.
Fill in the details and name the project DownloadImageTutorial.
Application Name : DownloadImageTutorial
Project Name : DownloadImageTutorial
Package Name : com.androidbegin.downloadimagetutorial
Step 2 : Open MainActivity.java and add the following code.
package com.androidbegin.downloadimagetutorial;
 import java.io.InputStream;
 import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
 public class MainActivity extends Activity {
                // Set your Image URL into a string
                String URL = "http://www.androidbegin.com/wp-content/uploads/2013/07/HD-Logo.gif";
                ImageView image;
                Button button;
                ProgressDialog mProgressDialog;
                @Override
                public void onCreate(Bundle savedInstanceState) {
                                super.onCreate(savedInstanceState);
                                // Get the layout from image.xml
                                setContentView(R.layout.activity_main);

                                // Locate the ImageView in activity_main.xml
                                image = (ImageView) findViewById(R.id.image);

                                // Locate the Button in activity_main.xml
                                button = (Button) findViewById(R.id.button);

                                // Capture button click
                                button.setOnClickListener(new OnClickListener() {
                                                public void onClick(View arg0) {

                                                                // Execute DownloadImage AsyncTask
                                                                new DownloadImage().execute(URL);
                                                }
                                });
                }

                // DownloadImage AsyncTask
                private class DownloadImage extends AsyncTask<String, Void, Bitmap> {

                                @Override
                                protected void onPreExecute() {
                                                super.onPreExecute();
                                                // Create a progressdialog
                                                mProgressDialog = new ProgressDialog(MainActivity.this);
                                                // Set progressdialog title
                                                mProgressDialog.setTitle("Download Image Tutorial");
                                                // Set progressdialog message
                                                mProgressDialog.setMessage("Loading...");
                                                mProgressDialog.setIndeterminate(false);
                                                // Show progressdialog
                                                mProgressDialog.show();
                                }

                                @Override
                                protected Bitmap doInBackground(String... URL) {

                                                String imageURL = URL[0];

                                                Bitmap bitmap = null;
                                                try {
                                                                // Download Image from URL
                                                                InputStream input = new java.net.URL(imageURL).openStream();
                                                                // Decode Bitmap
                                                                bitmap = BitmapFactory.decodeStream(input);
                                                } catch (Exception e) {
                                                                e.printStackTrace();
                                                }
                                                return bitmap;
                                }

                                @Override
                                protected void onPostExecute(Bitmap result) {
                                                // Set the bitmap into ImageView
                                                image.setImageBitmap(result);
                                                // Close progressdialog
                                                mProgressDialog.dismiss();
                                }
                }
}
In this activity, a Button and an ImageView has been created and on button click AsyncTask class will start the image download and will also display the progress dialog. The downloaded image will be decoded into a bitmap image and set into an ImageView.

Step 2 : Create an XML file for the MainActivity graphical layout. Go to res > layout > Right Click  layout > New > Android XML File

Name the new XML file activity_main.xml and add the following code.
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" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </ImageView>

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/image"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/button" />

</RelativeLayout>

Step 3 : Change the application name and texts. Open strings.xml in res > values folder and add the following code.
strings.xml
<resources>

    <string name="app_name">Download Image Tutorial</string>
    <string name="menu_settings">Settings</string>
    <string name="button">Download Image</string>

</resources>

Step 4 : In AndroidManifest.xml, we need to declare a permission to connect to the Internet. Open your AndroidManifest.xml and add the following code.
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.downloadimagetutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.INTERNET" >
    </uses-permission>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
The above code will download the required image from a specific URL into an Android Application.


Processing Json Data Parsing

JavaScript Object Notation ( JSON ) is a simple, light-weighted data interchange format. It is an independent data exchange format which makes data easily readable by machines and humans. It basically represents data in a text format that can be easily parsed. It is the second best alternative to XML.
Android provides four different classes for manipulating Json data for extracting necessary information. These classes are :
·         JSONArray
·         JSONObject
·         JSONStringer
·         JSONTokenizer

Sample JSON Format:
Let's take a look at the sample code of JSON given below. It's a very simple JSON code which gives a list of users where each object contains information like user id, name, gender, email and contact numbers of different users.
{
    "users": [
        {
                "id": "1087",
                "name": "Abhishek Saini",
                "email": "info@abhiandroid.com",
                "gender" : "male",
                "contact": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "1088",
                "name": "Gourav",
                "email": "gourav9188@gmail.com",
                "gender" : "male",
                "contact": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        .
        .
        .
        .
  ]
}

JSON Elements in Android
An JSON file has many components. The following table defines the components of a JSON file and their description :
Component
Description
Array([)
In a JSON file , square bracket ([) represents a JSON array
Objects({)          
In a JSON file, curly bracket ({) represents a JSON object
Key
A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
Value
Each key has a value that could be an integer, string , or double

JSON Parsing in Android

Generally, JSON has two types of nodes JSONArray and JSONObject. So when parsing the most appropriate method should be used. If JSON starts with square bracket ([) then getJSONArray() method is used and if it starts with curly bracket ({) then the getJSONObject() method is used. Besides these methods there are many other methods which can be used for parsing JSON data.

Simple JSON Parsing In Android Studio:
In the following example , the data from JSON is parsed and then displayed in the UI.
The example has employee name and salary stored in JSON format. The first step is to create two TextView's in the XML file and then in the Activity this data is parsed using JSONObject methods and finally set in the TextViews.

Step 1 : Create a new project and name it JSONParsingExample.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code:
(In this step create two TextView’s for displaying employee name and salary)

<?xml version="1.0" encoding="utf-8"?>
<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="exampleandroid.com.jsonparsingexample.MainActivity">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Name"
        android:textColor="#000"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/salary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="80dp"
        android:text="Salary"
        android:textColor="#000"
        android:textSize="20sp" />
</RelativeLayout>

Step 3 : Open app -> java -> package -> MainActivity.java and add the following code. In this step, the refernce of both TextView's is obtained and then JSON is parsed using JSONObject methods and then finally the data is set in TextViews.

package exampleandroid.com.jsonparsingexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {


    String JSON_STRING = "{\"employee\":{\"name\":\"Abhishek Saini\",\"salary\":65000}}";
    String name, salary;
    TextView employeeName, employeeSalary;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // get the reference of TextView's
        employeeName = (TextView) findViewById(R.id.name);
        employeeSalary = (TextView) findViewById(R.id.salary);

        try {
            // get JSONObject from JSON file
            JSONObject obj = new JSONObject(JSON_STRING);
            // fetch JSONObject named employee
            JSONObject employee = obj.getJSONObject("employee");
            // get employee name and salary
            name = employee.getString("name");
            salary = employee.getString("salary");
            // set employee name and salary in TextView's
            employeeName.setText("Name: "+name);
            employeeSalary.setText("Salary: "+salary);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}


Processing XML Data Parsing

Extensible Mark-up Language ( XML ) is a very popular format for sharing data over the internet. It is basically a set of rules for encoding various documents in machine and human readable format. It is common practice in Android to parse XML files to retrieve relevant information.

Types of XML Parsers in Android
There are three types of XML parsers in Android :
·         DOM Parsers
·         SAX Parsers
·         XML PullParser

DOM Parsers - These parsers use object based approach. With DOM Parsers, the entire xml document first loaded into the memory and validated. It then starts parsing the XML document from the starting node till the end node. It cannot parse any particular nodes. It is slower in processing than the other two parsers.

SAX Parser - This parser is similar to DOM Parser in terms of performance and memory. It also uses object based approach and begins parsing from the start node till the end node.

XMLPullParser - This parser can parse particular nodes. This parser is recommended by Android.

XML - Elements
An XML file has 4 major components, which are as follows:
Component
Description
Prolog
An XML file starts with a Prolog. It is the first line that contains information about the XML file.
Events
Events in an XML file refer to  start tags and end tags like Document starts, Document ends, and more.
Text
Text is the simple text between the tags.
Attributes
The additional properties of a tag are called attributes.

Android XMLPullParser Example
Let's take a look at a simple example that parses data of students in XML format using XMLPullParser.

Step 1 : Create a new Android project with package name com.androidxmlparser.

Step 2 : Create a new folder raw under res and add student.xml file inside res/raw with following xml data.
student.xml
<?xml version="1.0"?>
<class>
                <student>
                                <name>Neeraj Mishra</name>
                                <rollno>10</rollno>
                                <age>22</age>
                </student>
               
                <student>
                                <name>Mayank Khandiwal</name>
                                <rollno>11</rollno>
                                <age>22</age>
                </student>
               
                <student>
                                <name>Sumit Gendar</name>
                                <rollno>12</rollno>
                                <age>22</age>
                </student>
               
                <student>
                                <name>Vivek Pathak</name>
                                <rollno>13</rollno>
                                <age>22</age>
                </student>
</class>

Step 3: When a project is created, by default an activity MainActivity is created. This activity is utilized to display the parsed XML data. The following code has to be added inside its xml layout and java source file.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
    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.androidxmlparser.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:text=""/>
</RelativeLayout>

MainActivity.java

package com.androidxmlparser;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.textView);

        InputStream stream = this.getResources().openRawResource(R.raw.student);

        try {
            XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = xmlPullParserFactory.newPullParser();

            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(stream, null);

            String tag_name = "", text = "";
            int event = parser.getEventType();

            while (event != XmlPullParser.END_DOCUMENT) {
                tag_name = parser.getName();

                switch (event) {
                    case XmlPullParser.START_TAG:
                        break;

                    case XmlPullParser.TEXT:
                        text = parser.getText();
                        break;

                    case XmlPullParser.END_TAG:
                        switch(tag_name) {
                            case "name": textView.append("Name: " + text + "\n");
                                        break;
                            case "rollno": textView.append("Roll No: " + text + "\n");
                                        break;
                            case "age": textView.append("Age: " + text + "\n\n");
                                        break;
                        }
                        break;
                }

                event = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Step 4 :  Save and run the project.