Example usage for android.net Uri getPath

List of usage examples for android.net Uri getPath

Introduction

In this page you can find the example usage for android.net Uri getPath.

Prototype

@Nullable
public abstract String getPath();

Source Link

Document

Gets the decoded path.

Usage

From source file:com.cw.litenote.note_add.Note_addCameraImage.java

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    System.out.println("Note_addCameraImage / onActivityResult");
    if (requestCode == TAKE_IMAGE_ACT) {
        if (resultCode == Activity.RESULT_OK) {
            // disable Rotate to avoid leak window
            //            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

            // Note: 
            // 1 .for Google Camera App, imageReturnedIntent is null
            //    its default path is 
            //    a. open App by cell phone menu: /sdcard/DCIM/Camera
            //    b. open App by intent: intent appoints
            // 2. for Camera360 App, get data from imageReturnedIntent is null
            //    and its default path is /sdcard/DCIM/Camera (??? has duplication, how to solve?)

            // check returned intent
            if (imageReturnedIntent == null) {
                System.out.println("returned intent is null"); // Google Camera case
            } else {
                Uri imageUri = imageReturnedIntent.getData();

                if (imageUri == null)
                    System.out.println("-- imageUri = " + null); // Camera360 case
                else
                    System.out.println("-- imageUri = " + imageUri.toString());
            }/*from ww w.j a  va 2  s .c o  m*/

            // The following source code can be used 
            // if we know the file name is got from returned intent
            // note: unfortunately, this is not working for Google Camera,
            //       so using this way will get null after taking image
            /*            
                        // get Uri from returned intent, scheme is content
                        // example: content://media/external/images/media/43983
                        Uri picUri = imageReturnedIntent.getData();
                                
                        if(picUri == null)
                           System.out.println("-- picUri = " + null);
                        else
                           System.out.println("-- picUri = " + picUri.toString());
                                   
                        // get file path and add prefix (file://)
                        String realPath = Util.getRealPathByUri(this, picUri);
                        System.out.println("--- realPath = " + realPath);
                        if("content".equalsIgnoreCase(picUri.getScheme()))
                        {
                           // example: file:///storage/ext_sd/DCIM/100MEDIA/IMAG0146.jpg
                           // path of default camera App: 100MEDIA for hTC , 100ANDRO for Sony
                           pictureUriInDB = "file://".concat(realPath);
                           System.out.println("---- pictureUriInDB = " + pictureUriInDB);
                        }
                                
                                
                        // get picture name
                        File pic = new File(pictureUriInDB);
                        String picName = pic.getName();
            //            System.out.println("picName = " + picName);
                                
                        // get directory by removing picture name
                        String picDir = realPath.replace(picName, "");
            //            System.out.println("picDir = " + picDir);
                                
            //            // get current picture directory
            //            SharedPreferences pref_takePicture;
            //              pref_takePicture = getSharedPreferences("takePicutre", 0);   
            //              String currentPictureDir = pref_takePicture.getString("KEY_SET_PICTURE_DIR","unknown");
            //              
            //              // update picture directory if needed
            //              if(   !picDir.equalsIgnoreCase(currentPictureDir))         
            //                    pref_takePicture.edit().putString("KEY_SET_PICTURE_DIR",picDir).apply();
            */

            SharedPreferences pref_takeImage;
            pref_takeImage = getSharedPreferences("takeImage", 0);

            if (!UtilImage.bShowExpandedImage)
                noteId = savePictureStateInDB(noteId, imageUriInDB);

            // set for Rotate any times
            if (noteId != null) {
                cameraImageUri = dB_page.getNotePictureUri_byId(noteId);
            }

            if (getIntent().getExtras().getString("extra_ADD_NEW_TO_TOP", "false").equalsIgnoreCase("true")
                    && (dB_page.getNotesCount(true) > 0))
                Page_recycler.swap(Page_recycler.mDb_page);

            Toast.makeText(this, R.string.toast_saved, Toast.LENGTH_SHORT).show();

            // check and delete duplicated image file in 100ANDRO (Sony) / 100MEDIA (hTC)
            //            int lastContentId = getLastCapturedImageId(this);
            handleDuplicatedImage(this);

            // show confirm Continue dialog
            if (pref_takeImage.getString("KEY_SHOW_CONFIRMATION_DIALOG", "no").equalsIgnoreCase("yes")) {
                bUseCameraImage = true;
                // set Continue Taking Picture dialog
                showContinueConfirmationDialog();
            } else
            // not show confirm Continue dialog
            {
                bUseCameraImage = false;

                // take image without confirmation dialog 
                noteId = null; // set null for Insert
                takeImageWithName();
            }

            // enable Rotate 
            //               setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        } else if (resultCode == RESULT_CANCELED) {
            // hide action bar
            if (getActionBar() != null)
                getActionBar().hide();

            // set action bar to transparent
            //            getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
            //            getActionBar().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            //            setTitle("");

            // disable content view
            //            findViewById(android.R.id.content).setVisibility(View.INVISIBLE);

            // set background to transparent
            getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

            Toast.makeText(this, R.string.note_cancel_add_new, Toast.LENGTH_LONG).show();

            // delete the temporary note in DB
            if (noteId != null)
                dB_page.deleteNote(noteId, true);

            // When auto time out of taking picture App happens, 
            // Note_addCameraImage activity will start from onCreate,
            // at this case, imageUri is null
            if (imageUri != null) {
                File tempFile = new File(imageUri.getPath());
                if (tempFile.isFile()) {
                    // delete 0 bit temporary file
                    tempFile.delete();
                    System.out.println("temp 0 bit file is deleted");
                }
            }
            finish();
            return; // must add this
        }

    }
}

From source file:com.irccloud.android.activity.MainActivity.java

private Uri resize(Uri in) {
    Uri out = null;
    try {//from  w w w .  j  a  va2  s  . c om
        int MAX_IMAGE_SIZE = Integer
                .parseInt(PreferenceManager.getDefaultSharedPreferences(this).getString("photo_size", "1024"));
        File imageDir = new File(Environment.getExternalStorageDirectory(), "IRCCloud");
        imageDir.mkdirs();
        new File(imageDir, ".nomedia").createNewFile();

        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(IRCCloudApplication.getInstance().getApplicationContext()
                .getContentResolver().openInputStream(in), null, o);
        int scale = 1;

        if (o.outWidth < MAX_IMAGE_SIZE && o.outHeight < MAX_IMAGE_SIZE)
            return in;

        if (o.outWidth > o.outHeight) {
            if (o.outWidth > MAX_IMAGE_SIZE)
                scale = o.outWidth / MAX_IMAGE_SIZE;
        } else {
            if (o.outHeight > MAX_IMAGE_SIZE)
                scale = o.outHeight / MAX_IMAGE_SIZE;
        }

        o = new BitmapFactory.Options();
        o.inSampleSize = scale;
        Bitmap bmp = BitmapFactory.decodeStream(IRCCloudApplication.getInstance().getApplicationContext()
                .getContentResolver().openInputStream(in), null, o);

        //ExifInterface can only work on local files, so make a temporary copy on the SD card
        out = Uri.fromFile(File.createTempFile("irccloudcapture-original", ".jpg", imageDir));
        InputStream is = IRCCloudApplication.getInstance().getApplicationContext().getContentResolver()
                .openInputStream(in);
        OutputStream os = IRCCloudApplication.getInstance().getApplicationContext().getContentResolver()
                .openOutputStream(out);
        byte[] buffer = new byte[8192];
        int len;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        is.close();
        os.close();

        ExifInterface exif = new ExifInterface(out.getPath());
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
        new File(new URI(out.toString())).delete();

        out = Uri.fromFile(File.createTempFile("irccloudcapture-resized", ".jpg", imageDir));
        if (orientation > 1) {
            Matrix matrix = new Matrix();
            switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.postRotate(90);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.postRotate(180);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.postRotate(270);
                break;
            }
            try {
                Bitmap oldbmp = bmp;
                bmp = Bitmap.createBitmap(oldbmp, 0, 0, oldbmp.getWidth(), oldbmp.getHeight(), matrix, true);
                oldbmp.recycle();
            } catch (OutOfMemoryError e) {
                Log.e("IRCCloud", "Out of memory rotating the photo, it may look wrong on imgur");
            }
        }

        if (bmp == null || !bmp.compress(android.graphics.Bitmap.CompressFormat.JPEG, 90, IRCCloudApplication
                .getInstance().getApplicationContext().getContentResolver().openOutputStream(out))) {
            out = null;
        }
        if (bmp != null)
            bmp.recycle();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        Crashlytics.logException(e);
    } catch (OutOfMemoryError e) {
        Log.e("IRCCloud", "Out of memory rotating the photo, it may look wrong on imgur");
    }
    if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean("keep_photos", false)
            && in.toString().contains("irccloudcapture")) {
        try {
            new File(new URI(in.toString())).delete();
        } catch (Exception e) {
        }
    }
    if (out != null)
        return out;
    else
        return in;
}

From source file:com.remobile.filetransfer.FileTransfer.java

/**
 * Downloads a file form a given URL and saves it to the specified directory.
 *
 * @param source URL of the server to receive the file
 * @param target Full path of the file on the file system
 *//*  w w w  .  j  a va  2 s .  c o  m*/
private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "download " + source + " to " + target);
    final CordovaResourceApi resourceApi = new CordovaResourceApi(getReactApplicationContext());

    final boolean trustEveryone = args.optBoolean(2);
    final String objectId = args.getString(3);
    final JSONObject headers = args.optJSONObject(4);

    final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));

    // Accept a path or a URI for the source.
    Uri tmpTarget = Uri.parse(target);
    final Uri targetUri = resourceApi
            .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));

    int uriType = CordovaResourceApi.getUriType(sourceUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;
    if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
        Log.e(LOG_TAG, "Unsupported URI: " + sourceUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection connection = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            File file = null;
            PluginResult result = null;
            TrackingInputStream inputStream = null;
            boolean cached = false;

            OutputStream outputStream = null;
            try {
                CordovaResourceApi.OpenForReadResult readResult = null;

                file = resourceApi.mapUriToFile(targetUri);
                context.targetFile = file;

                Log.d(LOG_TAG, "Download file:" + sourceUri);

                FileProgressResult progress = new FileProgressResult();

                if (isLocalTransfer) {
                    readResult = resourceApi.openForRead(sourceUri);
                    if (readResult.length != -1) {
                        progress.setLengthComputable(true);
                        progress.setTotal(readResult.length);
                    }
                    inputStream = new SimpleTrackingInputStream(readResult.inputStream);
                } else {
                    // connect to server
                    // Open a HTTP connection to the URL based on protocol
                    connection = resourceApi.createHttpConnection(sourceUri);
                    if (useHttps && trustEveryone) {
                        // Setup the HTTPS connection class to trust everyone
                        HttpsURLConnection https = (HttpsURLConnection) connection;
                        oldSocketFactory = trustAllHosts(https);
                        // Save the current hostnameVerifier
                        oldHostnameVerifier = https.getHostnameVerifier();
                        // Setup the connection not to verify hostnames
                        https.setHostnameVerifier(DO_NOT_VERIFY);
                    }

                    connection.setRequestMethod("GET");

                    // This must be explicitly set for gzip progress tracking to work.
                    connection.setRequestProperty("Accept-Encoding", "gzip");

                    // Handle the other headers
                    if (headers != null) {
                        addHeadersToRequest(connection, headers);
                    }

                    connection.connect();
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        cached = true;
                        connection.disconnect();
                        Log.d(LOG_TAG, "Resource not modified: " + source);
                        JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection,
                                null);
                        result = new PluginResult(PluginResult.Status.ERROR, error);
                    } else {
                        if (connection.getContentEncoding() == null
                                || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
                            // Only trust content-length header if we understand
                            // the encoding -- identity or gzip
                            if (connection.getContentLength() != -1) {
                                progress.setLengthComputable(true);
                                progress.setTotal(connection.getContentLength());
                            }
                        }
                        inputStream = getInputStream(connection);
                    }
                }

                if (!cached) {
                    try {
                        synchronized (context) {
                            if (context.aborted) {
                                return;
                            }
                            context.connection = connection;
                        }

                        // write bytes to file
                        byte[] buffer = new byte[MAX_BUFFER_SIZE];
                        int bytesRead = 0;
                        outputStream = resourceApi.openOutputStream(targetUri);
                        while ((bytesRead = inputStream.read(buffer)) > 0) {
                            outputStream.write(buffer, 0, bytesRead);
                            // Send a progress event.
                            progress.setLoaded(inputStream.getTotalRawBytesRead());
                            FileTransfer.this.sendJSEvent("DownloadProgress-" + objectId,
                                    JsonConvert.jsonToReact(progress.toJSONObject()));
                        }
                    } finally {
                        synchronized (context) {
                            context.connection = null;
                        }
                        safeClose(inputStream);
                        safeClose(outputStream);
                    }

                    Log.d(LOG_TAG, "Saved file: " + target);

                    file = resourceApi.mapUriToFile(targetUri);
                    context.targetFile = file;
                    result = new PluginResult(PluginResult.Status.OK, targetUri.getPath());
                }

            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
            } catch (Throwable e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (connection != null) {
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) connection;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }

                if (result == null) {
                    result = new PluginResult(PluginResult.Status.ERROR,
                            createFileTransferError(CONNECTION_ERR, source, target, connection, null));
                }
                // Remove incomplete download.
                if (!cached && result.status.ordinal() != PluginResult.Status.OK.ordinal() && file != null) {
                    file.delete();
                }
                context.sendPluginResult(result);
            }
        }
    });
}

From source file:it.feio.android.omninotes.async.DataBackupIntentService.java

/**
  * Imports notes and notebooks from Springpad exported archive
  *//  w ww. j  a v  a 2  s  . c  o  m
  * @param intent
  */
synchronized private void importDataFromSpringpad(Intent intent) {
    String backupPath = intent.getStringExtra(EXTRA_SPRINGPAD_BACKUP);
    Importer importer = new Importer();
    try {
        importer.setZipProgressesListener(percentage -> mNotificationsHelper
                .setMessage(getString(R.string.extracted) + " " + percentage + "%").show());
        importer.doImport(backupPath);
        // Updating notification
        updateImportNotification(importer);
    } catch (ImportException e) {
        new NotificationsHelper(this).createNotification(R.drawable.ic_emoticon_sad_white_24dp,
                getString(R.string.import_fail) + ": " + e.getMessage(), null).setLedActive().show();
        return;
    }
    List<SpringpadElement> elements = importer.getSpringpadNotes();

    // If nothing is retrieved it will exit
    if (elements == null || elements.size() == 0) {
        return;
    }

    // These maps are used to associate with post processing notes to categories (notebooks)
    HashMap<String, Category> categoriesWithUuid = new HashMap<>();

    // Adds all the notebooks (categories)
    for (SpringpadElement springpadElement : importer.getNotebooks()) {
        Category cat = new Category();
        cat.setName(springpadElement.getName());
        cat.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
        DbHelper.getInstance().updateCategory(cat);
        categoriesWithUuid.put(springpadElement.getUuid(), cat);

        // Updating notification
        importedSpringpadNotebooks++;
        updateImportNotification(importer);
    }
    // And creates a default one for notes without notebook 
    Category defaulCategory = new Category();
    defaulCategory.setName("Springpad");
    defaulCategory.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
    DbHelper.getInstance().updateCategory(defaulCategory);

    // And then notes are created
    Note note;
    Attachment mAttachment = null;
    Uri uri;
    for (SpringpadElement springpadElement : importer.getNotes()) {
        note = new Note();

        // Title
        note.setTitle(springpadElement.getName());

        // Content dependent from type of Springpad note
        StringBuilder content = new StringBuilder();
        content.append(
                TextUtils.isEmpty(springpadElement.getText()) ? "" : Html.fromHtml(springpadElement.getText()));
        content.append(
                TextUtils.isEmpty(springpadElement.getDescription()) ? "" : springpadElement.getDescription());

        // Some notes could have been exported wrongly
        if (springpadElement.getType() == null) {
            Toast.makeText(this, getString(R.string.error), Toast.LENGTH_SHORT).show();
            continue;
        }

        if (springpadElement.getType().equals(SpringpadElement.TYPE_VIDEO)) {
            try {
                content.append(System.getProperty("line.separator"))
                        .append(springpadElement.getVideos().get(0));
            } catch (IndexOutOfBoundsException e) {
                content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
            }
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_TVSHOW)) {
            content.append(System.getProperty("line.separator"))
                    .append(TextUtils.join(", ", springpadElement.getCast()));
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOK)) {
            content.append(System.getProperty("line.separator")).append("Author: ")
                    .append(springpadElement.getAuthor()).append(System.getProperty("line.separator"))
                    .append("Publication date: ").append(springpadElement.getPublicationDate());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_RECIPE)) {
            content.append(System.getProperty("line.separator")).append("Ingredients: ")
                    .append(springpadElement.getIngredients()).append(System.getProperty("line.separator"))
                    .append("Directions: ").append(springpadElement.getDirections());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOKMARK)) {
            content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BUSINESS)
                && springpadElement.getPhoneNumbers() != null) {
            content.append(System.getProperty("line.separator")).append("Phone number: ")
                    .append(springpadElement.getPhoneNumbers().getPhone());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_PRODUCT)) {
            content.append(System.getProperty("line.separator")).append("Category: ")
                    .append(springpadElement.getCategory()).append(System.getProperty("line.separator"))
                    .append("Manufacturer: ").append(springpadElement.getManufacturer())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_WINE)) {
            content.append(System.getProperty("line.separator")).append("Wine type: ")
                    .append(springpadElement.getWine_type()).append(System.getProperty("line.separator"))
                    .append("Varietal: ").append(springpadElement.getVarietal())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_ALBUM)) {
            content.append(System.getProperty("line.separator")).append("Artist: ")
                    .append(springpadElement.getArtist());
        }
        for (SpringpadComment springpadComment : springpadElement.getComments()) {
            content.append(System.getProperty("line.separator")).append(springpadComment.getCommenter())
                    .append(" commented at 0").append(springpadComment.getDate()).append(": ")
                    .append(springpadElement.getArtist());
        }

        note.setContent(content.toString());

        // Checklists
        if (springpadElement.getType().equals(SpringpadElement.TYPE_CHECKLIST)) {
            StringBuilder sb = new StringBuilder();
            String checkmark;
            for (SpringpadItem mSpringpadItem : springpadElement.getItems()) {
                checkmark = mSpringpadItem.getComplete()
                        ? it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM
                        : it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM;
                sb.append(checkmark).append(mSpringpadItem.getName())
                        .append(System.getProperty("line.separator"));
            }
            note.setContent(sb.toString());
            note.setChecklist(true);
        }

        // Tags
        String tags = springpadElement.getTags().size() > 0
                ? "#" + TextUtils.join(" #", springpadElement.getTags())
                : "";
        if (note.isChecklist()) {
            note.setTitle(note.getTitle() + tags);
        } else {
            note.setContent(note.getContent() + System.getProperty("line.separator") + tags);
        }

        // Address
        String address = springpadElement.getAddresses() != null ? springpadElement.getAddresses().getAddress()
                : "";
        if (!TextUtils.isEmpty(address)) {
            try {
                double[] coords = GeocodeHelper.getCoordinatesFromAddress(this, address);
                note.setLatitude(coords[0]);
                note.setLongitude(coords[1]);
            } catch (IOException e) {
                Log.e(Constants.TAG,
                        "An error occurred trying to resolve address to coords during Springpad import");
            }
            note.setAddress(address);
        }

        // Reminder
        if (springpadElement.getDate() != null) {
            note.setAlarm(springpadElement.getDate().getTime());
        }

        // Creation, modification, category
        note.setCreation(springpadElement.getCreated().getTime());
        note.setLastModification(springpadElement.getModified().getTime());

        // Image
        String image = springpadElement.getImage();
        if (!TextUtils.isEmpty(image)) {
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, image);
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + image);
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // Other attachments
        for (SpringpadAttachment springpadAttachment : springpadElement.getAttachments()) {
            // The attachment could be the image itself so it's jumped
            if (image != null && image.equals(springpadAttachment.getUrl()))
                continue;

            if (TextUtils.isEmpty(springpadAttachment.getUrl())) {
                continue;
            }

            // Tries first with online images
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, springpadAttachment.getUrl());
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + springpadAttachment.getUrl());
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // If the note has a category is added to the map to be post-processed
        if (springpadElement.getNotebooks().size() > 0) {
            note.setCategory(categoriesWithUuid.get(springpadElement.getNotebooks().get(0)));
        } else {
            note.setCategory(defaulCategory);
        }

        // The note is saved
        DbHelper.getInstance().updateNote(note, false);
        ReminderHelper.addReminder(OmniNotes.getAppContext(), note);

        // Updating notification
        importedSpringpadNotes++;
        updateImportNotification(importer);
    }

    // Delete temp data
    try {
        importer.clean();
    } catch (IOException e) {
        Log.w(Constants.TAG, "Springpad import temp files not deleted");
    }

    String title = getString(R.string.data_import_completed);
    String text = getString(R.string.click_to_refresh_application);
    createNotification(intent, this, title, text, null);
}

