i'm trying upload image api show profile picture, problem first time user opens navdrawer image doesn't load , makes entire layout disappear, second time works, , notice happens when width of image less height. class i'm using:
public class circlednetworkimageview extends imageview { public boolean mcircled; /** * url of network image load */ private string murl; /** * resource id of image used placeholder until network image loaded. */ private int mdefaultimageid; /** * resource id of image used if network response fails. */ private int merrorimageid; /** * local copy of imageloader. */ private imageloader mimageloader; /** * current imagecontainer. (either in-flight or finished) */ private imageloader.imagecontainer mimagecontainer; public circlednetworkimageview(context context) { this(context, null); } public circlednetworkimageview(context context, attributeset attrs) { this(context, attrs, 0); } public circlednetworkimageview(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); } /** * sets url of image should loaded view. note calling * either set cached image (if available) or default image specified * {@link circlednetworkimageview#setdefaultimageresid(int)} on view. * <p/> * note: if applicable, {@link circlednetworkimageview#setdefaultimageresid(int)} , * {@link circlednetworkimageview#seterrorimageresid(int)} should called prior calling * function. * * @param url url should loaded imageview. * @param imageloader imageloader used make request. */ public void setimageurl(string url, imageloader imageloader) { murl = url; mimageloader = imageloader; // url has potentially changed. see if need load it. loadimageifnecessary(false); } /** * sets default image resource id used view until attempt load * completes. */ public void setdefaultimageresid(int defaultimage) { mdefaultimageid = defaultimage; } /** * sets error image resource id used view in event image * requested fails load. */ public void seterrorimageresid(int errorimage) { merrorimageid = errorimage; } /** * loads image view if isn't loaded. * * @param isinlayoutpass true if invoked layout pass, false otherwise. */ void loadimageifnecessary(final boolean isinlayoutpass) { int width = getwidth(); int height = getheight(); scaletype scaletype = getscaletype(); boolean wrapwidth = false, wrapheight = false; if (getlayoutparams() != null) { wrapwidth = getlayoutparams().width == viewgroup.layoutparams.wrap_content; wrapheight = getlayoutparams().height == viewgroup.layoutparams.wrap_content; } // if view's bounds aren't known yet, , not wrap-content/wrap-content // view, hold off on loading image. boolean isfullywrapcontent = wrapwidth && wrapheight; if (width == 0 && height == 0 && !isfullywrapcontent) { return; } // if url loaded in view empty, cancel old requests , clear // loaded image. if (textutils.isempty(murl)) { if (mimagecontainer != null) { mimagecontainer.cancelrequest(); mimagecontainer = null; } setdefaultimageornull(); return; } // if there old request in view, check if needs canceled. if (mimagecontainer != null && mimagecontainer.getrequesturl() != null) { if (mimagecontainer.getrequesturl().equals(murl)) { // if request same url, return. return; } else { // if there pre-existing request, cancel if it's fetching different url. mimagecontainer.cancelrequest(); setdefaultimageornull(); } } // calculate max image width / height use while ignoring wrap_content dimens. int maxwidth = wrapwidth ? 0 : width; int maxheight = wrapheight ? 0 : height; // pre-existing content of view didn't match current url. load new image // network. imageloader.imagecontainer newcontainer = mimageloader.get(murl, new imageloader.imagelistener() { @override public void onerrorresponse(volleyerror error) { if (merrorimageid != 0) { setimageresource(merrorimageid); } } @override public void onresponse(final imageloader.imagecontainer response, boolean isimmediate) { // if immediate response delivered inside of layout // pass not set image trigger requestlayout // inside of layout. instead, defer setting image posting // main thread. if (isimmediate && isinlayoutpass) { post(new runnable() { @override public void run() { onresponse(response, false); } }); return; } if (response.getbitmap() != null) { setimagebitmap(response.getbitmap()); } else if (mdefaultimageid != 0) { setimageresource(mdefaultimageid); } } }, maxwidth, maxheight, scaletype); // update imagecontainer new bitmap container. mimagecontainer = newcontainer; } private void setdefaultimageornull() { if (mdefaultimageid != 0) { setimageresource(mdefaultimageid); } else { setimagebitmap(null); } } @override protected void onlayout(boolean changed, int left, int top, int right, int bottom) { super.onlayout(changed, left, top, right, bottom); loadimageifnecessary(true); } @override protected void ondetachedfromwindow() { if (mimagecontainer != null) { // if view bound image request, cancel , clear // out image view. mimagecontainer.cancelrequest(); setimagebitmap(null); // clear out container can reload image if necessary. mimagecontainer = null; } super.ondetachedfromwindow(); } @override protected void drawablestatechanged() { super.drawablestatechanged(); invalidate(); } /** * in case bitmap manually changed, make sure * circle on next ondraw */ @override public void setimagebitmap(bitmap bm) { mcircled = false; super.setimagebitmap(bm); } /** * in case bitmap manually changed, make sure * circle on next ondraw */ @override public void setimageresource(int resid) { mcircled = false; super.setimageresource(resid); } /** * in case bitmap manually changed, make sure * circle on next ondraw */ @override public void setimagedrawable(drawable drawable) { mcircled = false; super.setimagedrawable(drawable); } /** * want make sure imageview has same height , width */ @override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { drawable drawable = getdrawable(); if (drawable != null) { int width = measurespec.getsize(widthmeasurespec); int diw = drawable.getintrinsicwidth(); if (diw > 0) { int height = width * drawable.getintrinsicheight() / diw; setmeasureddimension(width, height); } else super.onmeasure(widthmeasurespec, heightmeasurespec); } else super.onmeasure(widthmeasurespec, heightmeasurespec); } @override protected void ondraw(canvas canvas) { //let's circle image if (!mcircled && getdrawable() != null) { drawable d = getdrawable(); try { //we use reflection here in case drawable isn't //bitmapdrawable contains public getbitmap method. bitmap bitmap = (bitmap) d.getclass().getmethod("getbitmap").invoke(d); if (bitmap != null) { bitmap circlebitmap = getcirclebitmap(bitmap); setimagebitmap(circlebitmap); } } catch (illegalargumentexception e) { e.printstacktrace(); } catch (illegalaccessexception e) { e.printstacktrace(); } catch (invocationtargetexception e) { e.printstacktrace(); } catch (nosuchmethodexception e) { e.printstacktrace(); //seems current drawable not bitmapdrawable or //that doesn't have public getbitmap() method. } //mark circled if failed, because if fails once, //it fail again. mcircled = true; } super.ondraw(canvas); } /** * method used circle bitmap. * * @param bitmap bitmap circle * @return circled bitmap */ public static bitmap getcirclebitmap(bitmap bitmap) { int size = math.min(bitmap.getwidth(), bitmap.getheight()); bitmap output = bitmap.createbitmap(size, size, bitmap.config.argb_8888); canvas canvas = new canvas(output); bitmapshader shader; shader = new bitmapshader(bitmap, shader.tilemode.clamp, shader.tilemode.clamp); paint paint = new paint(); paint.setantialias(true); paint.setshader(shader); paint.setalpha(254); rectf rect = new rectf(0, 0, size, size); int radius = size / 2; canvas.drawroundrect(rect, radius, radius, paint); return output; } }
i came solution, didn't it, because image loses quality:
public class useractivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.profile_main); toolbar = (toolbar) findviewbyid(r.id.toolbar_user); camera = (imageview) findviewbyid(r.id.camera); fechar = (textview) findviewbyid(r.id.fechar); editar = (textview) findviewbyid(r.id.editar); membro = (textview) findviewbyid(r.id.membro); nome = (textview) findviewbyid(r.id.nome_usuario); email = (textview) findviewbyid(r.id.email_usuario); email = (textview) findviewbyid(r.id.email_usuario); profilepic = (networkimageview) findviewbyid(r.id.foto); mimageview = (imageview) findviewbyid(r.id.cropped); progress_wheel = (progresswheel) findviewbyid(r.id.progress_wheel); camera.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { alertdialog.builder getimagefrom = new alertdialog.builder(useractivity.this); getimagefrom.settitle("abrir com:"); final charsequence[] opschars = {getresources().getstring(r.string.takepic), getresources().getstring(r.string.opengallery)}; getimagefrom.setitems(opschars, new android.content.dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { if (which == 0) { intent intent = new intent(mediastore.action_image_capture); mimagecaptureuri = uri.fromfile(new file(environment.getexternalstoragedirectory(), "tmp_avatar_" + string.valueof(system.currenttimemillis()) + ".jpg")); intent.putextra(android.provider.mediastore.extra_output, mimagecaptureuri); try { intent.putextra("return-data", true); startactivityforresult(intent, pick_from_camera); } catch (activitynotfoundexception e) { e.printstacktrace(); } } else if (which == 1) { intent intent = new intent(); intent.settype("image/*"); intent.setaction(intent.action_get_content); startactivityforresult(intent.createchooser(intent, "complete action using"), pick_from_file); } dialog.dismiss(); } }); getimagefrom.show(); } }); profilepic.setimageurl(globalmodel.getperfil().getiddaimagem(), imageloader); profilepic.setdefaultimageresid(r.drawable.avatar_); } @override public void onactivityresult(final int requestcode, final int resultcode, final intent data) { super.onactivityresult(requestcode, resultcode, data); try { if (resultcode != result_ok) return; switch (requestcode) { case pick_from_camera: profilepic.setvisibility(view.gone); progress_wheel.setvisibility(view.visible); selectedimagepath = imagefilepath.getpath(getapplicationcontext(), mimagecaptureuri); log.i("image file path", "" + selectedimagepath); mimagecaptureuri = uri.parse(selectedimagepath); final bitmapfactory.options option = new bitmapfactory.options(); option.insamplesize = 8; bitmap photo = bitmapfactory.decodefile(mimagecaptureuri.getpath(), option); photo = bitmap.createscaledbitmap(photo, 200, 200, false); bytearrayoutputstream bytes = new bytearrayoutputstream(); photo.compress(bitmap.compressformat.jpeg, 100, bytes); file f = new file(environment.getexternalstoragedirectory() + file.separator + "imagename.jpg"); f.createnewfile(); fileoutputstream fo = new fileoutputstream(f); fo.write(bytes.tobytearray()); fo.close(); previewcapturedimage(f.getabsolutepath()); profilepic.setvisibility(view.visible); progress_wheel.setvisibility(view.gone); profilepic.setimagebitmap(bitmapfactory.decodefile(mimagecaptureuri.getpath())); break; case pick_from_file: profilepic.setvisibility(view.gone); progress_wheel.setvisibility(view.visible); mimagecaptureuri = data.getdata(); selectedimagepath = imagefilepath.getpath(getapplicationcontext(), mimagecaptureuri); log.i("image file path", "" + selectedimagepath); mimagecaptureuri = uri.parse(selectedimagepath); final bitmapfactory.options options = new bitmapfactory.options(); options.insamplesize = 8; bitmap photogaleria = bitmapfactory.decodefile(mimagecaptureuri.getpath(), options); photogaleria = bitmap.createscaledbitmap(photogaleria, 200, 200, false); bytearrayoutputstream bytesg = new bytearrayoutputstream(); photogaleria.compress(bitmap.compressformat.jpeg, 100, bytesg); file fg = new file(environment.getexternalstoragedirectory() + file.separator + "imagename.jpg"); fg.createnewfile(); fileoutputstream fog = new fileoutputstream(fg); fog.write(bytesg.tobytearray()); fog.close(); previewcapturedimage(fg.getabsolutepath()); profilepic.setvisibility(view.visible); progress_wheel.setvisibility(view.gone); profilepic.setimagebitmap(bitmapfactory.decodefile(mimagecaptureuri.getpath())); break; } } catch (exception e) { e.printstacktrace(); } } private void previewcapturedimage(string path) { try { uploadfoto mupload = new uploadfoto(path); mupload.seteventolistener(new iexecutartarefa<uploadfoto>() { @override public void antesdeexecutar(uploadfoto tarefa) { } @override public void depoisdeexecutar(uploadfoto tarefa) { if (tarefa.getresposta()[0].equals("200")) { globalmodel.getperfil().setiddaimagem(webservice.imgurl + tarefa.getresposta()[1].replace("\"", "")); profilepic.setimageurl(globalmodel.getperfil().getiddaimagem(), imageloader); } } }); mupload.execute(); } catch (nullpointerexception e) { e.printstacktrace(); } } @override public void onbackpressed() { super.onbackpressed(); finish(); overridependingtransition(r.anim.animation_back, r.anim.animation_back_leave); } @override protected void onresume() { super.onresume(); carregarperfil mcarrega = new carregarperfil(); mcarrega.execute(); } }
xml:
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res-auto" xmlns:wheel="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitssystemwindows="true" android:orientation="vertical"> <include android:id="@+id/toolbar_user" layout="@layout/toolbaruser" /> <relativelayout android:id="@+id/campoimagem" android:layout_width="fill_parent" android:layout_height="200dp" android:layout_below="@+id/toolbar_user" android:background="@color/armadillo"> <com.android.volley.toolbox.networkimageview android:id="@+id/foto" android:layout_width="200dp" android:layout_height="fill_parent" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:adjustviewbounds="true" android:scaletype="centercrop" android:src="@drawable/user" android:visibility="visible" /> <com.pnikosis.materialishprogress.progresswheel android:id="@+id/progress_wheel" android:layout_width="80dp" android:layout_height="80dp" android:layout_gravity="center" android:visibility="gone" wheel:matprog_barcolor="@color/white" wheel:matprog_progressindeterminate="true" android:layout_centervertical="true" android:layout_centerhorizontal="true" /> <imageview android:id="@+id/cropped" android:layout_width="200dp" android:layout_height="fill_parent" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:layout_gravity="center" android:visibility="visible"/> <imageview android:id="@+id/camera" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_alignparentend="true" android:layout_alignparentright="true" android:padding="15dp" android:src="@drawable/ic_camera" /> <textview android:id="@+id/button_crop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_alignparentleft="true" android:layout_alignparentstart="true" android:gravity="center" android:padding="15dp" android:text="salvar" android:textcolor="@color/white" android:visibility="gone" /> </relativelayout> <relativelayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignparentbottom="true"> <textview android:id="@+id/membro" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparentstart="true" android:layout_alignparenttop="true" android:gravity="center" android:paddingbottom="10dp" android:paddingleft="10dp" android:paddingtop="5dp" android:text="membro retornar desde julho de 2015" android:textcolor="@color/star_dust" /> </relativelayout> <linearlayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/campoimagem" android:layout_marginbottom="30dp" android:layout_marginleft="15dp" android:layout_marginright="15dp" android:layout_margintop="15dp" android:gravity="center" android:orientation="vertical"> <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:paddingbottom="0dp" android:paddingleft="10dp" android:paddingright="0dp" android:paddingtop="10dp" android:text="nome" android:textcolor="@color/star_dust" android:textsize="@dimen/text1" /> <textview android:id="@+id/nome_usuario" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:paddingbottom="0dp" android:paddingleft="10dp" android:paddingtop="5dp" android:textcolor="@color/armadillo" android:textsize="@dimen/text1" /> <textview android:id="@+id/entrar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:paddingleft="10dp" android:paddingtop="10dp" android:text="e-mail" android:textcolor="@color/star_dust" android:textsize="@dimen/text1" /> <textview android:id="@+id/email_usuario" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:paddingbottom="0dp" android:paddingleft="10dp" android:paddingtop="5dp" android:text="jgvidotto@gmail.com" android:textcolor="@color/armadillo" android:textsize="@dimen/text1" /> </linearlayout> </relativelayout>
because have not posted activity calling navigation drawer, have used both circlednetworkimageview
class , built-in networkimageview
in project. works well. please refer following:
customnavigationdrawer.java:
public class customnavigationdrawer { private static actionbardrawertoggle sdrawertoggle; public static drawerlayout setupdrawer(final context context) { final activity activity = ((activity) context); drawerlayout sdrawerlayout = (drawerlayout) activity.findviewbyid(r.id.drawer_layout); if (activity.getactionbar() != null) { activity.getactionbar().setdisplayhomeasupenabled(true); activity.getactionbar().sethomebuttonenabled(true); } sdrawertoggle = new actionbardrawertoggle( activity, sdrawerlayout, r.drawable.ic_drawer, r.string.drawer_open, r.string.drawer_close ) { public void ondrawerclosed(view view) { activity.invalidateoptionsmenu(); syncstate(); } public void ondraweropened(view drawerview) { activity.invalidateoptionsmenu(); syncstate(); } }; sdrawerlayout.setdrawerlistener(sdrawertoggle); return sdrawerlayout; } public static void syncstate() { sdrawertoggle.syncstate(); } public static void onconfigurationchanged(configuration newconfig) { sdrawertoggle.onconfigurationchanged(newconfig); } }
mainactivity.java:
public class mainactivity extends activity { final context mcontext = this; final string murl = "http://.../getimage"; networkimageview mnetworkimageview; circlednetworkimageview mcirclednetworkimageview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); customnavigationdrawer.setupdrawer(this); mnetworkimageview = (networkimageview) findviewbyid(r.id.networkimageview); mnetworkimageview.setimageurl(murl, volleysingleton.getinstance(mcontext).getimageloader()); mcirclednetworkimageview = (circlednetworkimageview) findviewbyid(r.id.circleimageview); mcirclednetworkimageview.setimageurl(murl, volleysingleton.getinstance(mcontext).getimageloader()); } @override protected void onpostcreate(bundle savedinstancestate) { super.onpostcreate(savedinstancestate); customnavigationdrawer.syncstate(); } @override public void onconfigurationchanged(configuration newconfig) { super.onconfigurationchanged(newconfig); customnavigationdrawer.onconfigurationchanged(newconfig); } @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.menu_main, menu); return true; } }
activity_main.xml:
<android.support.v4.widget.drawerlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity"> <relativelayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="start" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin"> <com.android.volley.toolbox.networkimageview android:id="@+id/networkimageview" android:layout_width="300dp" android:layout_height="wrap_content" /> <com.example.networkimageview.circlednetworkimageview android:id="@+id/circleimageview" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_below="@+id/networkimageview" /> </relativelayout> </android.support.v4.widget.drawerlayout>
you can create new sample project , use sample code. hope helps!
Comments
Post a Comment