Wednesday, September 30, 2015

Android - Mediaplayer

Android - Mediaplayer:

Android provides many ways to control playback of audio/video files and streams. One of this way is through a class called MediaPlayer.
Android is providing MediaPlayer class to access built-in mediaplayer services like playing audio,video e.t.c. In order to use MediaPlayer , we have to call a static Method create() of this class. This method returns an instance of MediaPlayer class. Its syntax is as follows −
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
The second parameter is the name of the song that you want to play. You have to make a new folder under your project with name raw and place the music file into it.
Once you have created the Mediaplayer object you can call some methods to start or stop the music. These methods are listed below.
mediaPlayer.start();
mediaPlayer.pause();
On call to start() method, the music will start playing from the beginning. If this method is called again after the pause() method , the music would start playing from where it is left and not from the beginning.
In order to start music from the beginning , you have to call reset() method. Its syntax is given below.
mediaPlayer.reset();
Apart from the start and pause method, there are other methods provided by this class for better dealing with audio/video files. These methods are listed below −
Sr.NoMethod & description
1isPlaying()This method just returns true/false indicating the song is playing or not
2seekTo(position)This method takes an integer, and move song to that particular second
3getCurrentDuration()This method returns the current position of song in milliseconds
4getDuration()This method returns the total time duration of song in milliseconds
5reset()This method resets the media player
6release()This method releases any resource attached with MediaPlayer object
7setVolume(float leftVolume, float rightVolume)This method sets the up down volume for this player
8setDataSource(FileDescriptor fd)This method sets the data source of audio/video file
9selectTrack(int index)This method takes an integer, and select the track from the list on that particular index
10getTrackInfo()This method returns an array of track information

Example

Here is an example demonstrating the use of MediaPlayer class. It creates a basic media player that allows you to forward, backward , play and pause a song.
To experiment with this example, you need to run this on an actual device to hear the audio sound.
StepsDescription
1You will use Android studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication;. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add MediaPlayer code.
3Modify the res/layout/activity_main to add respective XML components
4Create a new folder under MediaPlayer with name as raw and place an mp3 music file in it with name as song.mp3
5Run the application and choose a running android device and install the application on it and verify the results
Following is the content of the modified main activity file src/MainActivity.java.
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.app.Activity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;

import android.os.Bundle;
import android.os.Handler;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;


public class MainActivity extends Activity {
   private Button b1,b2,b3,b4;
   private ImageView iv;
   private MediaPlayer mediaPlayer;
   private double startTime = 0;
   private double finalTime = 0;
   private Handler myHandler = new Handler();;
   private int forwardTime = 5000;
   private int backwardTime = 5000;
   private SeekBar seekbar;
   private TextView tx1,tx2,tx3;
   
   public static int oneTimeOnly = 0;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      b1 = (Button) findViewById(R.id.button);
      b2 = (Button) findViewById(R.id.button2);
      b3=(Button)findViewById(R.id.button3);
      b4=(Button)findViewById(R.id.button4);
      iv=(ImageView)findViewById(R.id.imageView);
      
      tx1=(TextView)findViewById(R.id.textView2);
      tx2=(TextView)findViewById(R.id.textView3);
      tx3=(TextView)findViewById(R.id.textView4);
      tx3.setText("Song.mp3");
      
      mediaPlayer = MediaPlayer.create(this, R.raw.song);
      seekbar=(SeekBar)findViewById(R.id.seekBar);
      seekbar.setClickable(false);
      b2.setEnabled(false);
      
      b3.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Playing sound",Toast.LENGTH_SHORT).show();
            mediaPlayer.start();
            
            finalTime = mediaPlayer.getDuration();
            startTime = mediaPlayer.getCurrentPosition();
            
