Tweet
Mar
24
2014

Android JSON Parsing and Image Loading Tutorial

In this tutorial we will learn how JSON parsing is done in Android, also we will load the images from URL to display them in a customized List View of Android.

Download source code

 



 

1. What is JSON?

For those who don’t know what is JSON, a quick explanation is given below:

  • JSON stands for JavaScript Object Notation
  • It’s a light-weight data interchange format
  • It is easy for humans to read and write and easy for machines to parse and generate. 

JSON Explanation

JSON is made up of three parts:

  1. Key/Value Pairs separated by colons (:)
    • “firstName” is KEY, “John” is VALUE – in the above example
  2. JSON Arrays
    • JSON Array is a collection of JSON Objects and it is represented by square brackets [ ]
    • In the above example we have 1 JSON Array named as “employees”
  3. JSON Objects
    • JSON Objects can contain other objects or JSON Arrays and it is represented by curly brackets { }
    • In the above example we have 3 JSON objects, 1st JSON Object contains a JSON Array only (“employees”), the other two JSON Objects contain KEY/VALUE Pairs (“John Doe” and “Anna Smith”).

 

2. Real JSON Data

Now that you know what JSON is, let’s look how our real data looks like which we will parse in this tutorial.

Our JSON is hosted on the following url: http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors

3. How it works?

Android JSON Parsing Steps

Step 1. We will execute an AsyncTask in our MainActivity.java file to fetch the JSON data from the server.

Step 2. Server will send the JSON data back to MainActivity.java

Step 3. After fetching the JSON, we kind of store that temporarily in our Actors.java class by creating new objects for each Actor.

Step 4. We create an ActorAdapter class to pass this data to the ListView

Step 5. This is how our final ListView will look like

4. JSON Parsing

We use an AsyncTask to get the JSON Data. Our real data starts with a JSON Object which we save in jsono variable. Next we have a JSON Array that we store in jarray variable. After that we have multiple JSON Objects which we can fetch easily using a for or foreach loop. We can get the value of the objects using their keys, for example: To get the name of the actor we use the key “name”

5. Creating a new Android Project

Open Eclipse and Click File -> New -> Android Application Project. Package name used in the project is com.wingnity.jsonparsingtutorial

Add one class file: Right click your project select New -> Class, name it as Actors.java

Image below shows how data will be displayed in the ListView:

A customized ListView

5. Creating a Model

This class works as a Model to save the JSON data and then providing that data back to the Customized ListView. I have defined all the keys in the class and added a constructor of the Actors class and getters and setters for each key.

6. Create row.xml for ListView

This row.xml file helps in giving a new look to our ListView. Each row of ListView is inflated using this xml file.

7. Creating an Adapter for ListView

Add one more class file: Right click your project select New -> Class, name it as ActorAdapter.java

This class customize the ListView and insert the JSON data in the ListView. In the public constructor, we will inflate row.xml to show it into the ListView. We are also using an Async Task to download the images separately.

8. Internet Permission

Also we will make HTTP calls to fetch our JSON data and for that we will need the INTERNET permission in our AndroidManifest.xml file.

AndroidManifest.xml File Code:

Download source code

Post your questions, feedback or suggestions below. Hope you have enjoyed this article.

Related Posts

About the Author: Wingnity Team

