php - Android - send image to server - Async Task An error occured while executing doInBackground() -
i want make app takes picture , sends online server. have read many tutorials , articles , code far:
import android.app.activity; import android.content.intent; import android.content.res.configuration; import android.graphics.bitmap; import android.net.uri; import android.os.asynctask; import android.os.bundle; import android.os.environment; import android.provider.mediastore; import android.util.log; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.imageview; import android.widget.toast; import org.apache.http.httpresponse; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import java.io.bytearrayinputstream; import java.io.bytearrayoutputstream; import java.io.file; import java.io.ioexception; import java.io.inputstream; import java.text.simpledateformat; import java.util.date; public class mainactivity extends activity implements onclicklistener { private button mtakephoto; private imageview mimageview; private static final string tag = "upload"; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mtakephoto = (button) findviewbyid(r.id.take_photo); mimageview = (imageview) findviewbyid(r.id.imageview); mtakephoto.setonclicklistener(this); } @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.menu_main, menu); return true; } @override public void onclick(view v) { // todo auto-generated method stub int id = v.getid(); switch (id) { case r.id.take_photo: takephoto(); break; } } private void takephoto() { intent cameraintent = new intent(android.provider.mediastore.action_image_capture); startactivityforresult(cameraintent, 1); } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { // todo auto-generated method stub log.i(tag, "onactivityresult: " + this); if (requestcode == request_take_photo && resultcode == activity.result_ok) { bitmap photo = (bitmap) data.getextras().get("data"); mimageview.setimagebitmap(photo); try { sendphoto(photo); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } } } private void sendphoto(bitmap bitmap) throws exception { new uploadtask().execute(bitmap); } private class uploadtask extends asynctask<bitmap, void, void> { protected void doinbackground(bitmap... bitmaps) { if (bitmaps[0] == null) return null; setprogress(0); bitmap bitmap = bitmaps[0]; bytearrayoutputstream stream = new bytearrayoutputstream(); bitmap.compress(bitmap.compressformat.png, 100, stream); // convert bitmap bytearrayoutputstream inputstream in = new bytearrayinputstream(stream.tobytearray()); // convert bytearrayoutputstream bytearrayinputstream defaulthttpclient httpclient = new defaulthttpclient(); try { httppost httppost = new httppost( "http://xxxx/photo.php"); // server multipartentity reqentity = new multipartentity(); reqentity.addpart("myfile", system.currenttimemillis() + ".jpg", in); httppost.setentity(reqentity); log.i(tag, "request " + httppost.getrequestline()); httpresponse response = null; try { response = httpclient.execute(httppost); } catch (clientprotocolexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } try { if (response != null) log.i(tag, "response " + response.getstatusline().tostring()); } { } } { } if (in != null) { try { in.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } if (stream != null) { try { stream.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } return null; } @override protected void onprogressupdate(void... values) { // todo auto-generated method stub super.onprogressupdate(values); } @override protected void onpostexecute(void result) { // todo auto-generated method stub super.onpostexecute(result); toast.maketext(mainactivity.this, r.string.uploaded, toast.length_long).show(); } } @override protected void onresume() { // todo auto-generated method stub super.onresume(); log.i(tag, "onresume: " + this); } @override protected void onpause() { // todo auto-generated method stub super.onpause(); } @override public void onconfigurationchanged(configuration newconfig) { // todo auto-generated method stub super.onconfigurationchanged(newconfig); } @override protected void onsaveinstancestate(bundle outstate) { // todo auto-generated method stub super.onsaveinstancestate(outstate); log.i(tag, "onsaveinstancestate"); } string mcurrentphotopath; static final int request_take_photo = 1; file photofile = null; private void dispatchtakepictureintent() { intent takepictureintent = new intent(mediastore.action_image_capture); // ensure there's camera activity handle intent if (takepictureintent.resolveactivity(getpackagemanager()) != null) { // create file photo should go file photofile = null; try { photofile = createimagefile(); } catch (ioexception ex) { // error occurred while creating file } // continue if file created if (photofile != null) { takepictureintent.putextra(mediastore.extra_output, uri.fromfile(photofile)); startactivityforresult(takepictureintent, request_take_photo); } } } private file createimagefile() throws ioexception { // create image file name string timestamp = new simpledateformat("yyyymmdd_hhmmss").format(new date()); string imagefilename = "jpeg_" + timestamp + "_"; string storagedir = environment.getexternalstoragedirectory() + "/picupload"; file dir = new file(storagedir); if (!dir.exists()) dir.mkdir(); file image = new file(storagedir + "/" + imagefilename + ".jpg"); // save file: path use action_view intents mcurrentphotopath = image.getabsolutepath(); log.i(tag, "photo path = " + mcurrentphotopath); return image; } }
multipartentity.java
import org.apache.http.header; import org.apache.http.httpentity; import org.apache.http.message.basicheader; import java.io.bytearrayinputstream; import java.io.bytearrayoutputstream; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; public class multipartentity implements httpentity { private string boundary = null; bytearrayoutputstream out = new bytearrayoutputstream(); boolean issetlast = false; boolean issetfirst = false; public multipartentity() { this.boundary = system.currenttimemillis() + ""; } public void writefirstboundaryifneeds(){ if(!issetfirst){ try { out.write(("--" + boundary + "\r\n").getbytes()); } catch (final ioexception e) { } } issetfirst = true; } public void writelastboundaryifneeds() { if(issetlast){ return ; } try { out.write(("\r\n--" + boundary + "--\r\n").getbytes()); } catch (final ioexception e) { } issetlast = true; } public void addpart(final string key, final string value) { writefirstboundaryifneeds(); try { out.write(("content-disposition: form-data; name=\"" +key+"\"\r\n").getbytes()); out.write("content-type: text/plain; charset=utf-8\r\n".getbytes()); out.write("content-transfer-encoding: 8bit\r\n\r\n".getbytes()); out.write(value.getbytes()); out.write(("\r\n--" + boundary + "\r\n").getbytes()); } catch (final ioexception e) { } } public void addpart(final string key, final string filename, final inputstream fin){ addpart(key, filename, fin, "application/octet-stream"); } public void addpart(final string key, final string filename, final inputstream fin, string type){ writefirstboundaryifneeds(); try { type = "content-type: "+type+"\r\n"; out.write(("content-disposition: form-data; name=\""+ key+"\"; filename=\"" + filename + "\"\r\n").getbytes()); out.write(type.getbytes()); out.write("content-transfer-encoding: binary\r\n\r\n".getbytes()); final byte[] tmp = new byte[4096]; int l = 0; while ((l = fin.read(tmp)) != -1) { out.write(tmp, 0, l); } out.flush(); } catch (final ioexception e) { } { try { fin.close(); } catch (final ioexception e) { } } } public void addpart(final string key, final file value) { try { addpart(key, value.getname(), new fileinputstream(value)); } catch (final filenotfoundexception e) { } } @override public long getcontentlength() { writelastboundaryifneeds(); return out.tobytearray().length; } @override public header getcontenttype() { return new basicheader("content-type", "multipart/form-data; boundary=" + boundary); } @override public boolean ischunked() { return false; } @override public boolean isrepeatable() { return false; } @override public boolean isstreaming() { return false; } @override public void writeto(final outputstream outstream) throws ioexception { outstream.write(out.tobytearray()); } @override public header getcontentencoding() { return null; } @override public void consumecontent() throws ioexception, unsupportedoperationexception { if (isstreaming()) { throw new unsupportedoperationexception( "streaming entity not implement #consumecontent()"); } } @override public inputstream getcontent() throws ioexception, unsupportedoperationexception { return new bytearrayinputstream(out.tobytearray()); } }
androidmanifest:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.diana.data" > <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.read_external_storage" /> <uses-permission android:name="android.permission.write_external_storage" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name=".mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest>
and php:
<?php // path move uploaded files $target_path = "http://xxxx/photos/"; // array final json respone $response = array(); // getting server ip address $server_ip = gethostbyname(gethostname()); // final file url being uploaded $file_upload_url = 'http://' . $server_ip . '/' . 'androidfileupload' . '/' . $target_path; if (isset($_files['image']['name'])) { $target_path = $target_path . basename($_files['image']['name']); $response['file_name'] = basename($_files['image']['name']); $response['email'] = $email; try { // throws exception incase file not being moved if (!move_uploaded_file($_files['image']['tmp_name'], $target_path)) { // make error flag true $response['error'] = true; $response['message'] = 'could not move file!'; } // file uploaded $response['message'] = 'file uploaded successfully!'; $response['error'] = false; $response['file_path'] = $file_upload_url . basename($_files['image']['name']); } catch (exception $e) { // exception occurred. make error flag true $response['error'] = true; $response['message'] = $e->getmessage(); } } else { // file parameter missing $response['error'] = true; $response['message'] = 'not received file!f'; } // echo final json response client echo json_encode($response); ?>
the problem crashes when gets line , have no idea why.
response = httpclient.execute(httppost);
this logcat:
07-14 13:54:26.520 27507-28071/com.example.diana.data e/androidruntime﹕ fatal exception: asynctask #1 java.lang.runtimeexception: error occured while executing doinbackground() @ android.os.asynctask$3.done(asynctask.java:299) @ java.util.concurrent.futuretask.finishcompletion(futuretask.java:352) @ java.util.concurrent.futuretask.setexception(futuretask.java:219) @ java.util.concurrent.futuretask.run(futuretask.java:239) @ android.os.asynctask$serialexecutor$1.run(asynctask.java:230) @ java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1080) @ java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:573) @ java.lang.thread.run(thread.java:841) caused by: java.lang.securityexception: permission denied (missing internet permission?) @ java.net.inetaddress.lookuphostbyname(inetaddress.java:441) @ java.net.inetaddress.getallbynameimpl(inetaddress.java:239) @ java.net.inetaddress.getallbyname(inetaddress.java:218) @ org.apache.http.impl.conn.defaultclientconnectionoperator.openconnection(defaultclientconnectionoperator.java:141) @ org.apache.http.impl.conn.abstractpoolentry.open(abstractpoolentry.java:164) @ org.apache.http.impl.conn.abstractpooledconnadapter.open(abstractpooledconnadapter.java:119) @ org.apache.http.impl.client.defaultrequestdirector.execute(defaultrequestdirector.java:360) @ org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:555) @ org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:487) @ org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:465) @ com.example.diana.data.mainactivity$uploadtask.doinbackground(mainactivity.java:116) @ com.example.diana.data.mainactivity$uploadtask.doinbackground(mainactivity.java:91) @ android.os.asynctask$2.call(asynctask.java:287) @ java.util.concurrent.futuretask.run(futuretask.java:234) at android.os.asynctask$serialexecutor$1.run(asynctask.java:230) at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1080) at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:573) at java.lang.thread.run(thread.java:841) caused by: libcore.io.gaiexception: getaddrinfo failed: eai_nodata (no address associated hostname) @ libcore.io.posix.getaddrinfo(native method) @ libcore.io.forwardingos.getaddrinfo(forwardingos.java:61) @ java.net.inetaddress.lookuphostbyname(inetaddress.java:428) at java.net.inetaddress.getallbynameimpl(inetaddress.java:239) at java.net.inetaddress.getallbyname(inetaddress.java:218) at org.apache.http.impl.conn.defaultclientconnectionoperator.openconnection(defaultclientconnectionoperator.java:141) at org.apache.http.impl.conn.abstractpoolentry.open(abstractpoolentry.java:164) at org.apache.http.impl.conn.abstractpooledconnadapter.open(abstractpooledconnadapter.java:119) at org.apache.http.impl.client.defaultrequestdirector.execute(defaultrequestdirector.java:360) at org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:555) at org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:487) at org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:465) at com.example.diana.data.mainactivity$uploadtask.doinbackground(mainactivity.java:116) at com.example.diana.data.mainactivity$uploadtask.doinbackground(mainactivity.java:91) at android.os.asynctask$2.call(asynctask.java:287) at java.util.concurrent.futuretask.run(futuretask.java:234) at android.os.asynctask$serialexecutor$1.run(asynctask.java:230) at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1080) at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:573) at java.lang.thread.run(thread.java:841) caused by: libcore.io.errnoexception: getaddrinfo failed: eacces (permission denied) at libcore.io.posix.getaddrinfo(native method) at libcore.io.forwardingos.getaddrinfo(forwardingos.java:61) at java.net.inetaddress.lookuphostbyname(inetaddress.java:428) at java.net.inetaddress.getallbynameimpl(inetaddress.java:239) at java.net.inetaddress.getallbyname(inetaddress.java:218) at org.apache.http.impl.conn.defaultclientconnectionoperator.openconnection(defaultclientconnectionoperator.java:141) at org.apache.http.impl.conn.abstractpoolentry.open(abstractpoolentry.java:164) at org.apache.http.impl.conn.abstractpooledconnadapter.open(abstractpooledconnadapter.java:119) at org.apache.http.impl.client.defaultrequestdirector.execute(defaultrequestdirector.java:360) at org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:555) at org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:487) at org.apache.http.impl.client.abstracthttpclient.execute(abstracthttpclient.java:465) at com.example.diana.data.mainactivity$uploadtask.doinbackground(mainactivity.java:116) at com.example.diana.data.mainactivity$uploadtask.doinbackground(mainactivity.java:91) at android.os.asynctask$2.call(asynctask.java:287) at java.util.concurrent.futuretask.run(futuretask.java:234) at android.os.asynctask$serialexecutor$1.run(asynctask.java:230) at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1080) at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:573) at java.lang.thread.run(thread.java:841)
any ideas/tips might problem?
as stacktrace said:
caused by: java.lang.securityexception: permission denied (missing internet permission?)
you need add internet permission inside manifest file.
<uses-permission android:name="android.permission.internet" />
another problem is:
caused by: libcore.io.gaiexception: getaddrinfo failed: eai_nodata (no address associated hostname)
probably need check hostname using sending request. (http://xxxx/photo.php)
Comments
Post a Comment