From source file:com.dycody.android.idealnote.async.DataBackupIntentService.java

/**
  * Imports notes and notebooks from Springpad exported archive
  *//from   w w w  .  j a  va2  s  . co  m
  * @param intent
  */
synchronized private void importDataFromSpringpad(Intent intent) {
    String backupPath = intent.getStringExtra(EXTRA_SPRINGPAD_BACKUP);
    Importer importer = new Importer();
    try {
        importer.setZipProgressesListener(percentage -> mNotificationsHelper
                .setMessage(getString(com.dycody.android.idealnote.R.string.extracted) + " " + percentage + "%")
                .show());
        importer.doImport(backupPath);
        // Updating notification
        updateImportNotification(importer);
    } catch (ImportException e) {
        new NotificationsHelper(this)
                .createNotification(com.dycody.android.idealnote.R.drawable.ic_emoticon_sad_white_24dp,
                        getString(com.dycody.android.idealnote.R.string.import_fail) + ": " + e.getMessage(),
                        null)
                .setLedActive().show();
        return;
    }
    List<SpringpadElement> elements = importer.getSpringpadNotes();

    // If nothing is retrieved it will exit
    if (elements == null || elements.size() == 0) {
        return;
    }

    // These maps are used to associate with post processing notes to categories (notebooks)
    HashMap<String, Category> categoriesWithUuid = new HashMap<>();

    // Adds all the notebooks (categories)
    for (SpringpadElement springpadElement : importer.getNotebooks()) {
        Category cat = new Category();
        cat.setName(springpadElement.getName());
        cat.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
        DbHelper.getInstance().updateCategory(cat);
        categoriesWithUuid.put(springpadElement.getUuid(), cat);

        // Updating notification
        importedSpringpadNotebooks++;
        updateImportNotification(importer);
    }
    // And creates a default one for notes without notebook 
    Category defaulCategory = new Category();
    defaulCategory.setName("Springpad");
    defaulCategory.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
    DbHelper.getInstance().updateCategory(defaulCategory);

    // And then notes are created
    Note note;
    Attachment mAttachment = null;
    Uri uri;
    for (SpringpadElement springpadElement : importer.getNotes()) {
        note = new Note();

        // Title
        note.setTitle(springpadElement.getName());

        // Content dependent from type of Springpad note
        StringBuilder content = new StringBuilder();
        content.append(
                TextUtils.isEmpty(springpadElement.getText()) ? "" : Html.fromHtml(springpadElement.getText()));
        content.append(
                TextUtils.isEmpty(springpadElement.getDescription()) ? "" : springpadElement.getDescription());

        // Some notes could have been exported wrongly
        if (springpadElement.getType() == null) {
            Toast.makeText(this, getString(com.dycody.android.idealnote.R.string.error), Toast.LENGTH_SHORT)
                    .show();
            continue;
        }

        if (springpadElement.getType().equals(SpringpadElement.TYPE_VIDEO)) {
            try {
                content.append(System.getProperty("line.separator"))
                        .append(springpadElement.getVideos().get(0));
            } catch (IndexOutOfBoundsException e) {
                content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
            }
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_TVSHOW)) {
            content.append(System.getProperty("line.separator"))
                    .append(TextUtils.join(", ", springpadElement.getCast()));
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOK)) {
            content.append(System.getProperty("line.separator")).append("Author: ")
                    .append(springpadElement.getAuthor()).append(System.getProperty("line.separator"))
                    .append("Publication date: ").append(springpadElement.getPublicationDate());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_RECIPE)) {
            content.append(System.getProperty("line.separator")).append("Ingredients: ")
                    .append(springpadElement.getIngredients()).append(System.getProperty("line.separator"))
                    .append("Directions: ").append(springpadElement.getDirections());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOKMARK)) {
            content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BUSINESS)
                && springpadElement.getPhoneNumbers() != null) {
            content.append(System.getProperty("line.separator")).append("Phone number: ")
                    .append(springpadElement.getPhoneNumbers().getPhone());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_PRODUCT)) {
            content.append(System.getProperty("line.separator")).append("Category: ")
                    .append(springpadElement.getCategory()).append(System.getProperty("line.separator"))
                    .append("Manufacturer: ").append(springpadElement.getManufacturer())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_WINE)) {
            content.append(System.getProperty("line.separator")).append("Wine type: ")
                    .append(springpadElement.getWine_type()).append(System.getProperty("line.separator"))
                    .append("Varietal: ").append(springpadElement.getVarietal())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_ALBUM)) {
            content.append(System.getProperty("line.separator")).append("Artist: ")
                    .append(springpadElement.getArtist());
        }
        for (SpringpadComment springpadComment : springpadElement.getComments()) {
            content.append(System.getProperty("line.separator")).append(springpadComment.getCommenter())
                    .append(" commented at 0").append(springpadComment.getDate()).append(": ")
                    .append(springpadElement.getArtist());
        }

        note.setContent(content.toString());

        // Checklists
        if (springpadElement.getType().equals(SpringpadElement.TYPE_CHECKLIST)) {
            StringBuilder sb = new StringBuilder();
            String checkmark;
            for (SpringpadItem mSpringpadItem : springpadElement.getItems()) {
                checkmark = mSpringpadItem.getComplete()
                        ? it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM
                        : it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM;
                sb.append(checkmark).append(mSpringpadItem.getName())
                        .append(System.getProperty("line.separator"));
            }
            note.setContent(sb.toString());
            note.setChecklist(true);
        }

        // Tags
        String tags = springpadElement.getTags().size() > 0
                ? "#" + TextUtils.join(" #", springpadElement.getTags())
                : "";
        if (note.isChecklist()) {
            note.setTitle(note.getTitle() + tags);
        } else {
            note.setContent(note.getContent() + System.getProperty("line.separator") + tags);
        }

        // Address
        String address = springpadElement.getAddresses() != null ? springpadElement.getAddresses().getAddress()
                : "";
        if (!TextUtils.isEmpty(address)) {
            try {
                double[] coords = GeocodeHelper.getCoordinatesFromAddress(this, address);
                note.setLatitude(coords[0]);
                note.setLongitude(coords[1]);
            } catch (IOException e) {
                Log.e(Constants.TAG,
                        "An error occurred trying to resolve address to coords during Springpad import");
            }
            note.setAddress(address);
        }

        // Reminder
        if (springpadElement.getDate() != null) {
            note.setAlarm(springpadElement.getDate().getTime());
        }

        // Creation, modification, category
        note.setCreation(springpadElement.getCreated().getTime());
        note.setLastModification(springpadElement.getModified().getTime());

        // Image
        String image = springpadElement.getImage();
        if (!TextUtils.isEmpty(image)) {
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, image);
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + image);
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // Other attachments
        for (SpringpadAttachment springpadAttachment : springpadElement.getAttachments()) {
            // The attachment could be the image itself so it's jumped
            if (image != null && image.equals(springpadAttachment.getUrl()))
                continue;

            if (TextUtils.isEmpty(springpadAttachment.getUrl())) {
                continue;
            }

            // Tries first with online images
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, springpadAttachment.getUrl());
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + springpadAttachment.getUrl());
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // If the note has a category is added to the map to be post-processed
        if (springpadElement.getNotebooks().size() > 0) {
            note.setCategory(categoriesWithUuid.get(springpadElement.getNotebooks().get(0)));
        } else {
            note.setCategory(defaulCategory);
        }

        // The note is saved
        DbHelper.getInstance().updateNote(note, false);
        ReminderHelper.addReminder(IdealNote.getAppContext(), note);

        // Updating notification
        importedSpringpadNotes++;
        updateImportNotification(importer);
    }

    // Delete temp data
    try {
        importer.clean();
    } catch (IOException e) {
        Log.w(Constants.TAG, "Springpad import temp files not deleted");
    }

    String title = getString(com.dycody.android.idealnote.R.string.data_import_completed);
    String text = getString(com.dycody.android.idealnote.R.string.click_to_refresh_application);
    createNotification(intent, this, title, text, null);
}

