Example usage for java.lang OutOfMemoryError getMessage

List of usage examples for java.lang OutOfMemoryError getMessage

Introduction

In this page you can find the example usage for java.lang OutOfMemoryError getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Corrects the orientation of a Bitmap. Orientation, depending of the device
 * , is not correctly set in the EXIF data of the taken image when it is saved
 * into disk./*from w w w  . j ava2 s. co  m*/
 * 
 * Explanation:
 *    Camera orientation is not working ok (as is when capturing an image) because 
 *  OEMs do not adhere to the standard. So, each company does this following their 
 *  own way.
 * 
 * @param imagePath   path to the file
 * @return
 */
public static Bitmap media_correctImageOrientation(String imagePath) {
    Bitmap res = null;

    try {
        File f = new File(imagePath);
        ExifInterface exif = new ExifInterface(f.getPath());
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        int angle = 0;

        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
            angle = 90;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
            angle = 180;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
            angle = 270;
        }

        Matrix mat = new Matrix();
        mat.postRotate(angle);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;

        Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
        res = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);

    } catch (OutOfMemoryError e) {
        if (LOG_ENABLE)
            Log.e(TAG, "media_correctImageOrientation() [OutOfMemory!]: " + e.getMessage(), e);
    } catch (Exception e) {
        if (LOG_ENABLE)
            Log.e(TAG, "media_correctImageOrientation(): " + e.getMessage(), e);
    } catch (Throwable e) {
        if (LOG_ENABLE)
            Log.e(TAG, "media_correctImageOrientation(): " + e.getMessage(), e);
    }

    return res;
}

From source file:org.matrix.console.activity.RoomActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();//from ww  w  . ja v a 2s  . c  om

    if (CommonActivityUtils.shouldRestartApp()) {
        if (intent.hasExtra(EXTRA_START_FROM_PUSH)) {
            Log.e(LOG_TAG, "Room activity is started from push but the application should be restarted");
        } else {
            Log.e(LOG_TAG, "Restart the application.");
            CommonActivityUtils.restartApp(this);
        }
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_room);

    if (!intent.hasExtra(EXTRA_ROOM_ID)) {
        Log.e(LOG_TAG, "No room ID extra.");
        finish();
        return;
    }

    if (intent.hasExtra(EXTRA_START_CALL_ID)) {
        mCallId = intent.getStringExtra(EXTRA_START_CALL_ID);
    }

    // the user has tapped on the "View" notification button
    if ((null != intent.getAction()) && (intent.getAction().startsWith(NotificationUtils.TAP_TO_VIEW_ACTION))) {
        // remove any pending notifications
        NotificationManager notificationsManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationsManager.cancelAll();
    }

    mPendingThumbnailUrl = null;
    mPendingMediaUrl = null;
    mPendingMimeType = null;
    mPendingFilename = null;

    if (null != savedInstanceState) {
        if (savedInstanceState.containsKey(PENDING_THUMBNAIL_URL)) {
            mPendingThumbnailUrl = savedInstanceState.getString(PENDING_THUMBNAIL_URL);
            Log.d(LOG_TAG, "Restore mPendingThumbnailUrl " + mPendingThumbnailUrl);
        }

        if (savedInstanceState.containsKey(PENDING_MEDIA_URL)) {
            mPendingMediaUrl = savedInstanceState.getString(PENDING_MEDIA_URL);
            Log.d(LOG_TAG, "Restore mPendingMediaUrl " + mPendingMediaUrl);
        }

        if (savedInstanceState.containsKey(PENDING_MIMETYPE)) {
            mPendingMimeType = savedInstanceState.getString(PENDING_MIMETYPE);
            Log.d(LOG_TAG, "Restore mPendingMimeType " + mPendingMimeType);
        }

        if (savedInstanceState.containsKey(PENDING_FILENAME)) {
            mPendingFilename = savedInstanceState.getString(PENDING_FILENAME);
            Log.d(LOG_TAG, "Restore mPendingFilename " + mPendingFilename);
        }
    }

    String roomId = intent.getStringExtra(EXTRA_ROOM_ID);
    Log.i(LOG_TAG, "Displaying " + roomId);

    mEditText = (EditText) findViewById(R.id.editText_messageBox);

    mSendButton = (ImageButton) findViewById(R.id.button_send);
    mSendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // send the previewed image ?
            if (null != mPendingThumbnailUrl) {
                boolean sendMedia = true;

                // check if the media could be resized
                if ("image/jpeg".equals(mPendingMimeType)) {

                    System.gc();
                    FileInputStream imageStream = null;

                    try {
                        Uri uri = Uri.parse(mPendingMediaUrl);
                        final String filename = uri.getPath();

                        final int rotationAngle = ImageUtils.getRotationAngleForBitmap(RoomActivity.this, uri);

                        imageStream = new FileInputStream(new File(filename));

                        int fileSize = imageStream.available();

                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                        options.outWidth = -1;
                        options.outHeight = -1;

                        // get the full size bitmap
                        Bitmap fullSizeBitmap = null;
                        try {
                            fullSizeBitmap = BitmapFactory.decodeStream(imageStream, null, options);
                        } catch (OutOfMemoryError e) {
                            Log.e(LOG_TAG, "Onclick BitmapFactory.decodeStream : " + e.getMessage());
                        }

                        final ImageSize fullImageSize = new ImageSize(options.outWidth, options.outHeight);

                        imageStream.close();

                        int maxSide = (fullImageSize.mHeight > fullImageSize.mWidth) ? fullImageSize.mHeight
                                : fullImageSize.mWidth;

                        // can be rescaled ?
                        if (maxSide > SMALL_IMAGE_SIZE) {
                            ImageSize largeImageSize = null;

                            int divider = 2;

                            if (maxSide > LARGE_IMAGE_SIZE) {
                                largeImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider,
                                        (fullImageSize.mHeight + (divider - 1)) / divider);
                                divider *= 2;
                            }

                            ImageSize mediumImageSize = null;

                            if (maxSide > MEDIUM_IMAGE_SIZE) {
                                mediumImageSize = new ImageSize(
                                        (fullImageSize.mWidth + (divider - 1)) / divider,
                                        (fullImageSize.mHeight + (divider - 1)) / divider);
                                divider *= 2;
                            }

                            ImageSize smallImageSize = null;

                            if (maxSide > SMALL_IMAGE_SIZE) {
                                smallImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider,
                                        (fullImageSize.mHeight + (divider - 1)) / divider);
                            }

                            FragmentManager fm = getSupportFragmentManager();
                            ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm
                                    .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG);

                            if (fragment != null) {
                                fragment.dismissAllowingStateLoss();
                            }

                            final ArrayList<ImageCompressionDescription> textsList = new ArrayList<ImageCompressionDescription>();
                            final ArrayList<ImageSize> sizesList = new ArrayList<ImageSize>();

                            ImageCompressionDescription description = new ImageCompressionDescription();
                            description.mCompressionText = getString(R.string.compression_opt_list_original);
                            description.mCompressionInfoText = fullImageSize.mWidth + "x"
                                    + fullImageSize.mHeight + " ("
                                    + android.text.format.Formatter.formatFileSize(RoomActivity.this, fileSize)
                                    + ")";

                            textsList.add(description);
                            sizesList.add(fullImageSize);

                            if (null != largeImageSize) {
                                int estFileSize = largeImageSize.mWidth * largeImageSize.mHeight * 2 / 10 / 1024
                                        * 1024;

                                description = new ImageCompressionDescription();
                                description.mCompressionText = getString(R.string.compression_opt_list_large);
                                description.mCompressionInfoText = largeImageSize.mWidth + "x"
                                        + largeImageSize.mHeight + " (~" + android.text.format.Formatter
                                                .formatFileSize(RoomActivity.this, estFileSize)
                                        + ")";

                                textsList.add(description);
                                sizesList.add(largeImageSize);
                            }

                            if (null != mediumImageSize) {
                                int estFileSize = mediumImageSize.mWidth * mediumImageSize.mHeight * 2 / 10
                                        / 1024 * 1024;

                                description = new ImageCompressionDescription();
                                description.mCompressionText = getString(R.string.compression_opt_list_medium);
                                description.mCompressionInfoText = mediumImageSize.mWidth + "x"
                                        + mediumImageSize.mHeight + " (~" + android.text.format.Formatter
                                                .formatFileSize(RoomActivity.this, estFileSize)
                                        + ")";

                                textsList.add(description);
                                sizesList.add(mediumImageSize);
                            }

                            if (null != smallImageSize) {
                                int estFileSize = smallImageSize.mWidth * smallImageSize.mHeight * 2 / 10 / 1024
                                        * 1024;

                                description = new ImageCompressionDescription();
                                description.mCompressionText = getString(R.string.compression_opt_list_small);
                                description.mCompressionInfoText = smallImageSize.mWidth + "x"
                                        + smallImageSize.mHeight + " (~" + android.text.format.Formatter
                                                .formatFileSize(RoomActivity.this, estFileSize)
                                        + ")";

                                textsList.add(description);
                                sizesList.add(smallImageSize);
                            }

                            fragment = ImageSizeSelectionDialogFragment.newInstance(textsList);
                            fragment.setListener(new ImageSizeSelectionDialogFragment.ImageSizeListener() {
                                @Override
                                public void onSelected(int pos) {
                                    final int fPos = pos;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                // pos == 0 -> original
                                                if (0 != fPos) {
                                                    FileInputStream imageStream = new FileInputStream(
                                                            new File(filename));

                                                    ImageSize imageSize = sizesList.get(fPos);
                                                    InputStream resizeBitmapStream = null;

                                                    try {
                                                        resizeBitmapStream = ImageUtils.resizeImage(imageStream,
                                                                -1,
                                                                (fullImageSize.mWidth + imageSize.mWidth - 1)
                                                                        / imageSize.mWidth,
                                                                75);
                                                    } catch (OutOfMemoryError ex) {
                                                        Log.e(LOG_TAG,
                                                                "Onclick BitmapFactory.createScaledBitmap : "
                                                                        + ex.getMessage());
                                                    } catch (Exception e) {
                                                        Log.e(LOG_TAG,
                                                                "Onclick BitmapFactory.createScaledBitmap failed : "
                                                                        + e.getMessage());
                                                    }

                                                    if (null != resizeBitmapStream) {
                                                        String bitmapURL = mMediasCache.saveMedia(
                                                                resizeBitmapStream, null, "image/jpeg");

                                                        if (null != bitmapURL) {
                                                            mPendingMediaUrl = bitmapURL;
                                                        }

                                                        resizeBitmapStream.close();

                                                        // try to apply exif rotation
                                                        if (0 != rotationAngle) {
                                                            // rotate the image content
                                                            ImageUtils.rotateImage(RoomActivity.this,
                                                                    mPendingMediaUrl, rotationAngle,
                                                                    mMediasCache);
                                                        }
                                                    }
                                                }
                                            } catch (Exception e) {
                                                Log.e(LOG_TAG, "Onclick " + e.getMessage());
                                            }

                                            //
                                            mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl,
                                                    mPendingMediaUrl, mPendingFilename, mPendingMimeType);
                                            mPendingThumbnailUrl = null;
                                            mPendingMediaUrl = null;
                                            mPendingMimeType = null;
                                            mPendingFilename = null;
                                            manageSendMoreButtons();
                                        }
                                    });
                                }
                            });

                            fragment.show(fm, TAG_FRAGMENT_IMAGE_SIZE_DIALOG);
                            sendMedia = false;
                        }

                    } catch (Exception e) {
                        Log.e(LOG_TAG, "Onclick " + e.getMessage());
                    }
                }

                if (sendMedia) {
                    mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl, mPendingMediaUrl,
                            mPendingFilename, mPendingMimeType);
                    mPendingThumbnailUrl = null;
                    mPendingMediaUrl = null;
                    mPendingMimeType = null;
                    mPendingFilename = null;
                    manageSendMoreButtons();
                }
            } else {
                String body = mEditText.getText().toString();
                sendMessage(body);
                mEditText.setText("");
            }
        }
    });

    mAttachmentButton = (ImageButton) findViewById(R.id.button_more);
    mAttachmentButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            FragmentManager fm = getSupportFragmentManager();
            IconAndTextDialogFragment fragment = (IconAndTextDialogFragment) fm
                    .findFragmentByTag(TAG_FRAGMENT_ATTACHMENTS_DIALOG);

            if (fragment != null) {
                fragment.dismissAllowingStateLoss();
            }

            final Integer[] messages = new Integer[] { R.string.option_send_files, R.string.option_take_photo,
                    R.string.option_take_video };

            final Integer[] icons = new Integer[] { R.drawable.ic_material_file, // R.string.option_send_files
                    R.drawable.ic_material_camera, // R.string.action_members
                    R.drawable.ic_material_videocam, // R.string.action_members
            };

            fragment = IconAndTextDialogFragment.newInstance(icons, messages);
            fragment.setOnClickListener(new IconAndTextDialogFragment.OnItemClickListener() {
                @Override
                public void onItemClick(IconAndTextDialogFragment dialogFragment, int position) {
                    Integer selectedVal = messages[position];

                    if (selectedVal == R.string.option_send_files) {
                        RoomActivity.this.launchFileSelectionIntent();
                    } else if (selectedVal == R.string.option_take_photo) {
                        RoomActivity.this.launchCamera();
                    } else if (selectedVal == R.string.option_take_video) {
                        RoomActivity.this.launchVideo();
                    }
                }
            });

            fragment.show(fm, TAG_FRAGMENT_INVITATION_MEMBERS_DIALOG);
        }
    });

    mEditText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(android.text.Editable s) {
            MXLatestChatMessageCache latestChatMessageCache = RoomActivity.this.mLatestChatMessageCache;

            String textInPlace = latestChatMessageCache.getLatestText(RoomActivity.this, mRoom.getRoomId());

            // check if there is really an update
            // avoid useless updates (initializations..)
            if (!mIgnoreTextUpdate && !textInPlace.equals(mEditText.getText().toString())) {
                latestChatMessageCache.updateLatestMessage(RoomActivity.this, mRoom.getRoomId(),
                        mEditText.getText().toString());
                handleTypingNotification(mEditText.getText().length() != 0);
            }

            manageSendMoreButtons();
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    mSession = getSession(intent);

    if (mSession == null) {
        Log.e(LOG_TAG, "No MXSession.");
        finish();
        return;
    }

    mMyUserId = mSession.getCredentials().userId;

    CommonActivityUtils.resumeEventStream(this);

    mRoom = mSession.getDataHandler().getRoom(roomId);

    FragmentManager fm = getSupportFragmentManager();
    mConsoleMessageListFragment = (ConsoleMessageListFragment) fm
            .findFragmentByTag(TAG_FRAGMENT_MATRIX_MESSAGE_LIST);

    if (mConsoleMessageListFragment == null) {
        // this fragment displays messages and handles all message logic
        mConsoleMessageListFragment = ConsoleMessageListFragment.newInstance(mMyUserId, mRoom.getRoomId(),
                org.matrix.androidsdk.R.layout.fragment_matrix_message_list_fragment);
        fm.beginTransaction().add(R.id.anchor_fragment_messages, mConsoleMessageListFragment,
                TAG_FRAGMENT_MATRIX_MESSAGE_LIST).commit();
    }

    // set general room information
    setTitle(mRoom.getName(mMyUserId));
    setTopic(mRoom.getTopic());

    mImagePreviewLayout = findViewById(R.id.room_image_preview_layout);
    mImagePreviewView = (ImageView) findViewById(R.id.room_image_preview);
    mImagePreviewButton = (ImageButton) findViewById(R.id.room_image_preview_cancel_button);

    // the user cancels the image selection
    mImagePreviewButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mPendingThumbnailUrl = null;
            mPendingMediaUrl = null;
            mPendingMimeType = null;
            mPendingFilename = null;
            manageSendMoreButtons();
        }
    });

    mLatestChatMessageCache = Matrix.getInstance(this).getDefaultLatestChatMessageCache();
    mMediasCache = Matrix.getInstance(this).getMediasCache();

    // some medias must be sent while opening the chat
    if (intent.hasExtra(HomeActivity.EXTRA_ROOM_INTENT)) {
        final Intent mediaIntent = intent.getParcelableExtra(HomeActivity.EXTRA_ROOM_INTENT);

        // sanity check
        if (null != mediaIntent) {
            mEditText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendMediasIntent(mediaIntent);
                }
            }, 1000);
        }
    }
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToFacebook(final Activity activity, final Handler handler, final Facebook mFacebook,
        final String path, final String title, final String description, final String emailAddress,
        final long sdrecord_id) {

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // Track errors
            boolean failed = false;

            Log.i(TAG, "Upload starting");
            // Initialising REST API video.upload parameters
            Bundle params = new Bundle();

            params.putString("method", "facebook.video.upload");
            params.putString("format", "json");
            params.putString("title", title);
            params.putString("description", description);
            params.putString("call_id", String.valueOf(System.currentTimeMillis()));
            params.putString("v", "1.0");
            params.putString("oauth_token", mFacebook.getAccessToken());

            // Reading input file
            try {
                File videoFile = new File(path);
                byte[] data = null;
                try {

                    // XXX
                    // SPLIT THIS INTO 5K chunks!!
                    // XXX

                    data = new byte[(int) videoFile.length()];
                } catch (OutOfMemoryError e) {
                    failed = true;/* w  w  w  .  j a va  2 s . co m*/
                }
                if (data != null) {
                    InputStream is = new FileInputStream(videoFile);
                    is.read(data);
                    params.putByteArray(videoFile.getName(), data);
                }
            } catch (Exception ex) {
                Log.e(TAG, "Cannot read video file :", ex);
            }

            // Sending POST request to Facebook
            String response = null;
            String url = "https://api-video.facebook.com/restserver.php";

            try {
                if (!failed) {
                    response = Util.openUrl(url, "POST", params);
                }
                // SessionEvents.onUploadComplete(response);
            } catch (FileNotFoundException e) {
                // SessionEvents.onFileNotFoundException(e);
                failed = true;
                e.printStackTrace();
            } catch (MalformedURLException e) {
                // SessionEvents.onMalformedURLException(e);
                failed = true;
                e.printStackTrace();
            } catch (IOException e) {
                // SessionEvents.onIOException(e);
                failed = true;
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                failed = true;
                e.printStackTrace();
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.

                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

                return;
            }

            Log.i(TAG, "Uploading to facebook complete. Response is " + response);

            // response is JSON
            JSONObject fb_response = null;
            // decode, and grab URL
            try {
                fb_response = (JSONObject) new JSONTokener(response).nextValue();
            } catch (JSONException e) {
                //
                e.printStackTrace();
                fb_response = null;
            }
            String hosted_url = "facebook.com";

            if (fb_response != null) {

                try {
                    hosted_url = fb_response.getString("link");
                    Log.i(TAG, "Facebook hosted url is : " + hosted_url);
                } catch (JSONException e) {
                    //
                    e.printStackTrace();
                    hosted_url = null;
                }

                if (hosted_url != null) {
                    // Log record of this URL in POSTs table
                    dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, url, hosted_url, "");

                    mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                    // Use the handler to execute a Runnable on the
                    // main thread in order to have access to the
                    // UI elements.
                    handler.postDelayed(new Runnable() {

                        public void run() {
                            // Update UI

                            // Indicate back to calling activity the result!
                            // update uploadInProgress state also.

                            ((VidiomActivity) activity).finishedUploading(true);
                            ((VidiomActivity) activity)
                                    .createNotification(res.getString(R.string.upload_to_facebook_succeeded_));

                        }
                    }, 0);
                }

            } else {

                // an error -- fb_response is NULL.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

            }

            if (emailAddress != null && fb_response != null && hosted_url != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + hosted_url, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

        }
    });

    t.start();

    return t;

}