Android uses HttpURLConnection to obtain JSON and UI updates. androidjson Parsing

Source: Internet
Author: User

Android uses HttpURLConnection to obtain JSON and UI updates. androidjson Parsing
In this example, the combination of HttpURLConnection + Thread + Handler is used. After obtaining JSON data through HttpURLConnection in the new Thread, the UI is updated in the Handler.






You can also use HttpClient and AsyncTask to implement this function.


No more code is available.






------------------------------- Split line ----------------------------------------


Activity_main.xml (there is only one simple TextView for displaying and updating the Text after obtaining the JSON)




<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: id = "@ + id/container" android: layout_width = "match_parent" android: layout_height = "match_parent" tools: context = "com. zb. json_text.MainActivity "tools: ignore =" MergeRootFrame "android: background =" # f1f1f1 "android: orientation =" vertical "> <TextView android: id =" @ + id/textview_01 "android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = ". It will always arrive... "/> </LinearLayout>

 


MainActivity. java




Package com. zb. json_text; import java. io. byteArrayOutputStream; import java. io. inputStream; import java.net. httpURLConnection; import java.net. URL; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import org. json. JSONArray; import org. json. JSONObject; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. wi Dget. textView; public class MainActivity extends Activity {private TextView textview_01; private List <Map <String, String> slist; private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {switch (msg. what) {case 0: Map <String, String> map = slist. get (2); // example. You can obtain the value of textview_01.setText (map. get ("title"); // update UI break in handler; default: B Reak ;}}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); final String path = "http://m.lalas.cn/help/all_1.html? Format = json & size = 5 "; textview_01 = (TextView) findViewById (R. id. textview_01); new Thread () {// create a sub-Thread to perform the network access Operation public void run () {try {slist = getJSONObject (path); handler. sendEmptyMessage (0);} catch (Exception e) {e. printStackTrace ();}}}. start ();}/*** get the JSON data in the Network * @ param path * @ return * @ throws Exception */public static List <Map <String, string> getJSONObject (String path) throws handle T Ion {List <Map <String, String> list = new ArrayList <Map <String, String> (); Map <String, String> map = null; URL url = new URL (path); // using the HttpURLConnection object, we can obtain the webpage data from the webpage HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // The unit is millisecond, And the timeout value is set to 5 seconds conn. setConnectTimeout (15*1000); // The HttpURLConnection Object Requests the path through the HTTP protocol. Therefore, you need to set the request method. You can leave this parameter unspecified because the default value is get conn. setRequestMethod ("GET"); if (conn. GetResponseCode () = 200) {// checks whether the request code is 200. Otherwise, the request fails. InputStream is = conn. getInputStream (); // get the input stream byte [] data = readStream (is); // convert the input stream to a String group String json = new String (data ); // convert a string group to a string // data format: {"total": 2, "success": true, "arrayData": [{"id": 1, "name": "John" },{ "id": 2, "name": "Lee"}]} JSONObject jsonObject = new JSONObject (json ); // The returned data is of the Object type, so it can be directly converted into an Object int total = jsonObject. getInt ("cou Nt "); String keywords = jsonObject. getString ("keywords"); // contains an array of data. You can use getJSONArray to obtain the array JSONArray jsonArray = jsonObject. getJSONArray ("data"); for (int I = 1; I <jsonArray. length (); I ++) {JSONObject item = jsonArray. getJSONObject (I); // get each object int id = item. getInt ("id"); String title = item. getString ("title"); String description = item. getString ("description"); int time = item. getInt ("time "); Map = new HashMap <String, String> (); map. put ("id", id + ""); map. put ("title", title); map. put ("description", description); map. put ("time", time + ""); list. add (map) ;}} return list;} private static byte [] readStream (InputStream inputStream) throws Exception {ByteArrayOutputStream bout = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int len = 0; while (len = inputStream. read (buf Fer ))! =-1) {bout. write (buffer, 0, len);} bout. close (); inputStream. close (); return bout. toByteArray ();}}





Source Code address: http://download.csdn.net/detail/u011732740/8854953

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.