android - File.createNewFile() is ignored when saving Camera photo -
i having issue attempting save camera taken image phone's storage, keep getting error have not seen before saying file.createnewfile() ignored. how can corrected photo can saved? or there another, possibly better, way can save image has been captured camera , display in imageview well? problem area can found in onactivityresult() under pick_image_camera else if statement.
main activity
package com.example.stins.orbotcamera; import android.manifest; import android.app.progressdialog; import android.content.context; import android.content.dialoginterface; import android.content.intent; import android.content.pm.packagemanager; import android.database.cursor; import android.graphics.bitmap; import android.graphics.color; import android.graphics.drawable.bitmapdrawable; import android.net.uri; import android.os.asynctask; import android.os.build; import android.os.environment; import android.provider.mediastore; import android.provider.settings; import android.provider.syncstatecontract; import android.support.design.widget.coordinatorlayout; import android.support.design.widget.floatingactionbutton; import android.support.design.widget.snackbar; import android.support.v4.app.activitycompat; import android.support.v4.content.contextcompat; import android.support.v4.content.fileprovider; import android.support.v7.app.alertdialog; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.support.v7.widget.toolbar; import android.util.base64; import android.util.log; import android.view.menu; import android.view.menuinflater; import android.view.menuitem; import android.view.view; import android.widget.edittext; import android.widget.imageview; import android.widget.textview; import android.widget.toast; import net.gotev.uploadservice.multipartuploadrequest; import net.gotev.uploadservice.uploadnotificationconfig; import java.io.bytearrayoutputstream; import java.io.file; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.text.simpledateformat; import java.util.date; import java.util.hashmap; import java.util.locale; import java.util.uuid; public class mainactivity extends appcompatactivity implements view.onclicklistener { private floatingactionbutton fab; private imageview imageview; private uri file; private gpstracker gps; private edittext imagecomment; private coordinatorlayout coordinatorlayout; private textview imagelat, imagelong; private string mlat, mlong; private file destination = null; private string imgpath = null; string mcurrentphotopath; public static final string upload_url = "http://192.168.1.77/uploadexamples/upload.php"; private bitmap bitmap; private final int pick_image_camera = 1, pick_image_gallery = 2; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); fab = (floatingactionbutton) findviewbyid(r.id.fab); imageview = (imageview) findviewbyid(r.id.imageview); imagecomment = (edittext) findviewbyid(r.id.imagecomment); imagelat = (textview) findviewbyid(r.id.imagelat); imagelong = (textview) findviewbyid(r.id.imagelong); //fab.setonclicklistener(this); if (contextcompat.checkselfpermission(this, manifest.permission.camera) != packagemanager.permission_granted) { fab.setenabled(false); imagecomment.setenabled(false); activitycompat.requestpermissions(this, new string[]{manifest.permission.camera, manifest.permission.write_external_storage,manifest.permission.read_external_storage, manifest.permission.access_fine_location, manifest.permission.access_coarse_location}, 0); } fab.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { selectimage(); } }); } @override public void onrequestpermissionsresult(int requestcode, string[] permissions, int[] grantresults) { if (requestcode == 0) { if (grantresults.length > 0 && grantresults[0] == packagemanager.permission_granted && grantresults[1] == packagemanager.permission_granted) { fab.setenabled(true); imagecomment.setenabled(true); } else{ coordinatorlayout = (coordinatorlayout) findviewbyid(r.id.coordinatorlayout); final snackbar snackbar = snackbar .make(coordinatorlayout, "accept permissions use app", snackbar.length_indefinite); snackbar.setaction("ok", new view.onclicklistener() { @override public void onclick(view view) { intent = getbasecontext().getpackagemanager() .getlaunchintentforpackage( getbasecontext().getpackagename() ); i.addflags(intent.flag_activity_clear_top); startactivity(i); } }); snackbar.setactiontextcolor(color.white); view sbview = snackbar.getview(); textview textview = (textview) sbview.findviewbyid(android.support.design.r.id.snackbar_text); textview.settextcolor(color.gray); snackbar.show(); } } } public void selectimage(){ try { packagemanager pm = getpackagemanager(); int hasperm = pm.checkpermission(manifest.permission.camera, getpackagename()); if (hasperm == packagemanager.permission_granted) { final charsequence[] options = {"take photo", "choose gallery","cancel"}; android.support.v7.app.alertdialog.builder builder = new android.support.v7.app.alertdialog.builder(mainactivity.this); builder.settitle("select option"); builder.setitems(options, new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int item) { if (options[item].equals("take photo")) { dialog.dismiss(); intent intent = new intent(mediastore.action_image_capture); startactivityforresult(intent, pick_image_camera); } else if (options[item].equals("choose gallery")) { dialog.dismiss(); intent pickphoto = new intent(intent.action_pick, mediastore.images.media.external_content_uri); startactivityforresult(pickphoto, pick_image_gallery); } else if (options[item].equals("cancel")) { dialog.dismiss(); } } }); builder.show(); } else toast.maketext(this, "camera permission error", toast.length_short).show(); } catch (exception e) { toast.maketext(this, "camera permission error", toast.length_short).show(); e.printstacktrace(); } } public void uploadimage() { //getting name image string name = imagecomment.gettext().tostring().trim(); //getting actual path of image string path = getpath(file); //uploading code try { string uploadid = uuid.randomuuid().tostring(); //creating multi part request new multipartuploadrequest(this, uploadid, upload_url) .addfiletoupload(path, "image") //adding file .addparameter("name", name) //adding text parameter request .addparameter("latitude", mlat) .addparameter("longitude", mlong) .setnotificationconfig(new uploadnotificationconfig()) .setmaxretries(2) .startupload(); //starting upload log.d("upload", "uploadimage: " + path); } catch (exception exc) { toast.maketext(this, exc.getmessage(), toast.length_short).show(); } } public string getpath(uri uri) { cursor cursor = getcontentresolver().query(uri, null, null, null, null); if (cursor != null) { cursor.movetofirst(); } string document_id = null; if (cursor != null) { document_id = cursor.getstring(0); } if (document_id != null) { document_id = document_id.substring(document_id.lastindexof(":") + 1); } if (cursor != null) { cursor.close(); } cursor = getcontentresolver().query( android.provider.mediastore.images.media.external_content_uri, null, mediastore.images.media._id + " = ? ", new string[]{document_id}, null); if (cursor != null) { cursor.movetofirst(); } string path = null; if (cursor != null) { path = cursor.getstring(cursor.getcolumnindex(mediastore.images.media.data)); } if (cursor != null) { cursor.close(); } return path; } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { if (requestcode == 0 && resultcode == result_ok && data != null && data.getdata() != null) { file = data.getdata(); try { bitmap = mediastore.images.media.getbitmap(getcontentresolver(), file); imageview.setimagebitmap(bitmap); imagecomment.setvisibility(view.visible); } catch (ioexception e) { e.printstacktrace(); } } if (requestcode == 0) { gps = new gpstracker(mainactivity.this); if (resultcode == result_ok) { if (gps.cangetlocation()) { double latitude = gps.getlatitude(); double longitude = gps.getlongitude(); mlat = double.tostring(latitude); mlong = double.tostring(longitude); imagelat.settext(mlat); imagelong.settext(mlong); // \n new line //toast.maketext(getapplicationcontext(), "your location - \nlat: " + latitude + "\nlong: " + longitude, toast.length_long).show(); coordinatorlayout = (coordinatorlayout) findviewbyid(r.id.coordinatorlayout); final snackbar snackbar = snackbar .make(coordinatorlayout, "current location recorded", snackbar.length_long); snackbar.setactiontextcolor(color.white); view sbview = snackbar.getview(); textview textview = (textview) sbview.findviewbyid(android.support.design.r.id.snackbar_text); textview.setcompounddrawableswithintrinsicbounds(r.drawable.ic_location_on_white_24dp,0,0,0); textview.settextcolor(color.white); snackbar.show(); } else { // can't location. // gps or network not enabled. // ask user enable gps/network in settings. } } else if (resultcode == result_canceled) { // user cancelled image capture coordinatorlayout = (coordinatorlayout) findviewbyid(r.id.coordinatorlayout); final snackbar snackbar = snackbar .make(coordinatorlayout,"picture cancelled", snackbar.length_short); view sbview = snackbar.getview(); textview textview = (textview) sbview.findviewbyid(android.support.design.r.id.snackbar_text); textview.setcompounddrawableswithintrinsicbounds(r.drawable.ic_cancel_white_24dp,0,0,0); textview.settextcolor(color.white); snackbar.show(); } else { // failed capture image coordinatorlayout = (coordinatorlayout) findviewbyid(r.id.coordinatorlayout); final snackbar snackbar = snackbar .make(coordinatorlayout,"error taking picture", snackbar.length_short); view sbview = snackbar.getview(); textview textview = (textview) sbview.findviewbyid(android.support.design.r.id.snackbar_text); textview.setcompounddrawableswithintrinsicbounds(r.drawable.ic_error_outline_white_24dp,0,0,0); textview.settextcolor(color.white); snackbar.show(); } } if (requestcode == pick_image_camera && (data!=null)) { try { file = data.getdata(); bitmap = (bitmap) data.getextras().get("data"); bytearrayoutputstream bytes = new bytearrayoutputstream(); //bitmap.compress(bitmap.compressformat.jpeg, 50, bytes); log.e("activity", "pick camera::>>> "); string timestamp = new simpledateformat("yyyymmdd_hhmmss", locale.getdefault()).format(new date()); destination = new file(environment.getexternalstoragedirectory() + "/" + getstring(r.string.app_name), "img_" + timestamp + ".jpg"); fileoutputstream fo; try { destination.createnewfile(); fo = new fileoutputstream(destination); fo.write(bytes.tobytearray()); fo.close(); } catch (ioexception e) { e.printstacktrace(); } imgpath = destination.getabsolutepath(); imageview.setimagebitmap(bitmap); imagecomment.setvisibility(view.visible); } catch (exception e) { e.printstacktrace(); } } else if (requestcode == pick_image_gallery && (data!=null)) { file = data.getdata(); try { bitmap = mediastore.images.media.getbitmap(this.getcontentresolver(), file); log.e("activity", "pick gallery::>>> "); imgpath = getpath(file); destination = new file(imgpath); imageview.setimagebitmap(bitmap); imagecomment.setvisibility(view.visible); } catch (exception e) { e.printstacktrace(); } } } private static file getoutputmediafile() { file mediastoragedir = new file(environment.getexternalstoragepublicdirectory( environment.directory_pictures), "orbotcamera"); if (!mediastoragedir.exists()) { if (!mediastoragedir.mkdirs()) { log.d("orbotcamera", "failed create directory"); return null; } } string timestamp = new simpledateformat("yyyymmdd_hhmmss").format(new date()); return new file(mediastoragedir.getpath() + file.separator + "img_" + timestamp + ".jpg"); } @override public boolean oncreateoptionsmenu(menu menu) { menuinflater inflater = getmenuinflater(); inflater.inflate(r.menu.menu_main, menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { int id = item.getitemid(); switch (item.getitemid()) { case r.id.action_send: if(imageview.getdrawable()==null){ coordinatorlayout = (coordinatorlayout) findviewbyid(r.id.coordinatorlayout); final snackbar snackbar = snackbar .make(coordinatorlayout,"sorry, you'll need image that!", snackbar.length_short); view sbview = snackbar.getview(); textview textview = (textview) sbview.findviewbyid(android.support.design.r.id.snackbar_text); textview.setcompounddrawableswithintrinsicbounds(r.drawable.ic_error_outline_white_24dp,0,0,0); textview.settextcolor(color.white); snackbar.show(); } else { uploadimage(); } return true; } return super.onoptionsitemselected(item); } @override public void onbackpressed() { new alertdialog.builder(this, r.style.theme_appcompat_dialog_alert) .settitle("exit") .setmessage("are sure want close orbot camera?") .setpositivebutton("yes", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { finish(); } }) .setnegativebutton("no", null) .show(); } @override public void onclick(view v) { intent i; if(v.getid()==r.id.fab) { intent intent = new intent(); intent.settype("image/*"); intent.setaction(intent.action_get_content); startactivityforresult(intent.createchooser(intent, "select picture"), 0); } } }
logcat
07-26 10:56:30.757 23865-23865/com.example.stins.orbotcamera e/androidruntime: fatal exception: main process: com.example.stins.orbotcamera, pid: 23865 java.lang.nullpointerexception: uri @ com.android.internal.util.preconditions.checknotnull(preconditions.java:111) @ android.content.contentresolver.query(contentresolver.java:519) @ android.content.contentresolver.query(contentresolver.java:478) @ com.example.stins.orbotcamera.mainactivity.getpath(mainactivity.java:215) @ com.example.stins.orbotcamera.mainactivity.uploadimage(mainactivity.java:188) @ com.example.stins.orbotcamera.mainactivity.onoptionsitemselected(mainactivity.java:427) @ android.app.activity.onmenuitemselected(activity.java:3383) @ android.support.v4.app.fragmentactivity.onmenuitemselected(fragmentactivity.java:408) @ android.support.v7.app.appcompatactivity.onmenuitemselected(appcompatactivity.java:195) @ android.support.v7.view.windowcallbackwrapper.onmenuitemselected(windowcallbackwrapper.java:113) @ android.support.v7.app.appcompatdelegateimplv9.onmenuitemselected(appcompatdelegateimplv9.java:679) @ android.support.v7.view.menu.menubuilder.dispatchmenuitemselected(menubuilder.java:822) @ android.support.v7.view.menu.menuitemimpl.invoke(menuitemimpl.java:156) @ android.support.v7.view.menu.menubuilder.performitemaction(menubuilder.java:969) @ android.support.v7.view.menu.menubuilder.performitemaction(menubuilder.java:959) @ android.support.v7.widget.actionmenuview.invokeitem(actionmenuview.java:623) @ android.support.v7.view.menu.actionmenuitemview.onclick(actionmenuitemview.java:154) @ android.view.view.performclick(view.java:6261) @ android.widget.textview.performclick(textview.java:11157) @ android.view.view$performclick.run(view.java:23748) @ android.os.handler.handlecallback(handler.java:751) @ android.os.handler.dispatchmessage(handler.java:95) @ android.os.looper.loop(looper.java:154) @ android.app.activitythread.main(activitythread.java:6776) @ java.lang.reflect.method.invoke(native method) @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:1520) @ com.android.internal.os.zygoteinit.main(zygoteinit.java:1410)
try using method
string file_path = environment.getexternalstoragepublicdirectory(environment.directory_downloads)+""; file dir = new file(file_path); if(!dir.exists()){ dir.mkdirs(); } file cachedir = getcachedir(); file file1 = new file(cachedir, dir.tostring()); file1.delete(); file = new file(dir, "temp.jpeg"); fileoutputstream fo; try { fo = new fileoutputstream(file); bitmap.compress(bitmap.compressformat.jpeg, 100, fo); fo.flush(); fo.close(); } catch (ioexception e) { e.printstacktrace(); }
Comments
Post a Comment