            if (oneTimeOnly == 0) {
               seekbar.setMax((int) finalTime);
               oneTimeOnly = 1;
            }
            tx2.setText(String.format("%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
            TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime)))
            );
            
            tx1.setText(String.format("%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes((long) startTime),
            TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime)))
            );
            
            seekbar.setProgress((int)startTime);
            myHandler.postDelayed(UpdateSongTime,100);
            b2.setEnabled(true);
            b3.setEnabled(false);
         }
      });
      
      b2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Pausing sound",Toast.LENGTH_SHORT).show();
            mediaPlayer.pause();
            b2.setEnabled(false);
            b3.setEnabled(true);
         }
      });
      
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int temp = (int)startTime;
            
            if((temp+forwardTime)<=finalTime){
               startTime = startTime + forwardTime;
               mediaPlayer.seekTo((int) startTime);
               Toast.makeText(getApplicationContext(),"You have Jumped forward 5 seconds",Toast.LENGTH_SHORT).show();
            }
            else{
               Toast.makeText(getApplicationContext(),"Cannot jump forward 5 seconds",Toast.LENGTH_SHORT).show();
            }
         }
      });
      
      b4.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int temp = (int)startTime;
            
            if((temp-backwardTime)>0){
               startTime = startTime - backwardTime;
               mediaPlayer.seekTo((int) startTime);
               Toast.makeText(getApplicationContext(),"You have Jumped backward 5 seconds",Toast.LENGTH_SHORT).show();
            }
            else{
               Toast.makeText(getApplicationContext(),"Cannot jump backward 5 seconds",Toast.LENGTH_SHORT).show();
            }
         }
      });
   }
   
   private Runnable UpdateSongTime = new Runnable() {
      public void run() {
         startTime = mediaPlayer.getCurrentPosition();
         tx1.setText(String.format("%d min, %d sec",
         
         TimeUnit.MILLISECONDS.toMinutes((long) startTime),
         TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
         TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
         toMinutes((long) startTime)))
         );
         seekbar.setProgress((int)startTime);
         myHandler.postDelayed(this, 100);
      }
   };
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
Following is the modified content of the xml res/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" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
   <TextView android:text="Music Palyer" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:src="@drawable/abc"/>
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text=">>"
      android:id="@+id/button"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="||"
      android:id="@+id/button2"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="<"
      android:id="@+id/button3"
      android:layout_alignTop="@+id/button2"
      android:layout_toRightOf="@+id/button2"
      android:layout_toEndOf="@+id/button2" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="<<"
      android:id="@+id/button4"
      android:layout_alignTop="@+id/button3"
      android:layout_toRightOf="@+id/button3"
      android:layout_toEndOf="@+id/button3" />
      
   <SeekBar
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/seekBar"
      android:layout_alignLeft="@+id/textview"
      android:layout_alignStart="@+id/textview"
      android:layout_alignRight="@+id/textview"
      android:layout_alignEnd="@+id/textview"
      android:layout_above="@+id/button" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceSmall"
      android:text="Small Text"
      android:id="@+id/textView2"
      android:layout_above="@+id/seekBar"
      android:layout_toLeftOf="@+id/textView"
      android:layout_toStartOf="@+id/textView" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceSmall"
      android:text="Small Text"
      android:id="@+id/textView3"
      android:layout_above="@+id/seekBar"
      android:layout_alignRight="@+id/button4"
      android:layout_alignEnd="@+id/button4" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:text="Medium Text"
      android:id="@+id/textView4"
      android:layout_alignBaseline="@+id/textView2"
      android:layout_alignBottom="@+id/textView2"
      android:layout_centerHorizontal="true" />

</RelativeLayout>
Following is the content of the res/values/string.xml.
<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.mediaplayer"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="13"
      android:targetSdkVersion="22" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.sairamkrishna.myapplication.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Android studio will display following screens
Anroid MediaPlayer Tutorial By default you would see the pause button disabled. Now press play button and it would become disable and pause button become enable. It is shown in the picture below −
Up till now, the music has been playing. Now press the pause button and see the pause notification. This is shown below −
Anroid MediaPlayer Tutorial Now when you press the play button again, the song will not play from the beginning but from where it was paused. Now press the fast forward or backward button to jump the song forward or backward 5 seconds. A time came when the song cannot be jump forward. At this point , the notification would appear which would be something like this −
Anroid MediaPlayer Tutorial Your music would remain playing in the background while you are doing other tasks in your mobile. In order to stop it , you have to exit this application from background activities.
Anroid MediaPlayer Tutorial Above image shows when you pick rewind button.

 

