Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1K views

Android JSON Parsing and Image Loading Tutorial - Wingnity Blog PDF

This document provides a tutorial on parsing JSON data and loading images from URLs in Android. It discusses JSON syntax and structure, downloading JSON data from a URL using an AsyncTask, parsing the JSON into Actors objects with fields like name, image URL, etc. It also covers creating a custom row layout for a ListView, an ActorAdapter class to populate the ListView with the parsed data and downloaded images, and adding the necessary Internet permission to the Android manifest. The full source code is available for download to implement this tutorial on parsing JSON and loading images in an Android app.

Uploaded by

persephonise
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Android JSON Parsing and Image Loading Tutorial - Wingnity Blog PDF

This document provides a tutorial on parsing JSON data and loading images from URLs in Android. It discusses JSON syntax and structure, downloading JSON data from a URL using an AsyncTask, parsing the JSON into Actors objects with fields like name, image URL, etc. It also covers creating a custom row layout for a ListView, an ActorAdapter class to populate the ListView with the parsed data and downloaded images, and adding the necessary Internet permission to the Android manifest. The full source code is available for download to implement this tutorial on parsing JSON and loading images in an Android app.

Uploaded by

persephonise
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

HOME

ANDROID

HADOOP

INTERVIEWTIPS

typeyoursearchhere

ADVANCEDANDROIDTOPICS
Mar

24
2014

AndroidJSONParsingandImageLoadingTutorial
AnarticlebyWingnityTeam

97Comments

LEARNANDROIDNOW

InthistutorialwewilllearnhowJSONparsingisdoneinAndroid,alsowewillloadtheimagesfrom
URLtodisplaytheminacustomizedListViewofAndroid.
Downloadsourcecode

1/8

Android JSON Parsing Tutorial 1 - Overview of JSON

RECENTPOSTS
ShouldiswitchtoAndroidStudio?

1.WhatisJSON?
ForthosewhodontknowwhatisJSON,aquickexplanationisgivenbelow:
JSONstandsforJavaScriptObjectNotation
Itsalightweightdatainterchangeformat

ComparisonbetweenAndroidStudio&
Eclipse
WhatisAndroidStudio?
BigData,Hadoopandthepreparationfor
thefuture
HadoopandMongoDBgainspopularity

Itiseasyforhumanstoreadandwriteandeasyformachinestoparseandgenerate.

RECENTCOMMENTS
SunderonAndroidJSONParsingand
ImageLoadingTutorial
PankajonAndroidJSONParsingand
ImageLoadingTutorial
GetWizonBeginnersGuideforAndroid
Architecture
GetWizonWhatisContextinAndroid
paramatmasharanupadhyayonAndroid
JSONParsingandImageLoading
Tutorial

CATEGORIES
AdvancedAndroidTopics
Android

AndroidDevelopmentTutorials
AndroidStudio
Design
Hadoop
InterviewTips
Java
Widgets

FOLLOWONG+

Wingnity
google.com/+Wingnity
...wing you future

Takip et
+ 203

JSONismadeupofthreeparts:
1. Key/ValuePairsseparatedbycolons(:)
firstNameisKEY,JohnisVALUEintheaboveexample
2. JSONArrays
JSONArrayisacollectionofJSONObjectsanditisrepresentedbysquarebrackets[]
Intheaboveexamplewehave1JSONArraynamedasemployees
3. JSONObjects
JSONObjectscancontainotherobjectsorJSONArraysanditisrepresentedbycurly
brackets{}
Intheaboveexamplewehave3JSONobjects,1stJSONObjectcontainsaJSONArray
only(employees),theothertwoJSONObjectscontainKEY/VALUEPairs(JohnDoe
andAnnaSmith).

2.RealJSONData
NowthatyouknowwhatJSONis,letslookhowourrealdatalookslikewhichwewillparseinthis
tutorial.
OurJSONishostedonthefollowing
url:http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors

+1

