json - Decoding a jpeg in Android -


i have json data viewing url. there many json objects in json array, 1 of jpeg image.

i send image listview in android app.

right have image json object linked private static final string tag in java file. however, realize must decode image or receive error of: unable decode stream: java.io.filenotfoundexception , resolveuri failed on bad bitmap uri.

i in long , ongoing search understand how decode json jpeg image, of such research taken place viewing posts on website please not mark duplicate question.

public class jsonbuilderactivity extends listactivity {      private progressdialog pdialog;      //url json     private static string url = "";      //json node names     private static final string tag_cars = "cars";      //root     private static final string tag_carid = "carid";     private static final string tag_carvin = "carvin";     private static final string tag_img= "carmainimage";      jsonarray carid = null;  //initializes json array      static string response = null;      //hashmap listview     arraylist<hashmap<string, object>>caridlist;      @override     public void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);          listview lv = getlistview();          //listview on item click listener         lv.setonitemclicklistener(new onitemclicklistener() {              @override             public void onitemclick(adapterview<?> parent, view view, int position, long id) {                  //gets values selected listitem                 string cars = ((textview) view.findviewbyid(r.id.cars)).gettext().tostring();                 string car_id = ((textview) view.findviewbyid(r.id.car_id)).gettext().tostring();                 string car_vin = ((textview) view.findviewbyid(r.id.car_vin)).gettext().tostring();                 string model_img = ((imageview) view.findviewbyid(r.id.model_img)).gettag().tostring();                  intent in = new intent(jsonbuilderactivity.this, mainactivity.class);                 //sends data mainactivity                 in.putextra("tag_cars", cars);                 in.putextra("tag_carid", car_id);                 in.putextra("tag_carvin", car_vin);                 in.putextra("tag_img", model_img);                 startactivity(in);             }         });          //calls async task json         new getcars().execute();     }      public class servicehandler {          public final static int = 1;         public final static int post = 2;          public servicehandler() {          }          /**          * makes service call          * @url - url make request          * @method - http request method          * */         public string makeservicecall(string url, int method) {             return this.makeservicecall(url, method, null);         }          /**          * makes service call          * @url - url make request          * @method - http request method          * @params - http request params          * */         public string makeservicecall(string url, int method,arraylist<namevaluepair> params) {                     try {                     defaulthttpclient httpclient = new defaulthttpclient();                     httpentity httpentity = null;                     httpresponse httpresponse = null;                      //checks http request method type                     if (method == post) {                         httppost httppost = new httppost(url);                          //adds post params                     if (params != null) {                         httppost.setentity(new urlencodedformentity(params));                     }                          httpresponse = httpclient.execute(httppost);                  } else if (method == get) {                      //appends params url                     if (params != null) {                         string paramstring = urlencodedutils.format(params, "utf-8");                         url += "?" + paramstring;                     }                         httpget httpget = new httpget(url);                          httpresponse = httpclient.execute(httpget);                 }                  httpentity = httpresponse.getentity();                 response = entityutils.tostring(httpentity);              } catch (unsupportedencodingexception e) {                 e.printstacktrace();             } catch (clientprotocolexception e) {                 e.printstacktrace();             } catch (ioexception e) {                 e.printstacktrace();             }              return response;          }     }      /*      * async task class json making http call      */     private class getcars extends asynctask<void, void, void> {          @override         protected void onpreexecute() {             super.onpreexecute();            caridlist = new arraylist<hashmap<string, object>>();              //shows progress dialog             pdialog = new progressdialog(jsonbuilderactivity.this);             pdialog.setmessage("please wait...");             pdialog.setcancelable(false);             pdialog.show();          }          @override         protected void doinbackground(void... arg0) {              //creates service handler class instance             servicehandler sh = new servicehandler();              //makes request url , getting response             string jsonstr = sh.makeservicecall(url, servicehandler.get);              //prints json response in log             log.d("getcars response: ", "> " + jsonstr);                      if (jsonstr != null) {                         try {                              log.d("try", "in try");                              jsonobject jsonobj = new jsonobject(jsonstr);                             log.d("jsonobject", "new json object");                              //gets json array node                             carid = jsonobj.getjsonarray(tag_cars);                             log.d("json array", "user point array");                              int len = carid.length();                             log.d("len", "get array length");                              (int = 0; < carid.length(); i++) {                                 jsonobject c = carid.getjsonobject(i);                                 string car_id = c.getstring(tag_carid);                                 log.d("car_id", car_id);                                  string car_vin = c.getstring(tag_carvin);                                 log.d("car_vin", car_vin);                                   bitmapfactory.options options = new bitmapfactory.options();                                 options.injustdecodebounds = true;                                 bitmapfactory.decoderesource(getresources(), r.id.model_img, options);                                 int imageheight = options.outheight;                                 int imagewidth = options.outwidth;                                 string imagetype = options.outmimetype;                                  // byte[] bytearray =  base64.decode(jsonobj.getstring(tag_img), base64.default) ;                                 //bitmap bmp1 = bitmapfactory.decodebytearray(bytearray, 0, bytearray.length);                                  //string model_img = c.getstring(tag_img);                                 //log.d("model_img", model_img);                                  //hashmap single match                                 hashmap<string, object> matchgetcars = new hashmap<string, object>();                                  //adds each child node hashmap key => value                                 matchgetcars.put(tag_carid, car_id);                                 matchgetcars.put(tag_carvin, car_vin);                                 matchgetcars.put(tag_img,  ); //idk                                 caridlist.add(matchgetcars);                             }                         } catch (jsonexception e) {                             e.printstacktrace();                         }                     } else {                         log.e("servicehandler", "couldn't data url");                     }                     return null;                 }          @override                 protected void onpostexecute(void result) {                     super.onpostexecute(result);                     //dismisses progress dialog                     if (pdialog.isshowing())                         pdialog.dismiss();                      /**                      * updates parsed json data listview                      * */                    listadapter adapter = new simpleadapter(jsonbuilderactivity.this, caridlist, r.layout.list_item,                            new string[]{tag_carid, tag_carvin, tag_img}, new int[]{r.id.car_id, r.id.car_vin, r.id.model_img});                    setlistadapter(adapter);                     log.v("list parsed", caridlist.tostring());                 }     } 

so suggestions of how decode json jpeg image appreciated. thank you.

} 

update:

 public uri getimageuri(context incontext, bitmap inimage){         bytearrayoutputstream bytes = new bytearrayoutputstream();         inimage.compress(bitmap.compressformat.jpeg, 100, bytes);         string path = mediastore.images.media.insertimage(incontext.getcontentresolver(), inimage, "carmainimage", null);         return uri.parse(path);     }      public void savebmptofile(file filename, bitmap bmp){         fileoutputstream out = null;         try {             out = new fileoutputstream(filename);             bmp.compress(bitmap.compressformat.png, 100, out); // bmp bitmap instance             // png lossless format, compression factor (100) ignored         } catch (exception e) {             e.printstacktrace();         } {             try {                 if (out != null) {                     out.close();                 }             } catch (ioexception e) {                 e.printstacktrace();             }         }     }     //------------------------     public  boolean renamefileextension(string source, string newextension)     {         string target;         string currentextension = getfileextension(source);          if (currentextension.equals(""))         {             target = source + "." + newextension;         }         else         {             target = source.replacefirst(pattern.quote("." +                     currentextension) + "$", matcher.quotereplacement("." + newextension));          }         return new file(source).renameto(new file(target));     }     //---------------------------------------------------     public string getfileextension(string f)     {         string ext = "";         int = f.lastindexof('.');         if (i > 0 &&  < f.length() - 1)         {             ext = f.substring(i + 1);         }         return ext;     }     /*      * async task class json making http call      */     private class getcars extends asynctask<void, void, void> {          @override         protected void onpreexecute() {             super.onpreexecute();             caridlist = new arraylist<hashmap<string, object>>();              //shows progress dialog             pdialog = new progressdialog(jsonbuilderactivity.this);             pdialog.setmessage("please wait...");             pdialog.setcancelable(false);             pdialog.show();          }          @override         protected void doinbackground(void... arg0) {              //creates service handler class instance             servicehandler sh = new servicehandler();              //makes request url , getting response             string jsonstr = sh.makeservicecall(url, servicehandler.get);              //prints json response in log             log.d("getcars response: ", "> " + jsonstr);              if (jsonstr != null) {                 try {                      log.d("try", "in try");                      jsonobject jsonobj = new jsonobject(jsonstr);                     log.d("jsonobject", "new json object");                      //gets json array node                     carid = jsonobj.getjsonarray(tag_cars);                     log.d("json array", "user point array");                      int len = carid.length();                     log.d("len", "get array length");                      (int = 0; < carid.length(); i++) {                         jsonobject c = carid.getjsonobject(i);                         string car_id = c.getstring(tag_carid);                         log.d("car_id", car_id);                          string car_vin = c.getstring(tag_carvin);                         log.d("car_vin", car_vin);                           string model_img=c.getstring(tag_img);                         // byte[] bytearray =  base64.decode(jsonobj.getstring(tag_img), base64.default) ;                         //bitmap bmp1 = bitmapfactory.decodebytearray(bytearray, 0, bytearray.length);                         // string model_img = c.getstring(tag_img);                         //log.d("model_img", model_img);                          //hashmap single match                         hashmap<string, object> matchgetcars = new hashmap<string, object>();                          //adds each child node hashmap key => value                         matchgetcars.put(tag_carid, car_id);                         matchgetcars.put(tag_carvin, car_vin);                         matchgetcars.put(tag_img, model_img);                         caridlist.add(matchgetcars);                     }                 } catch (jsonexception e) {                     e.printstacktrace();                 }             } else {                 log.e("servicehandler", "couldn't data url");             }              return null;         }             @override         protected void onpostexecute(void result) {             super.onpostexecute(result);             //dismisses progress dialog             if (pdialog.isshowing())                 pdialog.dismiss();              /**              * updates parsed json data listview              * */             listadapter adapter = new simpleadapter(jsonbuilderactivity.this, caridlist, r.layout.list_item,                     new string[]{tag_carid, tag_carvin, tag_img}, new int[]{r.id.car_id, r.id.car_vin, r.id.model_img});             setlistadapter(adapter);             log.v("list parsed", caridlist.tostring());          }      } 

logcat:

v/list parsed﹕ [{carmainimage=/images/image.php?w=200&i unable decode stream: java.io.filenotfoundexception: /images/image.php?w=200.... unable resolveuri failed on bad bitmap uri: /images/image.php?w=200.... 

i not understand why parsed list correctly logged , error pop up. however, json jpeg in url not formatted jpeg in log cat because jpeg in json looks like: /images/image.php?w=200... , jpeg in logcat looks like: /images/image.php?200.. difference ..can elaborate if why error messages shown and/or offer suggestions fix errors? willing research , go , forth understand suggest. thanks.

without thinking post conversion code: **this place holder.** required understanding: bitmap uri provides object representation of "uniform resource identifier"  url (universal resourse loacator) reference (an address) resource on internet. file extensions. *.png *.jpg       up-dated when brain not without sleep ;o) more come think , brain hurts:     //------------------------                     public uri getimageuri(context incontext, bitmap inimage)                      {                       bytearrayoutputstream bytes = new bytearrayoutputstream();                       inimage.compress(bitmap.compressformat.jpeg, 100, bytes);                       string path = images.media.insertimage(incontext.getcontentresolver(), inimage, "title", null);                       return uri.parse(path);                     }                      public void savebmptofile(file filename, bitmap bmp)                      {                     fileoutputstream out = null;                     try {                         out = new fileoutputstream(filename);                         bmp.compress(bitmap.compressformat.png, 100, out); // bmp bitmap instance                         // png lossless format, compression factor (100) ignored                     } catch (exception e) {                         e.printstacktrace();                     } {                         try {                             if (out != null) {                                 out.close();                             }                         } catch (ioexception e) {                             e.printstacktrace();                         }                     }                     }     //------------------------           public static boolean renamefileextension(string source, string newextension)           {             string target;             string currentextension = getfileextension(source);              if (currentextension.equals(""))             {               target = source + "." + newextension;             }             else              {               target = source.replacefirst(pattern.quote("." +                   currentextension) + "$", matcher.quotereplacement("." + newextension));              }             return new file(source).renameto(new file(target));           }         //---------------------------------------------------           public static string getfileextension(string f)            {             string ext = "";             int = f.lastindexof('.');             if (i > 0 &&  < f.length() - 1)              {               ext = f.substring(i + 1);             }             return ext;           }         //----------------------- 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -