Example usage for android.provider OpenableColumns DISPLAY_NAME

List of usage examples for android.provider OpenableColumns DISPLAY_NAME

Introduction

In this page you can find the example usage for android.provider OpenableColumns DISPLAY_NAME.

Prototype

String DISPLAY_NAME

To view the source code for android.provider OpenableColumns DISPLAY_NAME.

Click Source Link

Document

The human-friendly name of file.

Usage

From source file:com.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java

public String checkExtension(Uri uri) {

    String extension = "";

    // The query, since it only applies to a single document, will only
    // return//from  ww  w .j  a  v  a 2 s.  co m
    // one row. There's no need to filter, sort, or select fields, since we
    // want
    // all fields for one document.
    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);

    try {
        // moveToFirst() returns false if the cursor has 0 rows. Very handy
        // for
        // "if there's anything to look at, look at it" conditionals.
        if (cursor != null && cursor.moveToFirst()) {

            // Note it's called "Display Name". This is
            // provider-specific, and might not necessarily be the file
            // name.
            String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            int position = displayName.indexOf(".");
            extension = displayName.substring(position + 1);
            Log.i(TAG, "Display Name: " + displayName);

            int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
            // If the size is unknown, the value stored is null. But since
            // an
            // int can't be null in Java, the behavior is
            // implementation-specific,
            // which is just a fancy term for "unpredictable". So as
            // a rule, check if it's null before assigning to an int. This
            // will
            // happen often: The storage API allows for remote files, whose
            // size might not be locally known.
            String size = null;
            if (!cursor.isNull(sizeIndex)) {
                // Technically the column stores an int, but
                // cursor.getString()
                // will do the conversion automatically.
                size = cursor.getString(sizeIndex);
            } else {
                size = "Unknown";
            }
            Log.i(TAG, "Size: " + size);
        }
    } finally {
        cursor.close();
    }
    return extension;
}

From source file:com.jefftharris.passwdsafe.file.PasswdFileUri.java

