Wednesday 28 September 2016

Android - JSON Parser Tutorial

Android - JSON Parser Tutorial



JSON 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.NoComponent & description
1Array([)
In a JSON file , square bracket ([) represents a JSON array
2Objects({)
In a JSON file, curly bracket ({) represents a JSON object
3Key
A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
4Value
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 getStringreturns 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.NoMethod & description
1get(String name)
This method just Returns the value but in the form of Object type
2getBoolean(String name)
This method returns the boolean value specified by the key
3getDouble(String name)
This method returns the double value specified by the key
4getInt(String name)
This method returns the integer value specified by the key
5getLong(String name)
This method returns the long value specified by the key
6length()
This method returns the number of name/value mappings in this object..
7names()
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.
StepsDescription
1You 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.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the res/values/string.xml to add necessary string components
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 filesrc/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 yourAVD 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

Android Application Concepts: The Activity

Android Application Concepts: The Activity


Android applications can be constructed from four different types of components: activities, services, broadcast receivers, and content providers. Of the four, the only one that you must use at least one of in every application (and the only one that I've had to use so far) is the activity.
I'm not going to even try to give a full explanation of what an activity is: the Application Fundamentals page on the Android Developers site provides a thorough (and rather long) explanation of activies as well as the other three components. So I'm just going to list some aspects of activities to give you a conceptual overview of what an activity is:
  • Each individual screen within an Android application is an activity, and users can perform actions by interacting with the visual components within an activity. Think of it as an individual web page within a modern web application, where the user can perform certain functions without leaving the page (using JavaScript), but must proceed to a different page in order to access a new set of tasks/functionality.
  • Each activity operates independently of one another (again, similar to how individual pages in a web application are separate from one another).
  • The visual objects within an activity (blocks of text, input boxes, buttons, etc.) are usually organized and instantiated by implementing instructions within a layout XML file.  They CAN be added individually with regular Java code, but the XML method is the recommended practice.
  • The transistion from one activity to another is accomplished through the use of asynchronous messages called Intents. An intent can be used to pass data from one activity to another, and that data is structured using key/value pairs. It's similar to how data is passed when an HTML form is submitted.
  • Each activity in an Android application is either a direct subclass of the Activity base class or a subclass of an Activity subclass that provides specialized functionality (such as the ListActivity class which contains methods specifically for the display of data in a touch-enabled list), and is represented in the application package as a single Java class.
  • All of the activities in the application must be defined in the application's manifest file, an XML file that keeps track of all of the components, resources, and permissions that make up the application.
  • All Android application components, including activities, have lifecycles. The current lifecycle state of a component provides part of the information the Android OS uses when it determines what components can be safely removed from memory in order to free up memory space. All activities inherit a set of lifecycle methods from the Activity base class that are executed when the corresponding lifecyle state of the activity is reached. These lifecycle methods are:
    • onCreate: the code within the onCreate lifecycle method is called when the activity is instantiated/loaded into memory. This is the method in which you want to set up the intial state of your variables, instantiate the visual objects within the activity via your layout file, and bind your event listeners. If you're a jQuery user, think of it as the equivalent of the document.ready function.
    • onStart: the method called when the activity becomes visible to the user.
    • onResume: the method called when the activity is moved to the foreground of the visible space, when the user is able to not only see the activity but interact with it. After the onResume method is called, the activity is considered to be "running."
    • onPause: called when the activity is no longer in the foreground, usually as the result of another activity being started.
    • onStop: called when the activity is no longer visible to the user in either the foreground or background.
    • onRestart: called when the activity is being restarted (made visible again) after executing onStop but not onDestroy.
    • onDestroy: called just before an activity is destroyed/unloaded from memory.

  • Any activity that isn't currently "running" could potentially be removed from memory by the Android OS if available system memory is low. The more inactive an activity is, the better the chance of it being destroyed to reclaim memory, so an activity that is "stopped" is in more danger of being removed from memory than an activity that is "paused."
  • Because even an activity that is "paused" can be destroyed under extremely low memory conditions, it is a best practice to run code to store/save any persistent data within the activity within the onPause method just in case (kind of like how the auto-save function works in Microsoft Office to save your work every few minutes).
  • To preserve the current state of an activity (like filtered search results) rather than persistent data, you can use code in the onSaveInstanceState method to perserve that data in a Bundleobject (which, like an intent, stores data in key/value pairs).  The onSaveInstanceState method in the activity is called by the Android OS itself as soon as the activity has the potential to be removed from memory. However, onSaveInstanceState is NOT called when the user explicitly takes action to destroy an activity (usually by exiting the entire application).
  • It is possible for one "application" to utilize activity objects from one or more different application packages (.apk files), given the proper planning and permissions.

7 Key Android Concepts



7 Key Android Concepts


 Karthikeyan .R
Although The Android Platform Is Open And Customizable, Android Users Have Become Accustomed To Constructs Developed By Google For Android Devices.
Although the Android platform is open and customizable, Android users have become accustomed to constructs developed by Google for Android devices. Moreover, the use of these Android concepts is vital in developing an application quickly – custom Android designs can take up to 10 times longer!

Android UI Controls

Android provides a number of standard UI controls that enable a rich user experience. Designers and developers should thoroughly understand all of these controls for the following reasons:
  • They are faster to implement. It can take up to ten times longer to develop a custom control than to implement a user interface with standard Android controls.
  • They ensure good performance. Custom controls rarely function as expected in their first implementation. By implementing standard controls, you can eliminate the need to test, revise and improve custom controls. Moreover, while designers will spend a great deal of time thinking about how a control should look, they may not always consider the many ways in which a custom control will behave in the user’s hands. Items on a mobile device often need to grow and shrink in size as they are pinched, or scroll if they are part of a list. As a result, creating a “clean” custom control from scratch can take a significant amount of design and development time. Google, however, has already thought about these interactions and developed standard controls to properly address them.
  • Android users expect standard controls. Through their interactions with other Android apps, users become accustomed to Android’s standard controls. Deviating from the standard Android user experience can confuse and frustrate users, making them less likely to want to use your app and incorporate it into their daily activities.
With a solid awareness of Android’s standard controls, designers and developers can speedapp development while offering users an intuitive experience that feels instantly familiar.

Activities

Android applications are composed of “activities” which are unique, focused actions a user can take. Because it can be difficult or time-consuming to scroll, zoom in, or click links on a small screen, it is recommended that an app display only one activity per screen. This practice presents the user with only the most relevant information and allows them to launch a new screen for additional information, or click the “back” button to view the previous activity. While a screen can expose multiple tasks, it should help the user complete just one activity at a time.
In Gmail for example, a user can only read the body of an e-mail (right) once he has clicked the relevant message (left). This layout reduces the amount of information displayed on each screen and allows the user to easily navigate between the Inbox and the message text.

User Interactions

When a user first downloads your application, he will make snap judgments on the usability and intuitiveness of the application within the first few minutes of use. It is, therefore, crucial to balance the creativity of your app with the standard user interactions Android users have come to expect. These include:
  • Hard buttons: including Back, Menu, Home and Search buttons. Soft buttons that duplicate these features will only confuse or frustrate Android users. Moreover, back button behavior can be tricky and needs to be defined up-front for every screen, as it is not always as simple as returning to the previous activities. Most mobile phones, for example, offer both an “incoming call” activity and an “active call” activity. Once a user has answered and completed the call, the user would not expect to return to the “incoming call” activity upon pressing the “back” button, but rather to the activity that occurred before the incoming call. If the app offers only one activity, the back button should return the user to the device’s home page.
  • Long press elements: Items of a list can be long pressed to open a context menu that provides secondary information. “ToDo” list apps, for example, often use a touch interaction to mark a task as completed and a long press interaction to display a menu with “edit” or “delete” functionality.

Layouts

Android UI screens are frequently resized, both on the fly via pinch and zoom as well as at startup when Android adjusts the size of the UI to fit the screen size of the mobile device on which it’s running. In order to make the most of the screen size and handle this resizing gracefully, Android provides a number of screen layout options.
First, Android developers must specify whether each screen should follow a linear layout which manages controls in a horizontal or vertical fashion, or a relative layout which manages controls in relation to one another. Linear layouts are the most common, as in the example below. At left, the controls only stretch to accommodate the text and are positioned in a horizontal line. In the middle image, the same rules apply but in a vertical layout. At right, the vertical layout is maintained but the middle button stretches to accommodate the screen rather than the text.
A relative layout defines the position of controls by their relationship to other components on the same screen. In the example below from the droidcake.com blog, the “OK” button was specified to be set below the radio button group. The “Cancel” button was specified to be set to the right of the OK button with its right edge extended to the edge of the screen. This relative layout positioning ensures the position of the buttons remains constant across a variety of screen sizes.
Android also offers specific layout properties to control the way in which screen elements are displayed across Android devices and during use:
  • Weight: The weight property allows the developer to determine how free space is divided on the screen.
  • Gravity: Gravity is the term used for control alignment (right, bottom, top, or left) on an Android device.
  • Density independence: Your application achieves “density independence” when it preserves the physical size (from the user’s point of view) of user interface elements displayed on screens with different densities. Without density independence, a UI element (such as a button) will appear larger on a low-density screen and smaller on a high-density screen.
So who specifies all of these properties?
If an Android application is designed in a vacuum and then “thrown over the wall” to the development team, you must rely on the developers’ interpretation of the design which may vary significantly from the original intent. On the other hand, the development team shouldn’t be expecting the designer to specify the weight, gravity and other layout properties of each screen and control.
In our experience, the best practice is to have the designer document the layout and resize behavior of each screen to the development team via a series of wireframes, if not a full style guide. The designer should then stay in close communication with the development team as the developers work to determine the right combination of Android layout properties to realize the design.

Screen Size

A common misconception is that an Android app should be designed to support only a specific set of Android devices. Many teams assume their app will only look right on a screen of a particular screen size and limit their design to suit only a handful of devices supporting that size. In reality, Android offers you tools needed to develop a visually impressive interface that supports the full range of devices and screen sizes on the market.
To help you accommodate the range of Android screen sizes, Android recommends designing four versions of the application UI:
  • A small version for screens under 3”.
  • A normal version to accommodate 3” to 4.5” screens.
  • A large version for viewing on 4.5” to 10” screens.
  • An extra large version for devices with screens larger than 10” (tablet).
It is not strictly necessary to create a design for all four versions – in some cases; one “normal” and one “extra large” version may suffice. If, however, you need to display a large number of controls on your screen, or your organization wishes to ensure perfect consistency across screen sizes, you may decide to accommodate all four size categories listed above.

Fragments

A smartphone should only display one activity per screen due to its small screen size. Tablet devices, however, offer additional screen real estate and are often used in a similar setting as a desktop or notebook, meaning the application could show more information at once on the screen. Using an Android construct called fragments, designers and developers can merge portions of the UI onto one large screen or split them into individual screens for use on small screens. This can help to reduce the number of interactions a user must perform on a device with a large screen and eliminate wasted space.
The example below shows a Gmail interface on a tablet display. This design uses fragments to display both the navigation list at left and the Inbox content at right. The design reduces the number of screens that must load before the user reaches the desired message.
If you anticipate your app will someday be used on a tablet device, we strongly recommend you incorporate fragments into your design. Designers need to be aware of the concept of fragments in order to design by fragment, and developers also need to be aware of this concept and its implementation details.
By designing custom, reusable fragments for each screen activity at the beginning of the project, you can eliminate the need to create an entirely new layout for a tablet device.

Intents

Android applications typically borrow from other applications already on the device. Using intents you can simplify both the programming requirements for your app and offer simpler, less cluttered screens.
If your app needs to perform a function beyond its core abilities such as opening a photo, looking up a contact, or playing a video, the team should investigate whether a tool that can perform that function already exists in the OS or in a popular third-party app. If so, you can leverage that functionality using intents.
For example, if your app accesses user contacts, you can use intent objects to launch the device’s existing Contacts application. This will eliminate programming duplication and speed up the user’s interaction with the device since the user will not need to re-learn how to add a contact to your particular app.
Android offers specific UI controls, activities, interactions, layout and resize options, as well as special constructs like fragments and intents. While on the surface these appear to be things that the design team needs to work with, we contend that the entire team must be immersed in Android to coordinate design, workflow, and execution into a single, intuitive application — one that grabs users’ attentions and draws them into the real value of your product.

Send Whatsapp Message via PHP Code

  How to Send and Receive Messages in WhatsApp using PHP In this tutorial you will see How to Send and Receive Messages in WhatsApp using PH...