{
"actors":[
{
"name":"BradPitt",
"description":"WilliamBradley'Brad'PittisanAmericanactorandfilmproducer.H
ehasreceivedaGoldenGlobeAward,aScreenActorsGuildAward,andthreeAcade
myAwardnominationsinactingcategories",
"dob":"December18,1963",
"country":"UnitedStates",
"height":"1.80m",
"spouse":"JenniferAniston",
"children":"ShilohNouvelJoliePitt,MaddoxChivanJoliePitt",
"image":"http://microblogging.wingnity.com/JSONParsingTutorial/brad.jpg"
},
{
"name":"TomCruise",
"description":"TomCruise,isanAmericanfilmactorandproducer.Hehasbeenn
ominatedforthreeAcademyAwardsandhaswonthreeGoldenGlobeAwards.Hesta
rtedhiscareeratage19inthe1981filmEndlessLove.",
"dob":"July3,1962",
"country":"UnitedStates",
"height":"1.70m",
"spouse":"KatieHolmes",
"children":"SuriCruise,IsabellaJaneCruise,ConnorCruise",

3.Howitworks?

Step1.WewillexecuteanAsyncTaskinourMainActivity.javafiletofetchtheJSONdatafromthe

server.
Step2.ServerwillsendtheJSONdatabacktoMainActivity.java
Step3.AfterfetchingtheJSON,wekindofstorethattemporarilyinourActors.javaclassby
creatingnewobjectsforeachActor.
Step4.WecreateanActorAdapterclasstopassthisdatatotheListView
Step5.ThisishowourfinalListViewwilllooklike

4.JSONParsing
classJSONAsyncTaskextendsAsyncTask<String,Void,Boolean>{

@Override
protectedBooleandoInBackground(String...urls){
try{

//>>
HttpGethttppost=newHttpGet(urls[0])
HttpClienthttpclient=newDefaultHttpClient()
HttpResponseresponse=httpclient.execute(httppost)

//StatusLinestat=response.getStatusLine()
intstatus=response.getStatusLine().getStatusCode()

if(status==200){
HttpEntityentity=response.getEntity()
Stringdata=EntityUtils.toString(entity)

JSONObjectjsono=newJSONObject(data)
JSONArrayjarray=jsono.getJSONArray("actors")

for(inti=0i<jarray.length()i++){
JSONObjectobject=jarray.getJSONObject(i)

WeuseanAsyncTasktogettheJSONData.OurrealdatastartswithaJSONObjectwhichwe
saveinjsonovariable.NextwehaveaJSONArraythatwestoreinjarrayvariable.Afterthatwe
havemultipleJSONObjectswhichwecanfetcheasilyusingafororforeachloop.Wecangetthe
valueoftheobjectsusingtheirkeys,forexample:Togetthenameoftheactorweusethekey
name

object.getString("name")//givesusthenameofactorfromthecurrentJSONObject

5.CreatinganewAndroidProject
OpenEclipseandClickFile>New>AndroidApplicationProject.Packagenameusedinthe
projectiscom.wingnity.jsonparsingtutorial
Addoneclassfile:RightclickyourprojectselectNew>Class,nameitasActors.java
ImagebelowshowshowdatawillbedisplayedintheListView:

5.CreatingaModel
ThisclassworksasaModeltosavetheJSONdataandthenprovidingthatdatabacktothe
CustomizedListView.Ihavedefinedallthekeysintheclassandaddedaconstructorofthe
Actorsclassandgettersandsettersforeachkey.

packagecom.wingnity.jsonparsingtutorial
publicclassActors{
privateStringname
privateStringdescription
privateStringdob
privateStringcountry
privateStringheight
privateStringspouse
privateStringchildren
privateStringimage
publicActors(){

//Gettersandsetters
publicStringgetName(){
returnname
}
publicvoidsetName(Stringname){
this.name=name
}
publicStringgetDescription(){
returndescription
}

6.Createrow.xmlforListView
Thisrow.xmlfilehelpsingivinganewlooktoourListView.EachrowofListViewisinflatedusing
thisxmlfile.

<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ImageView
android:id="@+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:src="@drawable/ic_launcher"/>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

7.CreatinganAdapterforListView
Addonemoreclassfile:RightclickyourprojectselectNew>Class,nameit
asActorAdapter.java
ThisclasscustomizetheListViewandinserttheJSONdataintheListView.Inthepublic
constructor,wewillinflaterow.xmltoshowitintotheListView.WearealsousinganAsyncTask
todownloadtheimagesseparately.

packagecom.wingnity.jsonparsingtutorial

importjava.io.InputStream
importjava.util.ArrayList

importandroid.content.Context
importandroid.graphics.Bitmap
importandroid.graphics.BitmapFactory
importandroid.os.AsyncTask
importandroid.util.Log
importandroid.view.LayoutInflater
importandroid.view.View
importandroid.view.ViewGroup
importandroid.widget.ArrayAdapter
importandroid.widget.ImageView
importandroid.widget.TextView

publicclassActorAdapterextendsArrayAdapter<Actors>{
ArrayList<Actors>actorList
LayoutInflatervi
intResource
ViewHolderholder

publicActorAdapter(Contextcontext,intresource,ArrayList<Actors>objects){

8.InternetPermission
AlsowewillmakeHTTPcallstofetchourJSONdataandforthatwewillneedtheINTERNET
permissioninourAndroidManifest.xmlfile.

<usespermissionandroid:name="android.permission.INTERNET"/>
AndroidManifest.xmlFileCode:

<?xmlversion="1.0"encoding="utf8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.wingnity.jsonparsingtutorial"
android:versionCode="1"
android:versionName="1.0">

<usessdk
android:minSdkVersion="8"
android:targetSdkVersion="18"/>
<usespermissionandroid:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.wingnity.jsonparsingtutorial.MainActivity"
android:label="@string/app_name">
<intentfilter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intentfilter>
</activity>
Downloadsourcecode
Postyourquestions,feedbackorsuggestionsbelow.Hopeyouhaveenjoyedthisarticle.

You might also like