Thursday, September 24, 2015

Android - Loading Spinner

Android - Loading Spinner:

You can show progress of a task in android through loading progress bar. The progress bar comes in two shapes. Loading bar and Loading Spinner. In this chapter we will discuss spinner.
Spinner is used to display progress of those tasks whose total time of completion is unknown. In order to use that, you just need to define it in the xml like this.
<ProgressBar
   android:id="@+id/progressBar1"
   style="?android:attr/progressBarStyleLarge"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true" />
After defining it in xml, you have to get its reference in java file through ProgressBar class. Its syntax is given below −
private ProgressBar spinner;
spinner = (ProgressBar)findViewById(R.id.progressBar1);
After that you can make its disappear , and bring it back when needed through setVisibility Method. Its syntax is given below −
spinner.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE); 
Apart from these Methods, there are other methods defined in the ProgressBar class , that you can use to handle spinner more effectively.
Sr.NoMethod & description
1isIndeterminate()Indicate whether this progress bar is in indeterminate mode
2postInvalidate()Cause an invalidate to happen on a subsequent cycle through the event loop
3setIndeterminate(boolean indeterminate)Change the indeterminate mode for this progress bar
4invalidateDrawable(Drawable dr)Invalidates the specified Drawable
5incrementSecondaryProgressBy(int diff)Increase the progress bar's secondary progress by the specified amount
6getProgressDrawable()Get the drawable used to draw the progress bar in progress mode

Example

Here is an example demonstrating the use of ProgressBar to handle spinner. It creates a basic application that allows you to turn on the spinner on clicking the button.
To experiment with this example , you can run this on an actual device or in an emulator.
StepsDescription
1You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication;. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/activity_main to add respective XML components
4Need to create a xml file in drawable folder.it contains shape and rotate information about the progress bar
5Run the application and choose a running android device and install the application on it and verify the results
Following is the content of the modified main activity file src/MainActivity.java.
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;


public class MainActivity extends Activity {
   Button b1;
   
   private ProgressBar spinner;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      b1=(Button)findViewById(R.id.button);
      spinner=(ProgressBar)findViewById(R.id.progressBar);
      spinner.setVisibility(View.GONE);
      
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            spinner.setVisibility(View.VISIBLE);
         }
      });
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
Following is the modified content of the xml res/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" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
   <TextView android:text="Progress Dialog" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="download"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_centerHorizontal="true" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />
      
   <ProgressBar
      style="?android:attr/progressBarStyleLarge"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/progressBar"
      android:progressDrawable="@drawable/circular_progress_bar"
      android:layout_below="@+id/button"
      android:layout_alignRight="@+id/textView"
      android:layout_alignEnd="@+id/textView"
      android:layout_alignLeft="@+id/textview"
      android:layout_alignStart="@+id/textview"
      android:layout_alignParentBottom="true" />

</RelativeLayout>
Following is the content of the res/drawable/circular_progress_bar.xml.
<?xml version="1.0" encoding="utf-8"?>
<rotate
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:fromDegrees="90"
   android:pivotX="50%"
   android:pivotY="50%"
   android:toDegrees="360">
   
   <shape
      android:innerRadiusRatio="3"
      android:shape="ring"
      android:thicknessRatio="7.0">
      
      <gradient
         android:centerColor="#007DD6"
         android:endColor="#007DD6"
         android:startColor="#007DD6"
         android:angle="0"
         android:type="sweep"
         android:useLevel="false" />
   </shape>
   
</rotate>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.spinner"
   android:versionCode="1"
   android:versionName="1.0" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.sairamkrishna.myapplication.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>
Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Anroid Loading Spinner Tutorial Now click on the load spinner button to turn on the loading spinner. It is shown in the image below −
Anroid Loading Spinner Tutorial

 