We offer online training courses for Android and many other courses. If you are interested and want to learn advance technologies differently, shoot us an email at support@wingnity.com and we will make it happen.

  • jayceed Deyro

    Ive been looking for this for about 1 week now… and im really thankful for it… and do you have a tutorial how to get the json parse to your app using the JSON API plugin?… or is it possible to get a list of all the post in a specific category or subcatergory from wordpress to android?..

    • wingnity

      Thanks Jayceed Deyro for your wonderful comments.
      Right now we don’t have any tutorial for JSON API plugin but we will notify you if we publish one. Make sure that you subscribe to our YouTube Channel to get the latest updates.

      YouTube: https://www.youtube.com/wingnity
      Facebook: https://www.facebook.com/wingnity

      Regarding your question:

      You can create a small web service in PHP for your Word Press website to fetch the post of a specific category in JSON format and then parse it Android App.

      Thanks,
      Winginty Team.

      • jayceed Deyro

        Thanks… for such wonderful tutorial.. I have a very simple app but the things i want to implement are very hard to understand because im still a newbie with no programming background… I know it is very simple to implement some of my ideas but the resources about tutorials in the internet regarding android is limited. I hope you can still create more Video tutorial.. Thanks alot. and ive already subscribe in your Youtube channel.. I still dont know why my image is not loading and i got Protocol not found: this is hard.. ^_^a… tabhost with listview perhaps in your next tutorial?..or fragment with list view from JSON?.. ^_^a…

        • wingnity

          Thanks Jayceed.

          • Nicu

            hello , i have a question, i can parse this json :

            private String strJSONValue = “{ “Android” :[{“song_name”:”Gimme Dat”,”song_id”:”1932″,”artist_name”:”Sidney Samson (Feat. Pitbull & Akon)”},{ “song_name”:”F-k The Money (Remix)”,”song_id”:”73″,”artist_name”:”B.o.B. (Feat. Wiz Khalifa)”}] }”;

            like this :

            String OutputData = “”;

            JSONObject jsonResponse;

            try {

            /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/

            jsonResponse = new JSONObject(strJSONValue);

            /***** Returns the value mapped by name if it exists and is a JSONArray. ***/

            /******* Returns null otherwise. *******/

            JSONArray jsonMainNode = jsonResponse.optJSONArray(“Android”);

            /*********** Process each JSON Node ************/

            int lengthJsonArr = jsonMainNode.length();

            for(int i=0; i < lengthJsonArr; i++)

            {

            /****** Get Object for each JSON node.***********/

            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

            /******* Fetch node values **********/

            int song_id = Integer.parseInt(jsonChildNode.optString("song_id").toString());

            String song_name = jsonChildNode.optString("song_name").toString();

            String artist_name = jsonChildNode.optString("artist_name").toString();

            OutputData += "Node : nn "+ song_id +" | "

            + song_name +" | "

            + artist_name +" nn ";

            //Log.i("JSON parse", song_name);

            }

            /************ Show Output on screen/activity **********/

            showMessage(OutputData, "STunes") ;

            } catch (JSONException e) {

            showMessage("STunes", "Error");}

            }

            My question is how i cand parse this json :

            {"music":[{"external_ids":{"isrc":"GBAMC9800041","upc":"731453835122"},"play_offset_ms":117680,"external_metadata":{"deezer":{"album":{"id":1939301},"artists":[{"id":119}],"genres":[{"id":132}],"track":{"id":20309341}}},"title":"Whiskey In The Jar","duration_ms":"0","album":{"name":"Garage Inc."},"acrid":"01272c3cd88a9b38e268ed038989b885","genres":[{"name":"Pop"}],"artists":[{"name":"Metallica"}]}],"timestamp_utc":"2015-08-13 05:43:55"}

            I can't find an answer

  • Toyin

    Hello,I’d like to say thank you for the tuts,but please where will i implement an onclicklistener for the items in the list. I will like to start a new activity(and put the details as extras). Have tried, but i keep getting different errors. Thanks

    • Rahul Verma

      Hello Toyin,

      Thanks.

      You can set listeners inside getView() method in the adapter, below is the code of how to do it. We are passing the context with Adapter Constructor, so you can save it there.

      Context myContext;

      public ActorAdapter(Context context, int resource, ArrayList objects) {

      super(context, resource, objects);

      vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      Resource = resource;
      actorList = objects;
      myContext = context;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {

      Intent intent = new Intent(myContext, AnotherActivity.class);
      intent.putExtras(“country”, actorList.get(position).getCountry());

      holder.tvCountry.setOnClickListener(new View.OnClickListeners(){

      @Override
      public void onClick(View v){

      // start the new activity here
      startActivity(intent);
      }
      });

      }

      Hope this will work, Let me know if this helps.

      Regards,
      Rahul

      • Toyin

        Thank you rahul, I was able to solve it with help from stackoverflow. The onclick listener was implemented in the postexecute method. Thanks for the response.

        • Rahul Verma

          OK, Great.

          I misunderstood your question. I was under the impression that you want to set listeners on the individual items present in the list like TextViews or Images so I replied accordingly.

          As I know, you can find the setOnItemClickListener on the list which is present in the code. Its not necessary to put the listener inside onPostExecute() method, you can set that inside the onCreate() where you are initializing your ListView like I did, or it may also be possible that I still don’t get the problem you were facing. :)

          Just in case here is the code:

          @Override

          protected void onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);

          setContentView(R.layout.activity_main);

          actorsList = new ArrayList();

          new JSONAsyncTask().execute(“http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors”);

          ListView listview = (ListView)findViewById(R.id.list);

          adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);

          listview.setAdapter(adapter);

          listview.setOnItemClickListener(new OnItemClickListener() {

          @Override

          public void onItemClick(AdapterView arg0, View arg1, int position,

          long id) {

          // TODO Auto-generated method stub

          Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();

          Intent intent = new Intent(getApplicationContext(), AnotherActivity.class);

          intent.putExtra(“key_name”, actorsList.get(position).getName());

          intent.putExtra(“key_country”, actorsList.get(position).getCountry());

          intent.putExtra(“key_spouse”, actorsList.get(position).getSpouse());

          startActivity(intent);

          }

          });

          }

          Regards,
          Rahul

  • Aman

    Hi Rahul,
    Thanks for this tutorial. But I am having a problem loading the content of this app. I downloaded the code exactly the one you have given and tried to run on my galaxy S4 after clean and build. It loads the application with no error but doesn’t shows anything in it. So could you please help it.

    Thank You.

    • Aman
      • wingnity

        Hi Aman,

        Thank you for contacting us.
        Include this one line inside your onPostExecute() method.

        adapter.notifyDataSetChanged();

        Also, we have updated the code and you can download it again to learn how to display a progress dialog while the content is being loaded.

        Cheers,
        Wingnity Team.

        • Aman

          Thank You.

  • guytrx

    Very nice tuts – thanks alot – it realy help me to understand specialy about the “downloading the image!!! ”
    but i have 1 q please : how can i improove the IMAGE STUFF eith File Chache Dir ?
    internal and external storage for the images?

  • Anju

    Hey,, Nice tut.. Thank you :). I want to implement this in fragments.. I tried to implement. but its getting force close… can you help me with this?? Please…

  • Anju

    Sorry… It was my mistake… Your Tut is awsome !!!!

    • wingnity

      You are welcome Anju.

      • Ibrahim Ahmed Alshareif

        can you upload the php source code

        • word

          -create a php file.
          -upload through FTP filemanager on a server. (upload 000webhost)
          -create an array of data and encode in json.
          -try this out

      • Jojo Antony

        How can I get data from database using this.Or Will you tell me how to add data to json file

  • Milky

    Hi Wingnity

    I have a json without array name.
    Your tutorial is json with array name.
    “JSONObject jsono = new JSONObject(data);
    JSONArray jarray = jsono.getJSONArray(“actors”); ”
    May i ask what am i supposed to do? i tried to modify it to
    ” JSONArray jarray = new JSONArray(data); ” . However, it crashed my app.

    Thank you.

    • wingnity

      Try fetching that json array with index if that doesn’t have a name:
      JSONArray jarray = jsono.getJSONArray(0);

      Hope this will help.

      • Guest

        It gave me error.

      • Milky

        It gave me error under getJSONArray(0) .

        • wingnity

          You need to share the structure of your JSON for us to give you the correct solution.
          However you can try this:

          JSONArray jarray = jsono.getJSONArray(“”);
          leaving it empty, that will fetch the array for you.

          • Milky

            That doesnt work either. The application crashed.

            Sorry >< i should had given you my JSON structure earlier.
            This is my JSON:
            [
            {
            "event_id": "EV00000001",
            "event_title": "SIT Movie Night",
            "event_desc": "The private screening of "Captain America: The Winter Soldier" .
            "start_date": "07 Jul 2014",
            "end_date": "07 Jul 2014",
            "start_time": "18:30",
            "end_time": "21:30",
            "location": "Grand Golden Village",
            "picture_path": "sitmovienight.png",
            "small_picture_path": "movie_small.jpg",
            "require_registration": "Y",
            "quantity_allowed": 1,
            "quantity_left": 1
            },
            {
            "event_id": "EV00000002",
            "event_title": "SHS Movie Night",
            "event_desc": "The private screening of "Captain America: The Winter Soldier" .
            "start_date": "15 Aug 2014",
            "end_date": "15 Aug 2014",
            "start_time": "18:30",
            "end_time": "21:30",
            "location": "The Grand Cathay",
            "picture_path": "sitmovienight.png",
            "small_picture_path": "movie_small.jpg",
            "require_registration": "Y",
            "quantity_allowed": 1,
            "quantity_left": 1
            }
            ]

            • wingnity

              Your json is starting directly with JSONArray. So you need to start like this:

              JSONArray array = new JSONArray(data);
              JSONOBject obj = array.getJSONObject(index);

              Please watch all the videos of this tutorial.
              Regards,
              Rahul.

              • Milky

                Sorry for the super late reply!
                Thanks for solving my problem :)

              • Martin Cvetko

                So you insert the

                JSONArray array = new JSONArray(data);
                JSONOBject obj = array.getJSONObject(index);

                before the for loop and then what?

                best regards, Martin

  • zull

    Hi wingnity, why everytime i scroll list view image always change? that means image always redownload right?

    • Ravi

      Yes, Image is being downloaded every time. If you see though the programming perspective, you have written code for downloading the image and recycling the views if they go out of the view, that means images will get downloaded whenever a view will get recycled. Generally we use caching so that images don’t get downloaded again and again. That would be too much for this basic parsing tutorial. Nice post though.

  • JT

    Great tutorial, thanks!

    How’s it different to use HttpUrlConnection vs HttpClient?

    • wingnity

      Hi JT,

      Both are similar however HttpUrlConnection is less buggy than HttpClient. On the other hand HttpClient comes handy with cookies, authentication and connection management etc.

      HttpClient was great and had fewer bugs in Android version 2.2 and earliar, but for newer versions it is suggested that you should use HttpUrlConnection.

      Hope this will help.

      Regards,
      Rahul.

  • Quirpy

    Thanks for a really great tutorial.

    • silentmind

      do you know how to host my own json and pass the url in app , so that i can pass my data instead of using the one giving here.

  • adi

    how to create my json hosted url ?
    please do reply

  • Aloe

    What if my array does not have an array name, how would the class be modified?

  • http://www.dianagung.com Agung

    why the ImageView load randomly? And how to solve that, Sir?

    • http://amanhaa.com ali dincergok

      can u solve that problem ?

    • http://www.msentri.co.za Sandile Mazibuko

      same to me it load randomly not sure why it does that….can you please advice

      • Shaggy

        (Answered in an earlier discussion..)
        Include this one line inside your onPostExecute() method.

        adapter.notifyDataSetChanged();

    • Jayakumari

      Change the property “android:layout_height” to “fill_parent” of ListView in activity_main.xml. This solved the image shuffling issue for me.

      • Alam

        I changed it to “Fill_parent” but not worked.

        • thiwanka

          set image view height with fix dp.

        • vikas singh

          #Alam, Did u fix this problem if yes then please tell me how..

  • guytrx

    hello everybody: it is great tutorial- help me alot to understand, BUT, for some reason I CANOT GET THE IMAGES FROM SERVER: I USE LOCAL HOST (may be this the prob), but when i use the “http.. from the tutorial, its work perfect.
    any seggestion???

  • peter

    The problem am facing now is making same JSON format as yours in Mysql and php.Can you help.

  • peter

    This is the JSON format I have but it cannot fetch.
    [{“message”:”what is the main economic
    activity…”,”status”:”false”},{“message”:”our main economic activity is
    fishing..”,”status”:”true”}]

    • Kaow Km

      me too

  • peter
  • peter

    //my php code//

    //my code//

  • Serial

    Hi, before I forget..great tutorial..

    Now..please..
    Can someone tell me where in the in code is the loop or that thing that defines the number of lists (items) in the listview..

    In the ActorAdapter I used this to make a search:

    ….
    String search = actorList.get(position).getName().toString();
    if(search.contains(“Brad”)){
    holder.tvName.setText(“Brad Pitt”);

    ….

    Now the first list (item) is a “description” of Brad Pitt, but then I get 5 more lists with the default (Tom cruise) description..
    In this case i would like just one list -> Brad Pitt

    I hope I was clear enough.. thx for any help

  • Brayan Muñoz Campos

    Hi ! Because the image is always loaded when the listivew moves ?? Pls, answer me brayan.munoz.2306@gmail.com

  • guytrx

    Hi – SORRY I CANNOT GET THE IMAGE FROM URL
    with the url from the tutorial it working perfect, but with my url it dont show the images in the listview (by the way – with UniversalImageLoader My url works perfect!)

    • Rose Caz

      Can you help me with that please…

  • twijukye vascubrian

    where is php files

  • rajeev

    Hi .. i tried your tutorial … it working fine …Except the imageView..
    When i scroll down the imageview showing images of another list item..
    i.e. in place of brad pit’s image it’s showing image of angelina jolie ..
    But after some time it shows brad pit’s image. same problem occurs when i scroll up.can we correct it??

    ie. i want to show image instantly when i scroll down or up . how to do it ?
    thanks in advance. :)

  • Rose Caz

    It doesnt work on me T___T
    log cat says”Could not preload class for phone policy: com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback”

  • aswin

    hi….. i downloaded your code and tried it but it is not displaying anything… can you tell me what is the prob ???

  • Bassam

    thank you great job

  • Perez

    Thanks a lot bro!!

  • Ibrahim Ahmed Alshareif

    hey thank you , Nice tut can you upload the php source code

  • mahmoud

    why the syncclass.execute(url);
    dosn’t work with me
    there’s always an error

  • Dipen

    This Tutorial is very useful for my Project point of view.

  • Rana Saqib Manjj

    Hi !! Wingnity team…. I face a problem that is ….. as like you used 8 components like name,description etc…. we also have 8 components but i also only 3 used in my xml file….. image and 2 textView used all in project .. how ??? please reply me as soon as possible….. thanx

  • Tiyan Altair Cyrus

    hey guys,, how to filter listview in this projects??

    • http://www.wingnity.com/ Wingnity Team

      Hi Tiyan

      To show filtered items in ListView, you have to change the data source.

      For example if you have a list of items containing all items then make
      another list and add only those items in that which you want to display
      and pass the list to the adapter.

      Hope this will solve your problem.

      • Sanyog Nishandar

        somebody pls helpme with making of http calls in newer API,

        please give me a replacement for the below code s this code is deprecated in newer version

        HttpClient client = new Default HttpClient();

        HttpPost post = new HttpPost();

        HttpResponse response = client.execute(post);

        int status = response.getStatusLine().getStatusCode();

        if (status == 200)

        {

        HttpEntity entity = response.getEntity;

        String data = EntityUtils.tostring(entity);

        }

  • Rana Saqib Manj

    HI !!! I used ListView ….. but not show in emeulator at run time…..

    • http://www.wingnity.com/ Wingnity Team

      Hi Saqib,
      Maybe your data source doesn’t have any items in it or it could be anything.

      Can’t say anything without examining code.

    • nadeem yousaf

      run it on android real device and make sure device connected to internet

  • Farhal Ansari

    can you please upload the php code ?

  • tim jack

    Helpful… tutorial… How to POST data (Name,Age,Hight,B’thDay).. in JSON.. which update randomly on apps.

    wait your ans..

    • http://www.wingnity.com/ Wingnity Team

      Hey Tim,

      Thanks for taking out the time to comment and ask question, but unfortunately our question is not clear to us.

      But to add more value to my reply; i’d like to add that for posting
      data on server, you have to create a web service which can accept data
      and save it into database eventually. HttpPost class is used for posting
      data in Android.

      Regards, Wingnity Team

      • tim jack

        Ohh… thanks for Reply… after Googling(Search_On_Google) i cleared my Query…

        i can post a data on server via WebServices … create a Php page use Get/Post method.. “echo _ encode JSON” … and a URL set.. in our android apps.. thanks.

        i was question in this tut..how to came JSON data on URL.. and now is cleared.. thanks.. thanks…. :)

        and please Update more tutorials… i waited..

  • PULKIT PAHWA

    Thankyou. I have tried many of the resources available over the internet, but none worked.
    It worked like charm

  • Urnish Makwana

    First of all thanks a lot for very nice tutorial which is easy to understand and simple. I have used your project as reference which works perfectly but I have issue with displaying Images from JSON. the images are not loaded instantly and fast and have to wait for several time. Would you like to share some solution.? is their any good library to display images quickly.I want to display images in listview.

  • Bruno Cardoso

    how can i do this with pictures on the drawable folder and an id from a local json? can any one help me? thanks

  • Simran Kaur

    i have an api which contains random data, like in facebook. how to parse that json file

  • Zaid Qureshi

    Hey please upload the php source code

  • Shilpa

    Nice tutorial..

  • Ali

    When Scrolling my loaded images are hiding.

  • Sharath kumar

    Great work.thanks alots! Why the image gets refreshed everything when i even scroll up and down?

  • Jojo Antony

    How can I get data from database using this.Or tell me how to add data to json file

  • http://amanhaa.com ali dincergok

    thanks for sharing
    but why all images reloading each scroll?

  • Basu

    After downloading the source code, how to use it sir?(I am new to this) also there is no xml file for main activity in this page.

    Thanks.

    • Basu

      The adt opens, but not this app.

      • Basu

        I got it, the zip file was opening with adt when i doubled clicked it, I changed it to winrar, and I got the project.

    • Android geek

      package com.wingnity.jsonparsingtutorial;

      import java.io.IOException;
      import java.util.ArrayList;

      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.client.HttpClient;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.apache.http.util.EntityUtils;
      import org.json.JSONArray;
      import org.json.JSONException;
      import org.json.JSONObject;

      import android.app.Activity;
      import android.app.ProgressDialog;
      import android.content.Intent;
      import android.net.ParseException;
      import android.os.AsyncTask;
      import android.os.Bundle;
      import android.view.View;
      import android.widget.AdapterView;
      import android.widget.Toast;
      import android.widget.AdapterView.OnItemClickListener;
      import android.widget.ListView;

      public class MainActivity extends Activity {

      ArrayList actorsList;

      ActorAdapter adapter;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      actorsList = new ArrayList();
      new JSONAsyncTask().execute(“your url is here”);

      ListView listview = (ListView)findViewById(R.id.list);
      adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);

      listview.setAdapter(adapter);

      listview.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView arg0, View arg1, int position,
      long id) {
      // TODO Auto-generated method stub
      Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
      }
      });
      }

      This code is needed to complete your main activity.

  • ankit

    how can we parse json in swipe view inside fragments.

  • https://hussainafridi.wordpress.com/ M Hussain Afridi

    Dear Sir. I want to Click on listview and then Open a new activity with detail of the related record… ?????

  • Rahul

    Sir , Can you code this with the use of VOLLY.jar because API 23 does not support HTTP class?

  • satish

    Nice tutorial very usefull

  • Rekz

    Working perfectly well, can you do another tutorial to get Solr JSON? Its format seems to be different from the usual JSON format

    • Rekz

      Take that back, this works perfectly well even with Solr

  • Jessica

    Thank you for your tutorial. It’s help me a lot!

  • jishnu

    Thank you for this turorial. can you post the php code ?. :)

  • Κάποιος Αναγνώστου

    Thanks for the very nice and comprehensive tutorial. May I ask you, how can we replace the lines:
    //——————>>
    HttpGet httppost = new HttpGet(urls[0]);
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httppost);

    in order to be compatible with android api 23?

    • Pankaj

      URL url = new URL(link);

      HttpURLConnection con = (HttpURLConnection) url.openConnection();

      InputStream in = con.getInputStream();

      StringBuilder sb = new StringBuilder();

      BufferedReader reader = new BufferedReader(new InputStreamReader(in, “iso-8859-1″), 8);

      String nextLine = “”;

      while ((nextLine = reader.readLine()) != null) {

      sb.append(nextLine + “n”);

      }

      str3 = sb.toString();

      • Sanyog Nishandar

        somebody pls helpme with making of http calls in newer API,

        please give me a replacement for the below code s this code is deprecated in newer version

        HttpClient client = new Default HttpClient();
        HttpPost post = new HttpPost();
        HttpResponse response = client.execute(post);

        int status = response.getStatusLine().getStatusCode();

        if (status == 200)
        {
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.tostring(entity);
        }

  • ss

    ArrayList actorsList;

    ActorAdapter adapter;

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

    new JSONAsyncTask().execute();

    ListView listview = (ListView) findViewById(R.id.list);
    adapter = new ActorAdapter(getApplicationContext(), R.layout.row,
    actorsList);

    listview.setAdapter(adapter);
    }

    adapter.notifyDataSetChanged();

  • ali

    its awesome

  • paramatma sharan upadhyay

    hello sir i have image url in json and text message in json . for this i have created custom class and i have to bind it into listview . now my question is that how i can show text message( json text) on the image (json url)

  • Sunder

    What is Status in MainActivity?please can you explain it?

  • aaaa00005

    can I use picasso for loading the image here? and how?

  • mudit

    Its giving runtime error ….I am using adt bundle package… Arent we suppose to define each class created in the manifest file?

  • Chirag thaker

    listview clicklistener not working, (working on fragments)

  • Bablu Basher

    can you send me source code for your web service as well i an unable to creat an exact json structure like you’s
    this is what i achived so far

  • Sanyog Nishandar

    somebody pls helpme with making of http calls in newer API,

    please give me a replacement for the below code s this code is deprecated in newer version

    HttpClient client = new Default HttpClient();

    HttpPost post = new HttpPost();

    HttpResponse response = client.execute(post);

    int status = response.getStatusLine().getStatusCode();

    if (status == 200)

    {

    HttpEntity entity = response.getEntity;

    String data = EntityUtils.tostring(entity);

    }

  • Shaggy

    I have used similar code in my application, but I want to cache to memory and file on download. Could you tell me how to do this?
    Thanks..

  • Anish

    Thank you so much Sir.I removed Async Task from adapter because images were shuffling before displaying.I downloaded all images at once and displayed.Thank you once again.

  • Asimina88

    Does this work on android with version above kitkat please?

  • Swanand Joshi

    Hello I am getting error on HttpGet httppost = new HttpGet(urls[0]);

    HttpClient httpclient = new DefaultHttpClient();

    HttpResponse response = httpclient.execute(httppost);

    // StatusLine stat = response.getStatusLine();

    int status = response.getStatusLine().getStatusCode();

    if (status == 200) {

    HttpEntity entity = response.getEntity();

    String data = EntityUtils.toString(entity);

    httpGet while working on android studio

  • lasthero

    Thank you very much for the greatest app and tut.
    I can’t load Korean language in the jason file.
    What can I do for that ?

    Thanks..^^

  • lasthero

    Thanks for the very nice app and comprehensive tutorial. May I ask you, how can we load Japanese language and Korean language.

  • anmol

    why status==200 reason??

  • phafpt.2006@yahoo.com

    I need file get_all_personal.php

  • vikas singh

    when i run this demoi n mobile then Unable to fetch data from server ..so how to solve it sir ?

  • mantena. manora

    Awesome.. Can anyone tell me how can i add spinner like this??

  • Mrunal

    ImageView load randomly And how to solve that?

  • Basil Benedict Victor

    How to do this process in a SplashScreen and then send it to the Main Activity.

  • eugene

    Many thanks for great tutorial!
    However ive got a encoding problem and wouldyou advise me how to solve encoding issue?
    Thanks in advance

Learn Android Now

Follow on G+