/** Resolve fields for a generic provider URI */
private void resolveGenericProviderUri(Context context) {
    ContentResolver cr = context.getContentResolver();
    boolean writable = false;
    boolean deletable = false;
    itsTitle = "(unknown)";
    Cursor cursor = cr.query(itsUri, null, null, null, null);
    try {/*w  w  w .  j  a  v  a  2  s  .c  om*/
        if ((cursor != null) && cursor.moveToFirst()) {
            int colidx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            if (colidx != -1) {
                itsTitle = cursor.getString(colidx);
            }

            int flags = 0;
            colidx = cursor.getColumnIndex(DocumentsContractCompat.COLUMN_FLAGS);
            if (colidx != -1) {
                flags = cursor.getInt(colidx);
            }

            PasswdSafeUtil.dbginfo(TAG, "file %s, %x", itsTitle, flags);
            writable = (flags & DocumentsContractCompat.FLAG_SUPPORTS_WRITE) != 0;
            deletable = (flags & DocumentsContractCompat.FLAG_SUPPORTS_DELETE) != 0;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    itsWritableInfo = new Pair<>(writable, null);
    itsIsDeletable = deletable;
}

From source file:com.hp.mss.printsdksample.fragment.TabFragmentPrintLayout.java

private void showFileInfo(Uri uri) {
    Cursor returnCursor = getActivity().getContentResolver().query(uri, null, null, null, null);

    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
    returnCursor.moveToFirst();/*from   w  w  w. j  a v  a2 s .com*/

    Toast.makeText(getActivity(), "File " + returnCursor.getString(nameIndex) + "("
            + Long.toString(returnCursor.getLong(sizeIndex)) + "0", Toast.LENGTH_LONG).show();

}

From source file:com.mattprecious.telescope.FileProvider.java

/**
 * Use a content URI returned by//from w w w . j  av a 2s  .  c  o  m
 * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
 * managed by the FileProvider.
 * FileProvider reports the column names defined in {@link android.provider.OpenableColumns}:
 * <ul>
 * <li>{@link android.provider.OpenableColumns#DISPLAY_NAME}</li>
 * <li>{@link android.provider.OpenableColumns#SIZE}</li>
 * </ul>
 * For more information, see
 * {@link ContentProvider#query(Uri, String[], String, String[], String)
 * ContentProvider.query()}.
 *
 * @param uri A content URI returned by {@link #getUriForFile}.
 * @param projection The list of columns to put into the {@link Cursor}. If null all columns are
 * included.
 * @param selection Selection criteria to apply. If null then all data that matches the content
 * URI is returned.
 * @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
 * the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
 * right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
 * <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
 * values are bound to <i>selection</i> as {@link java.lang.String} values.
 * @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
 * the resulting {@link Cursor}.
 * @return A {@link Cursor} containing the results of the query.
 */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    // ContentProvider has already checked granted permissions
    final File file = mStrategy.getFileForUri(uri);

    if (projection == null) {
        projection = COLUMNS;
    }

    String[] cols = new String[projection.length];
    Object[] values = new Object[projection.length];
    int i = 0;
    for (String col : projection) {
        if (OpenableColumns.DISPLAY_NAME.equals(col)) {
            cols[i] = OpenableColumns.DISPLAY_NAME;
            values[i++] = file.getName();
        } else if (OpenableColumns.SIZE.equals(col)) {
            cols[i] = OpenableColumns.SIZE;
            values[i++] = file.length();
        }
    }

    cols = copyOf(cols, i);
    values = copyOf(values, i);

    final MatrixCursor cursor = new MatrixCursor(cols, 1);
    cursor.addRow(values);
    return cursor;
}

From source file:com.wiret.arbrowser.AbstractArchitectCamActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == KmlFileBrowserActivity.FILE_SELECT_CODE) {
        if (resultCode == RESULT_OK) {
            try {
                String filename = "";
                Uri uri = data.getData();

                if (false) {
                    Toast.makeText(this,
                            "The selected file is too large. Selet a new file with size less than 2mb",
                            Toast.LENGTH_LONG).show();
                } else {
                    String mimeType = getContentResolver().getType(uri);
                    if (mimeType == null) {
                        String path = getPath(this, uri);
                        if (path == null) {
                            filename = FilenameUtils.getName(uri.toString());
                        } else {
                            File file = new File(path);
                            filename = file.getName();
                        }//from  w ww.  j av  a2  s  .  co  m
                    } else {
                        Uri returnUri = data.getData();
                        Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
                        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                        returnCursor.moveToFirst();
                        filename = returnCursor.getString(nameIndex);
                        String size = Long.toString(returnCursor.getLong(sizeIndex));
                    }
                    String sourcePath = getExternalFilesDir(null).toString();
                    try {
                        File outputPath = new File(sourcePath + "/" + filename);
                        copyFileStream(outputPath, uri, this);
                        importData(outputPath.getAbsolutePath());

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.applozic.mobicommons.file.FileUtils.java

/**
 * @param uri/*from   w w  w.  ja va 2s .  co m*/
 * @param context
 * @return
 */
public static String getFileName(Context context, Uri uri) {

    String fileName = null;
    if (uri.getScheme().equals("content")) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();
            }
        }
    }
    if (TextUtils.isEmpty(fileName)) {
        fileName = uri.getPath();
        int cut = fileName.lastIndexOf('/');
        if (cut != -1) {
            fileName = fileName.substring(cut + 1);
        }
    }
    return fileName;
}

From source file:com.synox.android.ui.activity.FileDisplayActivity.java

private void requestSimpleUpload(Intent data, int resultCode) {
    String filePath = null;//from w w w  . j  a  v  a  2s  . com
    String mimeType = null;

    Uri selectedImageUri = data.getData();

    try {
        mimeType = getContentResolver().getType(selectedImageUri);

        String fileManagerString = selectedImageUri.getPath();
        String selectedImagePath = UriUtils.getLocalPath(selectedImageUri, this);

        if (selectedImagePath != null)
            filePath = selectedImagePath;
        else
            filePath = fileManagerString;

    } catch (Exception e) {
        Log_OC.e(TAG, "Unexpected exception when trying to read the result of " + "Intent.ACTION_GET_CONTENT",
                e);

    } finally {
        if (filePath == null) {
            Log_OC.e(TAG, "Couldn't resolve path to file");
            Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content),
                    Toast.LENGTH_LONG);
            t.show();
        }
    }

    Intent i = new Intent(this, FileUploader.class);
    i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
    OCFile currentDir = getCurrentDir();
    String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;

    if (filePath != null && filePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
        Cursor cursor = getContentResolver().query(Uri.parse(filePath), null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                Log_OC.v(TAG, "Display Name: " + displayName);

                displayName.replace(File.separatorChar, '_');
                displayName.replace(File.pathSeparatorChar, '_');
                remotePath += displayName + DisplayUtils.getComposedFileExtension(filePath);

            }
            // and what happens in case of error?; wrong target name for the upload
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

    } else {
        if (filePath != null) {
            remotePath += new File(filePath).getName();
        }
    }

    i.putExtra(FileUploader.KEY_LOCAL_FILE, filePath);
    i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePath);
    i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
    i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
    if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
        i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
    startService(i);
}

