0

I have the following error when uploading video or images to the server in Android. Only some in some devices or some situations only occurs.

java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:864)
    Caused by: java.lang.OutOfMemoryError: (Heap Size=194364KB, Allocated=120067KB)
        at java.lang.String.<init>(String.java:422)
        at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:642)
        at java.lang.StringBuffer.toString(StringBuffer.java:723)
        at com.splunk.mint.network.io.OutputStreamMonitor.getHeaders(OutputStreamMonitor.java:83)
        at com.splunk.mint.network.socket.MonitoringSocketImpl.readingDone(MonitoringSocketImpl.java:154)
        at com.splunk.mint.network.io.InputStreamMonitorKitKat.tryToReadHeaders(InputStreamMonitorKitKat.java:190)
        at com.splunk.mint.network.io.InputStreamMonitorKitKat.updateBody(InputStreamMonitorKitKat.java:126)
        at com.splunk.mint.network.io.InputStreamMonitorKitKat.read(InputStreamMonitorKitKat.java:104)
        at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
        at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
        at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:82)
        at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
        at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
        at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
        at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
        at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
        at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:435)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:519)
        at com.sample.ws.AttachMentTask$HttpMultipartPostTask.doInBackground(AttachMentTask.java:112)
        at com.sample.ws.AttachMentTask$HttpMultipartPostTask.doInBackground(AttachMentTask.java:1)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        ... 4 more

I am using following code...

public class AttachMentTask {
    Attachment attachment;
    Context context;
    AttachMentUploadInterface mAttachMentUploadInterface;
    HttpMultipartPostTask mHttpMultipartPostTask;
    Uri mSaveduri;

    public AttachMentTask(Context context, Attachment attachment,
            AttachMentUploadInterface mAttachMentUploadInterface) {
        this.attachment = attachment;
        this.context = context;
        this.mAttachMentUploadInterface = mAttachMentUploadInterface;

    }

    public AttachMentTask(Context context, Attachment attachment,
            AttachMentUploadInterface mAttachMentUploadInterface, Uri uri) {
        this.attachment = attachment;
        this.context = context;
        this.mAttachMentUploadInterface = mAttachMentUploadInterface;
        this.mSaveduri = uri;
    }

    public void callWS() {
        mHttpMultipartPostTask = new HttpMultipartPostTask();
        mHttpMultipartPostTask.execute();
    }

    private class HttpMultipartPostTask extends
            AsyncTask<HttpResponse, Integer, String> {
        ProgressDialog pd;
        long totalSize = 0;

        // long presSizze = 0;

        @Override
        protected void onPreExecute() {

            pd = new ProgressDialog(context);
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.setMessage(context.getString(R.string.processing));
            pd.setCancelable(false);
            pd.setButton(DialogInterface.BUTTON_NEGATIVE, context
                    .getResources().getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            if (mHttpMultipartPostTask != null)
                                mHttpMultipartPostTask.cancel(true);
                            dialog.dismiss();
                        }
                    });

            pd.show();

        }

        @Override
        protected String doInBackground(HttpResponse... arg0) {
            if (attachment.getMimeType().contains("image"))
                Utils.resizeImage(mSaveduri, attachment, context);

            String serverResponse = null;
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(Constants.ATTACHMENT_URL);

            try {
                CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(
                        new com.sample.ws.ProgressListener() {

                            @Override
                            public void transferred(long num) {
                                // presSizze = num;
                                publishProgress((int) ((num / (float) totalSize) * 100));
                                // publishProgress(x);
                            }
                        });

                if (attachment.getMimeType().contains("image"))
                    multipartContent.addPart("IsAttachment", new StringBody(
                            "false"));
                else
                    multipartContent.addPart("IsAttachment", new StringBody(
                            "true"));
                multipartContent.addPart("ScaleType",
                        new StringBody(attachment.getScaleType() + ""));
                multipartContent.addPart("FileExtention", new StringBody(
                        attachment.getType()));
                /*
                 * if (attachment.getThumnail() != null) {
                 * 
                 * multipartContent.addPart("FILE", new ByteArrayBody(
                 * attachment.getThumnail(), "thumbnailurl")); }
                 */
                multipartContent.addPart("FILE",
                        new FileBody(attachment.getFile()));
                totalSize = multipartContent.getContentLength();

                // Send it
                httpPost.setEntity(multipartContent);
                HttpResponse response = httpClient.execute(httpPost,
                        httpContext);
                if (response != null) {

                    ByteArrayOutputStream outstream = new ByteArrayOutputStream();
                    response.getEntity().writeTo(outstream);
                    serverResponse = outstream.toString();

                }

            }

            catch (Exception e) {

            }
            return serverResponse;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            pd.setProgress((int) (progress[0]));
            // pd.setMessage("Uploading Picture..." + presSizze + "/" +
            // totalSize);
        }

        @Override
        protected void onPostExecute(String response) {
            if (pd.isShowing()) {
                pd.dismiss();
            }
            mAttachMentUploadInterface.onComplete(response);
        }
    }

}

//CustomMultiPartEntity.class

public class CustomMultiPartEntity extends MultipartEntity {

    private final ProgressListener listener;

    public CustomMultiPartEntity(ProgressListener listener) {
        super();
        this.listener = listener;
    }

    public CustomMultiPartEntity(final HttpMultipartMode mode,
            final ProgressListener listener) {
        super(mode);
        this.listener = listener;
    }

    public CustomMultiPartEntity(HttpMultipartMode mode, final String boundary,
            final Charset charset, final ProgressListener listener) {
        super(mode, boundary, charset);
        this.listener = listener;
    }

    @Override
    public void writeTo(final OutputStream outstream) throws IOException {
        super.writeTo(new CountingOutputStream(outstream, this.listener));
    }



    public static class CountingOutputStream extends FilterOutputStream {

        private final ProgressListener listener;
        private long transferred;

        public CountingOutputStream(final OutputStream out,
                final ProgressListener listener) {
            super(out);
            this.listener = listener;
            this.transferred = 0;
        }

        public void write(byte[] b, int off, int len) throws IOException {
            out.write(b, off, len);
            this.transferred += len;
            this.listener.transferred(this.transferred);
        }

        public void write(int b) throws IOException {
            out.write(b);
            this.transferred++;
            this.listener.transferred(this.transferred);
        }
    }
}

Please help me

Regards, dayakar

Dayakar Reddy
  • 179
  • 1
  • 5

1 Answers1

0
  <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:largeHeap="true"
         >

define largeheap = true in your manifest file under application tag. so that heap memory will be expanded. you are getting exception because size of your image or video will be too large. so use that parameter it might help you.

Aiyaz Parmar
  • 562
  • 6
  • 17
  • using `android:largeHeap="true"` doesn't actually useful answer... better to give other solution because largeHeap is not helpful for every situation or every file......this may cause an Exception later... – Pragnesh Ghoda シ Nov 26 '14 at 11:30
  • hey i was having same problem in my app it was occurring because background image of that app was 2mb so i degrade file size to 200kb and it worked very fine. i think you can use `System.gc()` that will manually tell your DVM that its time to run garbage collector. so try that if it works for you. – Aiyaz Parmar Nov 26 '14 at 11:35