From source file:com.codename1.impl.android.AndroidImplementation.java

private String getImageFilePath(Uri uri) {

    File file = new File(uri.getPath());
    String scheme = uri.getScheme();
    //String[] filePaths = file.getPath().split(":");
    //String image_id = filePath[filePath.length - 1];
    String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContext().getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Images.Media.DATA }, null, null, null);
    cursor.moveToFirst();//w  w  w  . jav a2 s. c om
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();

    if (filePath == null || "content".equals(scheme)) {
        //if the file is not on the filesystem download it and save it
        //locally
        try {
            InputStream inputStream = getContext().getContentResolver().openInputStream(uri);
            if (inputStream != null) {
                String name = new File(uri.toString()).getName();//getContentName(getContext().getContentResolver(), uri);
                if (name != null) {
                    String homePath = getAppHomePath();
                    if (homePath.endsWith("/")) {
                        homePath = homePath.substring(0, homePath.length() - 1);
                    }
                    filePath = homePath + getFileSystemSeparator() + name;
                    File f = new File(removeFilePrefix(filePath));
                    OutputStream tmp = createFileOuputStream(f);
                    byte[] buffer = new byte[1024];
                    int read = -1;
                    while ((read = inputStream.read(buffer)) > -1) {
                        tmp.write(buffer, 0, read);
                    }
                    tmp.close();
                    inputStream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //long len = new com.codename1.io.File(filePath).length();
    return filePath;
}