From source file:com.cerema.cloud2.ui.activity.FileDisplayActivity.java

private void requestSimpleUpload(Intent data, int resultCode) {
    String filePath = null;//  w w w  .java  2 s  . c  o  m
    String mimeType = null;

    Uri selectedImageUri = data.getData();

    try {
        mimeType = getContentResolver().getType(selectedImageUri);

        String fileManagerString = selectedImageUri.getPath();
        String selectedImagePath = UriUtils.getLocalPath(selectedImageUri, this);

        if (selectedImagePath != null)
            filePath = selectedImagePath;
        else
            filePath = fileManagerString;

    } catch (Exception e) {
        Log_OC.e(TAG, "Unexpected exception when trying to read the result of " + "Intent.ACTION_GET_CONTENT",
                e);

    } finally {
        if (filePath == null) {
            Log_OC.e(TAG, "Couldn't resolve path to file");
            Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content),
                    Toast.LENGTH_LONG);
            t.show();
            return;
        }
    }

    Intent i = new Intent(this, FileUploader.class);
    i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
    OCFile currentDir = getCurrentDir();
    String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;

    if (filePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
        Cursor cursor = getContentResolver().query(Uri.parse(filePath), null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                Log_OC.v(TAG, "Display Name: " + displayName);

                displayName.replace(File.separatorChar, '_');
                displayName.replace(File.pathSeparatorChar, '_');
                remotePath += displayName + DisplayUtils.getComposedFileExtension(filePath);

            }
            // and what happens in case of error?; wrong target name for the upload
        } finally {
            cursor.close();
        }

    } else {
        remotePath += new File(filePath).getName();
    }

    i.putExtra(FileUploader.KEY_LOCAL_FILE, filePath);
    i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePath);
    i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
    i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
    if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
        i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
    startService(i);
}

From source file:com.xperia64.timidityae.TimidityActivity.java

public void handleIntentData(Intent in) {
    if (in.getData() != null) {
        String data;/*from   w  w  w  . ja va 2s.c o m*/
        if ((data = in.getData().getPath()) != null && in.getData().getScheme() != null) {
            if (in.getData().getScheme().equals("file")) {
                if (new File(data).exists()) {
                    File f = new File(data.substring(0, data.lastIndexOf('/') + 1));
                    if (f.exists()) {
                        if (f.isDirectory()) {
                            ArrayList<String> files = new ArrayList<String>();
                            int position = -1;
                            int goodCounter = 0;
                            for (File ff : f.listFiles()) {
                                if (ff != null && ff.isFile()) {
                                    int dotPosition = ff.getName().lastIndexOf('.');
                                    String extension = "";
                                    if (dotPosition != -1) {
                                        extension = (ff.getName().substring(dotPosition))
                                                .toLowerCase(Locale.US);
                                        if (extension != null) {
                                            if ((Globals.showVideos ? Globals.musicVideoFiles
                                                    : Globals.musicFiles).contains("*" + extension + "*")) {

                                                files.add(ff.getPath());
                                                if (ff.getPath().equals(data))
                                                    position = goodCounter;
                                                goodCounter++;
                                            }
                                        }
                                    }
                                }
                            }
                            if (position == -1)
                                Toast.makeText(this, getResources().getString(R.string.intErr1),
                                        Toast.LENGTH_SHORT).show();
                            else {
                                stop();
                                selectedSong(files, position, true, false, false);
                                fileFrag.getDir(data.substring(0, data.lastIndexOf('/') + 1));
                            }
                        }
                    }
                } else {
                    Toast.makeText(this, getResources().getString(R.string.srv_fnf), Toast.LENGTH_SHORT).show();
                }
            } else if (in.getData().getScheme().equals("http") || in.getData().getScheme().equals("https")) {
                if (!data.endsWith("/")) {
                    if (!Globals.getExternalCacheDir(this).exists()) {
                        Globals.getExternalCacheDir(this).mkdirs();
                    }
                    final Globals.DownloadTask downloadTask = new Globals.DownloadTask(this);
                    downloadTask.execute(in.getData().toString(), in.getData().getLastPathSegment());
                    in.setData(null);
                } else {
                    Toast.makeText(this, "This is a directory, not a file", Toast.LENGTH_SHORT).show();
                }
            } else if (in.getData().getScheme().equals("content") && (data.contains("downloads"))) {
                String filename = null;
                Cursor cursor = null;
                try {
                    cursor = this.getContentResolver().query(in.getData(),
                            new String[] { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }, null, null,
                            null);
                    if (cursor != null && cursor.moveToFirst()) {
                        filename = cursor.getString(0);
                    }
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
                try {
                    InputStream input = getContentResolver().openInputStream(in.getData());
                    if (new File(Globals.getExternalCacheDir(this).getAbsolutePath() + '/' + filename)
                            .exists()) {
                        new File(Globals.getExternalCacheDir(this).getAbsolutePath() + '/' + filename).delete();
                    }
                    OutputStream output = new FileOutputStream(
                            Globals.getExternalCacheDir(this).getAbsolutePath() + '/' + filename);

                    byte[] buffer = new byte[4096];
                    int count;
                    while ((count = input.read(buffer)) != -1) {
                        output.write(buffer, 0, count);
                    }
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }

                File f = new File(Globals.getExternalCacheDir(this).getAbsolutePath() + '/');
                if (f.exists()) {
                    if (f.isDirectory()) {
                        ArrayList<String> files = new ArrayList<String>();
                        int position = -1;
                        int goodCounter = 0;
                        for (File ff : f.listFiles()) {
                            if (ff != null && ff.isFile()) {
                                int dotPosition = ff.getName().lastIndexOf('.');
                                String extension = "";
                                if (dotPosition != -1) {
                                    extension = (ff.getName().substring(dotPosition)).toLowerCase(Locale.US);
                                    if (extension != null) {
                                        if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles)
                                                .contains("*" + extension + "*")) {

                                            files.add(ff.getPath());
                                            if (ff.getPath()
                                                    .equals(Globals.getExternalCacheDir(this).getAbsolutePath()
                                                            + '/' + filename))
                                                position = goodCounter;
                                            goodCounter++;
                                        }
                                    }
                                }
                            }
                        }
                        if (position == -1)
                            Toast.makeText(this, getResources().getString(R.string.intErr1), Toast.LENGTH_SHORT)
                                    .show();
                        else {
                            stop();
                            selectedSong(files, position, true, false, false);
                            fileFrag.getDir(Globals.getExternalCacheDir(this).getAbsolutePath());
                        }
                    }
                }

            } else {
                System.out.println(in.getDataString());
                Toast.makeText(this,
                        getResources().getString(R.string.intErr2) + " (" + in.getData().getScheme() + ")",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }
}

From source file:com.github.colorchief.colorchief.MainActivity.java

private String getUriFileName(Uri uri) {
    String uriString = uri.toString();
    File file = new File(uriString);
    String path = file.getAbsolutePath();
    String displayName = null;/* w  w w  .j  a v a 2  s  . c o  m*/

    if (uriString.startsWith("content://")) {
        Cursor cursor = null;
        try {
            cursor = getContentResolver().query(uri, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
        } finally {
            cursor.close();
        }
    } else if (uriString.startsWith("file://")) {
        displayName = file.getName();
    }
    return displayName;
}