Android - JSON Parser Tutorial

Similar documents
Android - Widgets Tutorial

Time Picker trong Android

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

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Switching UIs


Android Application Development. By : Shibaji Debnath

Fragment Example Create the following files and test the application on emulator or device.

Tabel mysql. Kode di PHP. Config.php. Service.php

MAD ASSIGNMENT NO 3. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Cloudant NoSQL DB)

Mobile Software Development for Android - I397

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

EMBEDDED SYSTEMS PROGRAMMING Android Services

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 2

PENGEMBANGAN APLIKASI PERANGKAT BERGERAK (MOBILE)

SD Module-1 Android Dvelopment

EMBEDDED SYSTEMS PROGRAMMING UI Specification: Approaches

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation

Software Practice 3 Before we start Today s lecture Today s Task Team organization

Create Parent Activity and pass its information to Child Activity using Intents.

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

CSE 660 Lab 7. Submitted by: Arumugam Thendramil Pavai. 1)Simple Remote Calculator. Server is created using ServerSocket class of java. Server.

Tip Calculator. xmlns:tools=" android:layout_width="match_parent"

Group B: Assignment No 8. Title of Assignment: To verify the operating system name and version of Mobile devices.

Introduction to Android Development

PROGRAMMING APPLICATIONS DECLARATIVE GUIS

COMP61242: Task /04/18

MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

Android UI Development

1. Location Services. 1.1 GPS Location. 1. Create the Android application with the following attributes. Application Name: MyLocation

ELET4133: Embedded Systems. Topic 15 Sensors

Tutorial: Setup for Android Development

An Overview of the Android Programming

Android Navigation Drawer for Sliding Menu / Sidebar

Android Apps Development for Mobile Game Lesson 5

Android Programs Day 5

LAMPIRAN. byte bcdtodec(byte val) { return( (val/16*10) + (val%16) ); } void setup() {

Android JSON Parsing Tutorial

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

Mobile Application Development Lab [] Simple Android Application for Native Calculator. To develop a Simple Android Application for Native Calculator.

Intents. Your first app assignment

Produced by. Mobile Application Development. Eamonn de Leastar

Coding Menggunakan software Eclipse: Mainactivity.java (coding untuk tampilan login): package com.bella.pengontrol_otomatis;

LifeStreet Media Android Publisher SDK Integration Guide

Tutorial: Setup for Android Development

Multiple Activities. Many apps have multiple activities

Basic GUI elements - exercises

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

Getting Started With Android Feature Flags

CSE 660 Lab 3 Khoi Pham Thanh Ho April 19 th, 2015


Diving into Android. By Jeroen Tietema. Jeroen Tietema,

EMBEDDED SYSTEMS PROGRAMMING Application Basics

APPENDIX CODE TO STORE THE BUTTON MENU AND MOVE THE PAGE

// MainActivity.java ; Noah Spenser; Senior Design; Diabetic Breathalyzer

M.A.D ASSIGNMENT # 2 REHAN ASGHAR BSSE 15126

StoppUhr. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="start1"

Vienos veiklos būsena. Theory

TextView Control. EditText Control. TextView Attributes. android:id - This is the ID which uniquely identifies the control.

Mobile Health Sensing with Smart Phones

B9: Việc cuối cùng cần làm là viết lại Activity. Tới Example.java và chỉnh sửa theo nội dung sau: Mã: package at.exam;

Serious Gaming. Technical manual. This document is a collection of the code and installation process

IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application.

Manifest.xml. Activity.java

Our First Android Application

B3: Bên khung Package Explore bên trái đi tới thư mục res, bạn sẽ thấy có 3 thư mục con:

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

Create a local SQL database hosting a CUSTOMER table. Each customer includes [id, name, phone]. Do the work inside Threads and Asynctasks.

ITU- FAO- DOA- TRCSL. Training on. Innovation & Application Development for E- Agriculture. Shared Preferences

Fragments. Lecture 11

android-espresso #androidespresso

Android Workshop: Model View Controller ( MVC):

Created By: Keith Acosta Instructor: Wei Zhong Courses: Senior Seminar Cryptography

SMAATSDK. NFC MODULE ON ANDROID REQUIREMENTS AND DOCUMENTATION RELEASE v1.0

INTRODUCTION TO ANDROID

Database Development In Android Applications

1 카메라 1.1 제어절차 1.2 관련주요메서드 1.3 제작철차 서피스뷰를생성하고이를제어하는서피스홀더객체를참조해야함. 매니페스트에퍼미션을지정해야한다.

EMBEDDED SYSTEMS PROGRAMMING Android NDK

API Guide for Gesture Recognition Engine. Version 2.0

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

Android Beginners Workshop

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 4. Workshop

EMBEDDED SYSTEMS PROGRAMMING Android NDK

Data Persistence. Chapter 10

Learning Android Canvas

Dynamically Create Admob Banner and Interstitial Ads

B5: Time to coding. Tới thư mục src/example.java và thay đổi nội dung file như sau: Mã: package at.exam;

Mobile Development Lecture 9: Android & RESTFUL Services

使用 TensorFlow 設計矩陣乘法計算並轉移執行在 Android 上 建國科技大學資管系 饒瑞佶 2017/8

Arrays of Buttons. Inside Android

Wireless Vehicle Bus Adapter (WVA) Android Library Tutorial

Developing For Android

8/30/15 MOBILE COMPUTING. CSE 40814/60814 Fall How many of you. have implemented a command-line user interface?

App Development for Smart Devices. Lec #7: Audio, Video & Telephony Try It Out

Applications. Marco Ronchetti Università degli Studi di Trento

API Guide for Gesture Recognition Engine. Version 1.1

Workshop. 1. Create a simple Intent (Page 1 2) Launch a Camera for Photo Taking

M.A.D Assignment # 1

Android Tutorial: Part 3

Transcription:

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 Stt Component & Miêu tả 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 u 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 Stt Phương thức & Miêu tả 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. Ví dụ thuộc tính trong CSS To experiment with this example, you can run this on an actual device or in an emulator. Steps Miêu tả 1 You will use Android studio to create an Android application. While creati project, make sure you Target SDK and Compile With at the latest versio 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 a it and verify the results Sau đây là nội dung của Main Activity file đã được sửa đổi: 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(); Bạn sửa đổi nội dung của 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> Tiếp theo là nội dung của 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> Chạy ứng dụng vừa sửa đổi ở trên. 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 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: Above Example showing the data from string json,the data has contained employer details as well as salary information