php - I have the error of parsing a JSON object to String in Android -


i wanted learn android in connection php , found code in web: demo web so, code works fine, when want select says there error when parsing json object string. give 3 parts of code. can see code in website adobe.

here have 2 codes:

public class jsonparser {      static inputstream = null;     static jsonobject jobj = null;     static string json = "";      // constructor     public jsonparser() {      }       public jsonobject getjsonfromurl(final string url) {          // making http request         try {             // construct client , http request.             defaulthttpclient httpclient = new defaulthttpclient();             httppost httppost = new httppost(url);              // execute post request , store response locally.             httpresponse httpresponse = httpclient.execute(httppost);             // extract data response.             httpentity httpentity = httpresponse.getentity();             // open inputstream data content.             = httpentity.getcontent();          } catch (unsupportedencodingexception e) {             e.printstacktrace();         } catch (clientprotocolexception e) {             e.printstacktrace();         } catch (ioexception e) {             e.printstacktrace();         }          try {             // create bufferedreader parse through inputstream.             bufferedreader reader = new bufferedreader(new inputstreamreader(                     is, "iso-8859-1"), 8);             // declare string builder parsing.             stringbuilder sb = new stringbuilder();             // declare string store json object data in string form.             string line = null;              // build string until null.             while ((line = reader.readline()) != null) {                 sb.append(line + "\n");             }              // close input stream.             is.close();             // convert string builder data actual string.             json = sb.tostring();         } catch (exception e) {             log.e("buffer error", "error converting result " + e.tostring());         }          // try parse string json object         try {             jobj = new jsonobject(json);         } catch (jsonexception e) {             log.e("json parser", "error parsing data " + e.tostring());         }          // return json object.         return jobj;      }       // function json url     // making http post or method     public jsonobject makehttprequest(string url, string method,             list<namevaluepair> params) {          // making http request         try {              // check request method             if(method == "post"){                 // request method post                 // defaulthttpclient                 defaulthttpclient httpclient = new defaulthttpclient();                 httppost httppost = new httppost(url);                 httppost.setentity(new urlencodedformentity(params));                  httpresponse httpresponse = httpclient.execute(httppost);                 httpentity httpentity = httpresponse.getentity();                 = httpentity.getcontent();              }else if(method == "get"){                 // request method                 defaulthttpclient httpclient = new defaulthttpclient();                 string paramstring = urlencodedutils.format(params, "utf-8");                 url += "?" + paramstring;                 httpget httpget = new httpget(url);                  httpresponse httpresponse = httpclient.execute(httpget);                 httpentity httpentity = httpresponse.getentity();                 = httpentity.getcontent();             }                     } catch (unsupportedencodingexception e) {             e.printstacktrace();         } catch (clientprotocolexception e) {             e.printstacktrace();         } catch (ioexception e) {             e.printstacktrace();         }          try {             bufferedreader reader = new bufferedreader(new inputstreamreader(                     is, "iso-8859-1"), 8);             stringbuilder sb = new stringbuilder();             string line = null;             while ((line = reader.readline()) != null) {                 sb.append(line + "\n");             }             is.close();             json = sb.tostring();         } catch (exception e) {             log.e("buffer error", "error converting result " + e.tostring());         }          // try parse string json object         try {             jobj = new jsonobject(json);         } catch (jsonexception e) {             log.e("json parser", "error parsing data " + e.tostring());         }          // return json string         return jobj;      } } 

the other class:

package com.example.mysqltest;  import java.util.arraylist; import java.util.hashmap; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; import android.app.listactivity; import android.app.progressdialog; import android.content.intent; import android.os.asynctask; import android.os.bundle; import android.view.view; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.listadapter; import android.widget.listview; import android.widget.simpleadapter;  public class readcomments extends listactivity {      // progress dialog     private progressdialog pdialog;      // php read comments script      // localhost :     // testing on device     // put local ip instead, on windows, run cmd > ipconfig     // or in mac's terminal type ifconfig , ip under en0 or en1     // private static final string read_comments_url =     // "http://xxx.xxx.x.x:1234/webservice/comments.php";      // testing on emulator:     private static final string read_comments_url = "http://10.0.2.2/webservice/comments.php";      // testing real server:     // private static final string read_comments_url =     // "http://www.mybringback.com/webservice/comments.php";      // json ids:     private static final string tag_success = "success";     private static final string tag_title = "title";     private static final string tag_posts = "posts";     private static final string tag_post_id = "post_id";     private static final string tag_username = "username";     private static final string tag_message = "message";     // it's important note message both in parent branch of     // our json tree displays "post available" or "no post available"     // message,     // , there message each individual post, listed under     // "posts"     // category, displays user typed message.      // array of of our comments     private jsonarray mcomments = null;     // manages of our comments in list.     private arraylist<hashmap<string, string>> mcommentlist;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         // note use read_comments.xml instead of our single_post.xml         setcontentview(r.layout.read_comments);     }      @override     protected void onresume() {         // todo auto-generated method stub         super.onresume();         // loading comments via asynctask         new loadcomments().execute();     }      public void addcomment(view v) {         intent = new intent(readcomments.this, addcomment.class);         startactivity(i);     }      /**      * retrieves recent post data server.      */     public void updatejsondata() {          // instantiate arraylist contain json data.         // going use bunch of key-value pairs, referring         // json element name, , content, example,         // message tag, , "i'm awesome" content..          mcommentlist = new arraylist<hashmap<string, string>>();          // bro, it's time power j parser         jsonparser jparser = new jsonparser();         // feed beast our comments url, , spits         // json object. boo-yeah jerome.         jsonobject json = jparser.getjsonfromurl(read_comments_url);          // when parsing json stuff, should         // try catch exceptions:         try {              // know said check if "posts avail." (success==1)             // before tried read individual posts, lied...             // mcomments tell how many "posts" or comments             // available             mcomments = json.getjsonarray(tag_posts);              // looping through posts according json object returned             (int = 0; < mcomments.length(); i++) {                 jsonobject c = mcomments.getjsonobject(i);                  // gets content of each tag                 string title = c.getstring(tag_title);                 string content = c.getstring(tag_message);                 string username = c.getstring(tag_username);                  // creating new hashmap                 hashmap<string, string> map = new hashmap<string, string>();                  map.put(tag_title, title);                 map.put(tag_message, content);                 map.put(tag_username, username);                  // adding hashlist arraylist                 mcommentlist.add(map);                  // annndddd, our json data date same our array                 // list             }          } catch (jsonexception e) {             e.printstacktrace();         }     }      /**      * inserts parsed data listview.      */     private void updatelist() {         // listactivity need set list adapter, , in order         //that, need create listadapter.  simpleadapter,         //will utilize our updated hashmapped arraylist,          //use our single_post xml template each item in our list,         //and place appropriate info list         //correct gui id.  order important here.         listadapter adapter = new simpleadapter(this, mcommentlist,                 r.layout.single_post, new string[] { tag_title, tag_message,                         tag_username }, new int[] { r.id.title, r.id.message,                         r.id.username });          // shouldn't have comment on one:         setlistadapter(adapter);          // optional: when user clicks list item          //could something.  however, choose         //to nothing...         listview lv = getlistview();             lv.setonitemclicklistener(new onitemclicklistener() {              @override             public void onitemclick(adapterview<?> parent, view view,                     int position, long id) {                  // method triggered if item click within our                 // list. our example won't using this,                 // useful know in real life applications.              }         });     }      public class loadcomments extends asynctask<void, void, boolean> {          @override         protected void onpreexecute() {             super.onpreexecute();             pdialog = new progressdialog(readcomments.this);             pdialog.setmessage("loading comments...");             pdialog.setindeterminate(false);             pdialog.setcancelable(true);             pdialog.show();         }          @override         protected boolean doinbackground(void... arg0) {             updatejsondata();             return null;          }          @override         protected void onpostexecute(boolean result) {             super.onpostexecute(result);             pdialog.dismiss();             updatelist();         }     } } 

here have php code:

*/ require("config.inc.php");   $query = "select post_id,username,title,message comments";   try {     $stmt   = $db->prepare($query);     $result = $stmt->execute($query_params);  } catch (pdoexception $ex) {     $response["success"] = 0;     $response["message"] = "database error!";     die(json_encode($response)); }   $rows = $stmt->fetchall();   if ($rows) {     $response["success"] = 1;     $response["message"] = "post available!";     json_encode($response)     $response["posts"]   = array();       foreach ($rows $row) {         $post             = array();         $post["post_id"]  = $row["post_id"];         $post["username"] = $row["username"];         $post["title"]    = $row["title"];         $post["message"]  = $row["message"];           //update our repsonse json data         array_push($response["posts"], $post);     }      // echoing json response     echo json_encode($response);   } else {     $response["success"] = 0;     $response["message"] = "no post available!";     die(json_encode($response)); } 

i hope can me, because loving android, code advance person think. still learning json.

as said in android api documentation:

public jsonarray getjsonarray (string name)

returns value mapped name if exists , jsonarray.

throws jsonexception if mapping doesn't exist or not jsonarray.

in case don't check if json object in response have field status value of 1. if it's 0, jsonexception thrown on line mcomments = json.getjsonarray(tag_posts);. because have array posts status = 1


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -