edit: found solution problem. json string output returned wrong url local images.
i barely new android , struggle asynctask.
what want corresponding image marker on map. every entry on map has own image has loaded server via json.
the image load works fine dont right workflow image need 1 entry.
by have 1 solution load async task in for-loop, cant right way because app refuses go on after 43 tasks , stops "econnection timeout"
so how can asynctask out of loop?
hope can help? thank you!
here code:
public class mapsactivity extends appcompatactivity implements onmapreadycallback {
private googlemap mmap; jsonarray contentjson; string contentid; string imagejsonurl; string userid; bitmap bmp; latlng latlng; marker m; hashmap<marker, string> hashmap; int k = 0; // check value request check final int my_location_request_code = 3; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_maps); // obtain supportmapfragment , notified when map ready used. supportmapfragment mapfragment = (supportmapfragment) getsupportfragmentmanager() .findfragmentbyid(r.id.map); mapfragment.getmapasync(this); toolbar mytoolbar = (toolbar) findviewbyid(r.id.my_toolbar); setsupportactionbar(mytoolbar); getsupportactionbar().setdisplayshowtitleenabled(false); if(this.getintent().getextras() != null) { try { contentjson = new jsonarray(this.getintent().getstringextra("contentjson")); // log.v("testitest", contentjson.tostring()); } catch (jsonexception e) { log.e("exception", "unexpected json exception", e); e.printstacktrace(); } } } public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.menu_maps, menu); return true; } public latlng getlatlngposition() { return new latlng(0, 0); } /** * manipulates map once available. * callback triggered when map ready used. * can add markers or lines, add listeners or move camera. in case, * add marker near sydney, australia. * if google play services not installed on device, user prompted install * inside supportmapfragment. method triggered once user has * installed google play services , returned app. */ @override public void onmapready(googlemap googlemap) { mmap = googlemap; //ask permission. if granted show location if (activitycompat.checkselfpermission(mapsactivity.this, manifest.permission.access_fine_location) != packagemanager.permission_granted) { // check permissions activitycompat.requestpermissions(mapsactivity.this, new string[]{manifest.permission.access_fine_location}, my_location_request_code); } else { // permission has been granted, continue usual mmap.setmylocationenabled(true); } placeautocompletefragment autocompletefragment = (placeautocompletefragment) getfragmentmanager().findfragmentbyid(r.id.place_autocomplete_fragment); autocompletefragment.setonplaceselectedlistener(new placeselectionlistener() { @override public void onplaceselected(place place) { // todo: info selected place. latlng selectedlocation = place.getlatlng(); mmap.animatecamera(cameraupdatefactory.newlatlngzoom(selectedlocation, 10f)); } @override public void onerror(status status) { // todo: handle error. log.i("placeselectorerror", "an error occurred: " + status); } }); latlng bonn = new latlng(50.7323, 7.1847); latlng cologne = new latlng(50.9333333, 6.95); //mmap.addmarker(new markeroptions().position(bonn).title("marker in bonn")); // hash map saving content id marker hashmap = new hashmap<marker, string>(); if(contentjson != null) { if (this.getintent().getstringextra("contentid") == null) { // show contents of friends try { (int = 0; < contentjson.length(); i++) { jsonobject jsoninfo = contentjson.getjsonobject(i); jsonarray contents = jsoninfo.getjsonarray("content"); // log.v("contentslength", string.valueof(contents.length())); //get contents of 1 user (int j = 0; j < contents.length(); j++) { jsonobject eachcontent = contents.getjsonobject(j); //log.v("eachcontent", eachcontent.tostring()); jsonobject location = eachcontent.getjsonobject("location"); string contentid = eachcontent.getstring("id"); string contenttitle = eachcontent.getstring("title"); userid = eachcontent.getstring("user_id"); latlng = new latlng(double.valueof(location.getstring("latitude")), double.valueof(location.getstring("longitude"))); new mapimageloadtask("http://192.168.63.35:1234/rest_app_users/getimage/", userid, contentid, contenttitle, latlng).execute(); log.v("contenttitle", contenttitle); //log.v("m", m.tostring()); //m = mmap.addmarker(new markeroptions().title(contenttitle).position(new latlng(double.valueof(location.getstring("latitude")), double.valueof(location.getstring("longitude")))).icon(bitmapdescriptorfactory.frombitmap(bmp))); } } } catch (jsonexception e) { log.e("exception", "unexpected json exception", e); e.printstacktrace(); } } else { // if want see specific content try { (int = 0; < contentjson.length(); i++) { jsonobject jsoninfo = contentjson.getjsonobject(i); jsonarray contents = jsoninfo.getjsonarray("content"); //get contents of 1 user (int j = 0; j < contents.length(); j++) { jsonobject eachcontent = contents.getjsonobject(j); jsonobject location = eachcontent.getjsonobject("location"); if(eachcontent.getstring("id").equals(this.getintent().getstringextra("contentid"))) { string contentid = eachcontent.getstring("id"); string contenttitle = eachcontent.getstring("title"); userid = eachcontent.getstring("user_id"); latlng = new latlng(double.valueof(location.getstring("latitude")), double.valueof(location.getstring("longitude"))); // log.v("latlng", contentid); new mapimageloadtask("http://192.168.63.35:1234/rest_app_users/getimage/", userid, contentid, contenttitle, latlng).execute(); continue; } } } } catch (jsonexception e) { log.e("logedilog", "unexpected json exception", e); e.printstacktrace(); } } } mmap.setonmylocationchangelistener(new googlemap.onmylocationchangelistener() { @override public void onmylocationchange(location location) { mmap.animatecamera(cameraupdatefactory.newlatlngzoom( new latlng(location.getlatitude(), location.getlongitude()), 10f)); mmap.setonmylocationchangelistener(null); } }); mmap.setoninfowindowclicklistener(new googlemap.oninfowindowclicklistener() { @override public void oninfowindowclick(marker marker) { string id = hashmap.get(marker); log.v("bitmap", bmp.tostring()); try { context context = getapplicationcontext(); intent mapintent = new intent(getapplicationcontext(), contentdetailactivity.class); mapintent.putextra("contentid", id); mapintent.putextra("contentjson", contentjson.tostring()); mapintent.putextra("userid", userid); string filename = "profileimage.png"; fileoutputstream stream = context.openfileoutput(filename, context.mode_private); bmp.compress(bitmap.compressformat.png, 100, stream); //cleanup stream.close(); mapintent.putextra("image", filename); startactivity(mapintent); } catch (exception e) { e.printstacktrace(); } } }); } public marker[] addmarkers() { return null; } /** * lets load image external source via url */ public class mapimageloadtask extends asynctask<void, void, bitmap> { private final string log_tag = mapimageloadtask.class.getsimplename(); string url, userid, contentid, title; latlng location; bufferedreader reader = null; public mapimageloadtask(string url, string userid, string contentid, string title, latlng location) { this.url = url; this.userid = userid; this.contentid = contentid; this.title = title; this.location = location; } private string getimageurlfromjson(string imagejson) throws jsonexception { jsonobject imagejsonoutput = new jsonobject(imagejson); imagejsonurl = imagejsonoutput.getstring("imageurl"); //log.v(log_tag, imagejsonurl); return imagejsonurl; } @override protected bitmap doinbackground(void... params) { string imagejson = null; try { url urlconnection = new url(url + userid); httpurlconnection connection = (httpurlconnection) urlconnection .openconnection(); connection.setdoinput(true); connection.connect(); inputstream input = connection.getinputstream(); stringbuffer buffer = new stringbuffer(); if (input == null) { // nothing do. //forecastjsonstr = null; return null; } reader = new bufferedreader(new inputstreamreader(input)); string line; while ((line = reader.readline()) != null) { // since it's json, adding newline isn't necessary (it won't affect parsing) // make debugging *lot* easier if print out completed // buffer debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { return null; } imagejson = buffer.tostring(); } catch (exception e) { e.printstacktrace(); } try { string jsonurl = getimageurlfromjson(imagejson); url url = new url(jsonurl); bmp = bitmapfactory.decodestream(url.openconnection().getinputstream()); return bmp; } catch(exception e) { e.printstacktrace(); } return null; } @override protected void onpostexecute(bitmap result) { super.onpostexecute(result); k +=1; log.v("counter", string.valueof(k)); m = mmap.addmarker(new markeroptions().title(title).position(location).icon(bitmapdescriptorfactory.frombitmap(bmp))); hashmap.put(m, contentid); } }
}
your problem maybe asynctask limitations. in android.os.asynctask.java see core size , blockingqueue size(128), should use counter asynctask , debug it(problem is, lots of async tasks or other).
asynctask.java
public abstract class asynctask<params, progress, result> { private static final string log_tag = "asynctask"; private static final int cpu_count = runtime.getruntime().availableprocessors(); private static final int core_pool_size = cpu_count + 1; private static final int maximum_pool_size = cpu_count * 2 + 1; private static final int keep_alive = 1; private static final threadfactory sthreadfactory = new threadfactory() { private final atomicinteger mcount = new atomicinteger(1); public thread newthread(runnable r) { return new thread(r, "asynctask #" + mcount.getandincrement()); } }; private static final blockingqueue<runnable> spoolworkqueue = new linkedblockingqueue<runnable>(128); ...}
change code use buffer(requestdata) , use 1 async task. update market instance every publishprogress in onprogressupdate
private googlemap mmap; jsonarray contentjson; string contentid; string imagejsonurl; string userid; bitmap bmp; latlng latlng; marker m; hashmap<marker, string> hashmap; int k = 0; // check value request check final int my_location_request_code = 3; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_maps); // obtain supportmapfragment , notified when map ready used. supportmapfragment mapfragment = (supportmapfragment) getsupportfragmentmanager() .findfragmentbyid(r.id.map); mapfragment.getmapasync(this); toolbar mytoolbar = (toolbar) findviewbyid(r.id.my_toolbar); setsupportactionbar(mytoolbar); getsupportactionbar().setdisplayshowtitleenabled(false); if(this.getintent().getextras() != null) { try { contentjson = new jsonarray(this.getintent().getstringextra("contentjson")); // log.v("testitest", contentjson.tostring()); } catch (jsonexception e) { log.e("exception", "unexpected json exception", e); e.printstacktrace(); } } } public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.menu_maps, menu); return true; } public latlng getlatlngposition() { return new latlng(0, 0); } /** * manipulates map once available. * callback triggered when map ready used. * can add markers or lines, add listeners or move camera. in case, * add marker near sydney, australia. * if google play services not installed on device, user prompted install * inside supportmapfragment. method triggered once user has * installed google play services , returned app. */ @override public void onmapready(googlemap googlemap) { mmap = googlemap; //ask permission. if granted show location if (activitycompat.checkselfpermission(mapsactivity.this, manifest.permission.access_fine_location) != packagemanager.permission_granted) { // check permissions activitycompat.requestpermissions(mapsactivity.this, new string[]{manifest.permission.access_fine_location}, my_location_request_code); } else { // permission has been granted, continue usual mmap.setmylocationenabled(true); } placeautocompletefragment autocompletefragment = (placeautocompletefragment) getfragmentmanager().findfragmentbyid(r.id.place_autocomplete_fragment); autocompletefragment.setonplaceselectedlistener(new placeselectionlistener() { @override public void onplaceselected(place place) { // todo: info selected place. latlng selectedlocation = place.getlatlng(); mmap.animatecamera(cameraupdatefactory.newlatlngzoom(selectedlocation, 10f)); } @override public void onerror(status status) { // todo: handle error. log.i("placeselectorerror", "an error occurred: " + status); } }); latlng bonn = new latlng(50.7323, 7.1847); latlng cologne = new latlng(50.9333333, 6.95); //mmap.addmarker(new markeroptions().position(bonn).title("marker in bonn")); // hash map saving content id marker hashmap = new hashmap<marker, string>(); if(contentjson != null) { if (this.getintent().getstringextra("contentid") == null) { // show contents of friends try { (int = 0; < contentjson.length(); i++) { jsonobject jsoninfo = contentjson.getjsonobject(i); jsonarray contents = jsoninfo.getjsonarray("content"); // log.v("contentslength", string.valueof(contents.length())); //get contents of 1 user (int j = 0; j < contents.length(); j++) { jsonobject eachcontent = contents.getjsonobject(j); //log.v("eachcontent", eachcontent.tostring()); jsonobject location = eachcontent.getjsonobject("location"); string contentid = eachcontent.getstring("id"); string contenttitle = eachcontent.getstring("title"); userid = eachcontent.getstring("user_id"); latlng = new latlng(double.valueof(location.getstring("latitude")), double.valueof(location.getstring("longitude"))); new mapimageloadtask("http://192.168.63.35:1234/rest_app_users/getimage/", userid, contentid, contenttitle, latlng).execute(); log.v("contenttitle", contenttitle); //log.v("m", m.tostring()); //m = mmap.addmarker(new markeroptions().title(contenttitle).position(new latlng(double.valueof(location.getstring("latitude")), double.valueof(location.getstring("longitude")))).icon(bitmapdescriptorfactory.frombitmap(bmp))); } } } catch (jsonexception e) { log.e("exception", "unexpected json exception", e); e.printstacktrace(); } } else { // if want see specific content try { list<requestdata> datas = new arraylist<requestdata>(); (int = 0; < contentjson.length(); i++) { jsonobject jsoninfo = contentjson.getjsonobject(i); jsonarray contents = jsoninfo.getjsonarray("content"); //get contents of 1 user (int j = 0; j < contents.length(); j++) { jsonobject eachcontent = contents.getjsonobject(j); jsonobject location = eachcontent.getjsonobject("location"); if(eachcontent.getstring("id").equals(this.getintent().getstringextra("contentid"))) { string contentid = eachcontent.getstring("id"); string contenttitle = eachcontent.getstring("title"); userid = eachcontent.getstring("user_id"); latlng = new latlng(double.valueof(location.getstring("latitude")), double.valueof(location.getstring("longitude"))); // log.v("latlng", contentid); requestdata data = new requestdata(); data.url = "http://192.168.63.35:1234/rest_app_users/getimage/"; data.userid = userid; data.contentid = contentid; data.contenttitle = contenttitle; data.latlng = latlng; datas.add(data); //new mapimageloadtask("http://192.168.63.35:1234/rest_app_users/getimage/", userid, contentid, contenttitle, latlng).execute(); continue; } } } new mapimageloadtask(datas).execute(); } catch (jsonexception e) { log.e("logedilog", "unexpected json exception", e); e.printstacktrace(); } } } mmap.setonmylocationchangelistener(new googlemap.onmylocationchangelistener() { @override public void onmylocationchange(location location) { mmap.animatecamera(cameraupdatefactory.newlatlngzoom( new latlng(location.getlatitude(), location.getlongitude()), 10f)); mmap.setonmylocationchangelistener(null); } }); mmap.setoninfowindowclicklistener(new googlemap.oninfowindowclicklistener() { @override public void oninfowindowclick(marker marker) { string id = hashmap.get(marker); log.v("bitmap", bmp.tostring()); try { context context = getapplicationcontext(); intent mapintent = new intent(getapplicationcontext(), contentdetailactivity.class); mapintent.putextra("contentid", id); mapintent.putextra("contentjson", contentjson.tostring()); mapintent.putextra("userid", userid); string filename = "profileimage.png"; fileoutputstream stream = context.openfileoutput(filename, context.mode_private); bmp.compress(bitmap.compressformat.png, 100, stream); //cleanup stream.close(); mapintent.putextra("image", filename); startactivity(mapintent); } catch (exception e) { e.printstacktrace(); } } }); } public marker[] addmarkers() { return null; } /** * lets load image external source via url */ static class requestdata{ public string url; public string userid; public string contentid; public string contenttitle; public latlng latlng; public bitmap bmp; } public class mapimageloadtask extends asynctask<void, requestdata, void> { private final string log_tag = mapimageloadtask.class.getsimplename(); bufferedreader reader = null; list<requestdata> dataset; public mapimageloadtask(list<requestdata> dataset) { this.dataset = dataset; } private string getimageurlfromjson(string imagejson) throws jsonexception { jsonobject imagejsonoutput = new jsonobject(imagejson); imagejsonurl = imagejsonoutput.getstring("imageurl"); //log.v(log_tag, imagejsonurl); return imagejsonurl; } @override protected bitmap doinbackground(void... params) { for(requestdata item : dataset){ string imagejson = null; try { url urlconnection = new url(url + userid); httpurlconnection connection = (httpurlconnection) urlconnection .openconnection(); connection.setdoinput(true); connection.connect(); inputstream input = connection.getinputstream(); stringbuffer buffer = new stringbuffer(); if (input == null) { // nothing do. //forecastjsonstr = null; return null; } reader = new bufferedreader(new inputstreamreader(input)); string line; while ((line = reader.readline()) != null) { // since it's json, adding newline isn't necessary (it won't affect parsing) // make debugging *lot* easier if print out completed // buffer debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { return null; } imagejson = buffer.tostring(); } catch (exception e) { e.printstacktrace(); } try { string jsonurl = getimageurlfromjson(imagejson); url url = new url(jsonurl); bmp = bitmapfactory.decodestream(url.openconnection().getinputstream()); // item.bmp = bmp; publishprogress(item); } catch(exception e) { e.printstacktrace(); } } return null; } protected void onpublishprogress(requestdata item){ k +=1; log.v("counter", string.valueof(k)); m = mmap.addmarker(new markeroptions().title(item.title).position(item.location).icon(bitmapdescriptorfactory.frombitmap(item.bmp))); hashmap.put(m, contentid); } @override protected void onpostexecute(bitmap result) { super.onpostexecute(result); } } }
Comments
Post a Comment