Thursday, October 1, 2015

[Android] Get and parse Json file from URL, available for v23 sdk

I found a nice example from codeofaninja.com to get and parse json from URL in android:

Simple Android JSON Parser Example Code with URL and Logcat Output

However, Some of the syntax do not support ApacheHttp Client anymore in v23 sdk so that example from codeofaninja doesn't work anymore.


And here i would like to share the code amended from example, which is referenced from the android official site:

JsonParser.java :
package com.example.app;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import org.json.JSONObject;
import org.json.JSONException;
import java.io.IOException;

import java.net.HttpURLConnection;
import android.util.Log;

public class JsonParser {
    final String TAG = "JsonParser.java";
    static InputStream inputStream = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONObject getJSONFromUrl(String urlSource) {
        //make HTTP request
        try {
            URL url = new URL(urlSource);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);
            inputStream = new BufferedInputStream(urlConnection.getInputStream());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Read JSON data from inputStream
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e(TAG, "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e(TAG, "Error parsing data " + e.toString());
        }

        return jObj;// return JSON String
    }
}
 And the MainAcitivity.java

package com.example.app;

import android.app.Activity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.example.app.JsonParser;

public class MainActivity extends Activity {

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

        // we will using AsyncTask during parsing
        new AsyncTaskParseJson().execute();
    }

    // you can make this class as another java file so it will be separated from your main activity.
    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

        final String TAG = "AsyncTaskParseJson.java";

        // set your json string url here
        String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";

        // contacts JSONArray
        JSONArray dataJsonArr = null;

        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... arg0) {

            try {

                // instantiate our json parser
                JsonParser jParser = new JsonParser();

                // get json string from url
                JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

                // get the array of users
                dataJsonArr = json.getJSONArray("Users");

                // loop through all users
                for (int i = 0; i < dataJsonArr.length(); i++) {

                    JSONObject c = dataJsonArr.getJSONObject(i);

                    // Storing each json item in variable
                    String firstname = c.getString("firstname");
                    String lastname = c.getString("lastname");
                    String username = c.getString("username");

                    // show the values in our logcat
                    Log.e(TAG, "firstname: " + firstname
                            + ", lastname: " + lastname
                            + ", username: " + username);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {}
    }
}
Example and source from
https://www.codeofaninja.com/2013/11/android-json-parsing-tutorial.html

Reference:
http://stackoverflow.com/questions/32153318/httpclient-wont-import-in-android-studio
http://android--examples.blogspot.hk/2015/05/how-to-parse-json-data-in-android.html
https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
https://developer.android.com/reference/java/net/HttpURLConnection.html

99 comments :

  1. Veryyyyy coooll!!! Thanks reallyyy i was looked for a json parser to apk 23 and not founded it, only was <23 haha, thanks really

    post data: you will know to make this json parser with params?

    ReplyDelete
  2. Nice!
    But how can you pass the parameters & set the method. whether is "POST" / "GET".

    ReplyDelete
  3. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.android app development training in chennai|Android Training institute in chennai with placement | Best Android Training in velachery

    ReplyDelete
  4. Well done! Pleasant post! This truly helps me to discover the solutions for my inquiry. Trusting, that you will keep posting articles having heaps of valuable data. You're the best! 
    Click here:
    angularjs6 Training in Chennai
    Click here:
    angularjs Training in online

    ReplyDelete
  5. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command
    Click here:
    Microsoft azure training in sollinganallur

    ReplyDelete
  6. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Devops training in sholinganallur

    ReplyDelete
  7. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.

    java training in marathahalli | java training in btm layout

    java training in jayanagar | java training in electronic city

    ReplyDelete
  8. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.

    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in chennai

    ReplyDelete
  9. I really appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thx again!
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete
  10. I think this is the best article today. Thanks for taking your own time to discuss this topic, I feel happy about that curiosity has increased to learn more about this topic. Keep sharing your information regularly for my future
    apple service center chennai
    apple service center in chennai
    apple mobile service centre in chennai
    apple service center near me

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Good to become visiting your weblog again, it has been months for me. Nicely this article that i've been waited for so long. I will need this post to total my assignment in the college, and it has exact same topic together with your write-up. Thanks, good share.

    Big Data Course

    ReplyDelete
  13. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page digital marketing course in singapore

    ReplyDelete
  14. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.
    big data course malaysia

    ReplyDelete
  15. Coin master is one of the famous and grossing games right now. you can spin the wheel and believe in fortune to get a lot of Spins. But you end up getting small amounts of spins. For those who are searching for Coin Master unlimited spins, this article is very useful to them. https://meditips.in/coin-master-free-spins/

    ReplyDelete
  16. I feel really happy to have seen your webpage and look forward to so many more entertaining times
    web design company in velachery

    ReplyDelete
  17. Awesome post sir,
    really appreciate for your writing. This blog is very much useful...
    For more details Click Here- Digital Marketing Course

    ReplyDelete
  18. thank you very much for share this wonderful article 토토사이트

    ReplyDelete


  19. Dubai video surveillance and surveillance system

    The best provider of CCTV installation services in Dubai
    We offer services at your doorstep. If you need a video surveillance camera, we will help you. We are dubai cctv installation , our engineers are certified by the dubai administration,
    Our security experts can provide all the details, we also offer video surveillance if you need bulk goods. We also offer office and home services.

    ReplyDelete
  20. I am glad to discover this post extremely valuable for me, as it contains part of data. I generally like to peruse the
    quality substance and this thing I found in you post. A debt of gratitude is in order for sharing. 메이저사이트


    ReplyDelete
  21. very nice and great thank you This type of informational article helps many people. Hope you'll bring this type of post again 슬롯사이트.

    ReplyDelete
  22. Your Website is very good, Your Website impressed us a lot, We have liked your website very much.
    We have also created a website of Android App that you can see it.
    http://damodapk.com/
    http://seniorjacket.com/

    ReplyDelete
  23. Lovely post. Sports lovers will like this game 파워볼사이트

    ReplyDelete

  24. Great information!! Thanks for sharing nice blog.
    Data Science Course in Hyderabad

    ReplyDelete
  25. The way of you expressing your ideas is really good.you gave more useful ideas for us and please update more ideas for the learners.
    Java training in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Online Training

    ReplyDelete
  26. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.I am really happy with your blog because your article is very unique and powerful for new reader.Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training

    ReplyDelete
  27. I have to search sites with relevant information on given topic and provide them to teacher our opinion and the article.

    Simple Linear Regression

    Correlation vs Covariance

    Simple Linear Regression

    Correlation vs covariance

    KNN Algorithm

    ReplyDelete
  28. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.data science course in Hyderabad

    ReplyDelete
  29. I am really happy with your blog because your article is very unique and powerful for new reader.data science course in Hyderabad

    ReplyDelete
  30. Very nice blogs!!! i have to learning for lot of information for this sites…Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing, data science online course

    ReplyDelete
  31. Wonderful article, very useful and well explanation. Your post is extremely incredible. I will refer this to my candidates...data science courses

    ReplyDelete
  32. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    Simple Linear Regression

    Correlation vs Covariance

    bag of words

    time series analysis

    ReplyDelete
  33. I'm a long-serving digital marketing professional and full-service as a social media marketing manager. I'm offering services at a competitively low cost. I have experience in keyword research, Article writing or Rewriting, Guest posting, B2B Lead Generation , Data Entry ,link building, web 2.0 backlink ,
    Video submission. I have 5 years of experience in the field and are assured of delivering High Quality and manual work. I have my own site name as AbidhTech.

    ReplyDelete
  34. Thank you for writing can I say something for those people who are looking for one of the best website to find details about latest update
    Mobile And Computer Par Gmail Se Message Kaise Bhejte Hai

    ReplyDelete
  35. I think this is among the most vital information for me. And i am glad reading your article.
    Thanks!
    visit my sites Please.

    1) http://15998271.com/bbs/board.php?bo_table=bbs_02&wr_id=36183
    2) http://kocac.org/board/bbs/board.php?bo_table=QnA&wr_id=1246729&page=0&sca=&sfl=&stx=&sst=&sod=&spt=0&page=0
    3) http://tspon.com/bbs/board.php?bo_table=1&wr_id=74571
    4) http://sangreen.co.kr/mobile/bbs_view.html?bo_table=photo&wr_id=5125&page=1
    5) http://feeldoor.co.kr/gnuboard4/bbs/board.php?bo_table=feeldoor_estimate&wr_id=157039&page=0&sca=&sfl=&stx=&sst=&sod=&spt=0&page=0

    ReplyDelete
  36. Hi! I understand this is kind of off-topic but I had to ask. Does managing a well-established blog like yours require a lot of work? I am completely new to operating a blog however I do write in my diary daily. I’d like to start a blog so I can share my personal experience and views online. Please let me know if you have any kind of suggestions or tips for new aspiring blog owners. Thankyou!

    What your stating is absolutely genuine. I know that everyone ought to say the identical factor, but I just feel that you set it in a way that absolutely everyone can realize. I also adore the photographs you set in here. They fit so nicely with what youre hoping to say. Im guaranteed youll attain so numerous people today with what youve got to say.

    These moles may possibly be irregular in size and color and that is what can make them this type of wellness danger. When you have been born with this particular problem you might also be more likely to develop Melanoma and so you might have to get the required precautions with regards to protecting your pores and skin and your well being.

    This is such a great post, and was thinking much the same myself. It’s certainly an opinion I agree with.

    Enjoyed this article. I believe that the writer took an rationale perspective and made some pivotale ideas.

    Aw, it was an extremely good post. In notion I must place in writing such as this moreover – spending time and actual effort to make a really good article… but so what can I say… I procrastinate alot and no means apparently go completed.

    You need to experience a tournament for just one of the most effective blogs on the web. I’ll recommend this page!

    Thank you for yet another great informative article, I’m a loyal reader to this blog and I can’t stress enough how much valuable information I’ve learned from reading your content. I really appreciate all the hard work you put into this great site.

    When I originally commented I clicked the -Notify me when new comments are added- checkbox and now when a comment is added I buy four emails concentrating on the same comment. Perhaps there is in any manner you can get rid of me from that service? Thanks!

    ReplyDelete
  37. Nice Post. You are Share great post and keep posting.

    breakup-shayari

    https://allshayaristatus.in/breakup-shayari/

    ReplyDelete
  38. This is a fabulous post I seen because of offer it. It is really what I expected to see trust in future you will continue in sharing such a mind boggling post
    data scientist training and placement

    ReplyDelete
  39. 이 웹 로그가 너무 좋아서 즐겨 찾기에 저장되었습니다. 듣기에 정말 반가 웠습니다. 여기에 많은 훌륭한 포인트를 제시하여 귀하의 기사를 몇 번 읽었습니다.
    업데이트에 감사 드리며 행운을 빕니다.
    내 사이트도 방문하십시오.파워볼 놀이터
    많은 정보를 얻을 수 있습니다.

    ReplyDelete
  40. I would like to thank you for the efforts you have made in writing this article. I am hoping for the same best work from you in the future as well..
    data scientist training and placement in hyderabad

    ReplyDelete
  41. Interesting blog. Full of knowledge. If you are searching for Write my essay then go for the best writing platform available online.

    ReplyDelete
  42. Nice Post Your content is very inspiring and appriciating I really like it please visit my site for Satta King and Satta king Charts or for super fast result satta matka also checkout my site Lottery Sambad you can also visit out site satta king result visit us on satta king faridabad satta king ghaziabad my new site SattaKing

    ReplyDelete
  43. Coimbatore House For Sale , Land For Sale - Buy, Sell, Rent Properties In Coimbatore
    Search, buy, rent, lease, Residential and Commercial real estate properties in Coimbatore Tamil Nadu.
    best-villa-projects-in-coimbatore
    Home1chennai

    ReplyDelete
  44. Trade Capital Options: IC Markets Offers Customers The Opportunity To Trade A Wide Array Of Assets And Financial Instruments With A 30p Per Lot Commission.

    ReplyDelete
  45. what an useful post you share here. Thanks and keep up your work!
    anime wallpaper 4k
    canlı saray
    reels indir

    ReplyDelete
  46. Is There A Link That You Could Share That Would Give Us A More Detailed Rundown On How VT MARKET LOGIN Works?

    ReplyDelete
  47. Automated Forex Trading : tradeatf Is An Automated Forex Investing Software. It Is An Algorithmic Trading Software That Provides Automated Forex Trading Signals.

    ReplyDelete
  48. قیمت ویتامین لب واقعا ارزان و مقرون به صرفه است.

    ReplyDelete
  49. Very good info. Lucky me I discovered your site by chance (stumbleupon). I have saved it for later! Here is my web site:Satta King

    ReplyDelete
  50. Perfect blog to read in free time to gain knowladge.Satta King

    ReplyDelete
  51. thanks a lot for sharing, this really helped in my workSattaking

    ReplyDelete
  52. I loved to read blogs and your blog is one of the best blog.Sattaking

    ReplyDelete
  53. If You Are Looking For Forex Broker? Read This Review And Find Out How Much I've Enjoyed My Experience With Meta Fx Global

    ReplyDelete
  54. That Is Very Interesting, You Are An Excessively Skilled Blogger. Stay In Control Of Your Online Trades With AximTrade Login, A Cloud-based Online Trading Platform.

    ReplyDelete
  55. That Is Very Interesting, You Are An Excessively Skilled Blogger. Stay In Control Of Your Online Trades With AximTrade Review Login, A Cloud-based Online Trading Platform.

    ReplyDelete
  56. AximTrade Review Is A Forex And Cfd Broker. It Offers Trading In Currency Pairs, Commodities, Indices, And Shares. It Also Provides A Range Of Tools, And 24/7 Customer Service. Sign Up For AximTrade Login Account Today!

    ReplyDelete
  57. XM REVIEW If You Are A Beginner, Check Out Our Guide On How To Open An Account With XM. They Offer Copy Trading Where You Can Copy The Trades Of Successful Traders.

    ReplyDelete
  58. Want To Trade Forex With AVATRADE REVIEW ? Read This Blog First To Find Out About The Best Forex Trading Conditions. We Review The Most Popular Forex Brokers And Tell You What You Need To Know.

    ReplyDelete
  59. It was a wonderful chance to visit this kind of site and I am happy to know. Thank you so much for giving us a chance to have this opportunity..
    data science coaching in hyderabad
    It was a wonderful chance to visit this kind of site and I am happy to know. Thank you so much for giving us a chance to have this opportunity..
    data science coaching in hyderabad

    ReplyDelete
  60. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.
    data analytics courses in hyderabad with placements

    ReplyDelete
  61. This is a fabulous post I seen because of offer it. It is really what I expected to see trust in future you will continue in sharing such a mind boggling post data scientist course in surat

    ReplyDelete
  62. The top six ended up in Final A group, and the rest will be in Final B. The teams will then play five more matches within their own group in the split phase to wrap up the year. Gangwon secured the sixth and final ticket to Final A and will be in the upper group for the first time in three years.
    사설토토
    먹튀검증
    토토검증
    슬롯사이트
    카지노사이트
    먹튀폴리스
    슈어맨

    ReplyDelete