将图像上传到服务器时,出现以下错误" java.lang.OutOfMemoryError:"

时间:2014-11-26 10:58:25

标签: android

在Android中将视频或图像上传到服务器时出现以下错误。某些设备或某些情况下只会出现一些。

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

我正在使用以下代码......

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);
        }
    }
}

请帮帮我

此致 dayakar

1 个答案:

答案 0 :(得分:0)

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

在应用程序标记下的清单文件中定义largeheap = true。 这样就可以扩展堆内存。你会遇到异常,因为你的图片或视频的尺寸太大了。所以使用它可能会帮助你。