Friday, September 18, 2015

Android - JSON Parser

Android - JSON Parser:

SON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.

Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.
The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting temperature only.
{
   "sys":
   {
      "country":"GB",
      "sunrise":1381107633,
      "sunset":1381149604
   },
   "weather":[
   {
      "id":711,
      "main":"Smoke",
      "description":"smoke",
      "icon":"50n"
   }
],
"main":
   {
      "temp":304.15,
      "pressure":1009,
   }
}

JSON - Elements

An JSON file consist of many components. Here is the table defining the components of an JSON file and their description −
Sr.No Component & description
1 Array([) In a JSON file , square bracket ([) represents a JSON array
2 Objects({) In a JSON file, curly bracket ({) represents a JSON object
3 Key A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
4 Value Each key has a value that could be string , integer or double e.t.c

JSON - Parsing

For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it. Its syntax is:
String in;
JSONObject reader = new JSONObject(in);
The last step is to parse the JSON. An JSON file consist of different object with different key/value pair e.t.c. So JSONObject has a separate function for parsing each of the component of JSON file. Its syntax is given below:
JSONObject sys  = reader.getJSONObject("sys");
country = sys.getString("country");
   
JSONObject main  = reader.getJSONObject("main");
temperature = main.getString("temp");
The method getJSONObject returns the JSON object. The method getString returns the string value of the specified key.
Apart from the these methods , there are other methods provided by this class for better parsing JSON files. These methods are listed below −
Sr.No Method & description
1 get(String name) This method just Returns the value but in the form of Object type
2 getBoolean(String name) This method returns the boolean value specified by the key
3 getDouble(String name) This method returns the double value specified by the key
4 getInt(String name) This method returns the integer value specified by the key
5 getLong(String name) This method returns the long value specified by the key
6 length() This method returns the number of name/value mappings in this object..
7 names() This method returns an array containing the string names in this object.

Example

To experiment with this example , you can run this on an actual device or in an emulator.
Steps Description
1 You will use Android studio to create an Android application. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file to add necessary code.
3 Modify the res/layout/activity_main to add respective XML components
4 Modify the res/values/string.xml to add necessary string components
5 Run the application and choose a running android device and install the application on it and verify the results
Following is the content of the modified main activity file src/MainActivity.java.
package com.tutorialspoint.json;

import android.app.Activity;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends Activity {
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      TextView output = (TextView) findViewById(R.id.textView1);
      String strJson="
      {
         \"Employee\" :[
         {
            \"id\":\"01\",
            \"name\":\"Gopal Varma\",
            \"salary\":\"500000\"
         },
         {
            \"id\":\"02\",
            \"name\":\"Sairamkrishna\",
            \"salary\":\"500000\"
         },
         {
            \"id\":\"03\",
            \"name\":\"Sathish kallakuri\",
            \"salary\":\"600000\"
         }
         ] 
      }";
      String data = "";
      try {
         JSONObject  jsonRootObject = new JSONObject(strJson);
         
         //Get the instance of JSONArray that contains JSONObjects
         JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
         
         //Iterate the jsonArray and print the info of JSONObjects
         for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            
            int id = Integer.parseInt(jsonObject.optString("id").toString());
            String name = jsonObject.optString("name").toString();
            float salary = Float.parseFloat(jsonObject.optString("salary").toString());
            
            data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
         }
         output.setText(data);
      } catch (JSONException e) {e.printStackTrace();}
   }
}
Following is the modified content of the xml res/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" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="JSON example"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="35dp"
      android:textColor="#ff16ff01" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="New Text"
      android:id="@+id/textView1"
      android:layout_below="@+id/textView2"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true" />
</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   
   <uses-permission android:name="android.permission.INTERNET"/>
   
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      
   </application>
</manifest>
Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:
Anroid XML Parser Tutorial Above Example showing the data from string json,The data has contained employer details as well as salary information