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.google.android.apps.mytracks.ImportActivity.java

private String getNameFromContentUri(Uri contentUri) {

    final String name;

    final Cursor returnCursor = this.getContentResolver().query(contentUri, null, null, null, null);

    if (returnCursor != null && returnCursor.moveToFirst()) {

        int columnIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);

        if (columnIndex != -1) {

            name = returnCursor.getString(columnIndex);

        } else {/*from   w  ww. j a va2s . c om*/

            name = contentUri.getLastPathSegment();

        }

    } else {

        name = null;

    }

    if (returnCursor != null && !returnCursor.isClosed()) {

        returnCursor.close();

    }

    return name;

}

From source file:com.pixby.texo.images.ImageUtil.java

public static String getFileNameFromCursor(Cursor cursor) {
    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    cursor.moveToFirst();//w ww . j  a v  a 2 s  .  c om
    return cursor.getString(nameIndex);
}

From source file:com.android.messaging.datamodel.MediaScratchFileProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    if (projection != null && projection.length > 0
            && TextUtils.equals(projection[0], OpenableColumns.DISPLAY_NAME) && isMediaScratchSpaceUri(uri)) {
        // Retrieve the display name associated with a temp file. This is used by the Contacts
        // ImportVCardActivity to retrieve the name of the contact(s) being imported.
        String displayName;/*from  w ww . ja  v  a2 s.  c om*/
        synchronized (sUriToDisplayNameMap) {
            displayName = sUriToDisplayNameMap.get(uri);
        }
        if (!TextUtils.isEmpty(displayName)) {
            MatrixCursor cursor = new MatrixCursor(new String[] { OpenableColumns.DISPLAY_NAME });
            RowBuilder row = cursor.newRow();
            row.add(displayName);
            return cursor;
        }
    }
    return null;
}

From source file:com.github.barteksc.sample.PDFViewActivity.java

public String getFileName(Uri uri) {
    String result = null;//from w w w. j  a va  2  s. co  m
    if (uri.getScheme().equals("content")) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    if (result == null) {
        result = uri.getLastPathSegment();
    }
    return result;
}

From source file:org.c99.wear_imessage.RemoteInputService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_REPLY.equals(action)) {
            JSONObject conversations = null, conversation = null;
            try {
                conversations = new JSONObject(
                        getSharedPreferences("data", 0).getString("conversations", "{}"));
            } catch (JSONException e) {
                conversations = new JSONObject();
            }//from   w w w  .j  av  a 2s . c  o m

            try {
                String key = intent.getStringExtra("service") + ":" + intent.getStringExtra("handle");
                if (conversations.has(key)) {
                    conversation = conversations.getJSONObject(key);
                } else {
                    conversation = new JSONObject();
                    conversations.put(key, conversation);

                    long time = new Date().getTime();
                    String tmpStr = String.valueOf(time);
                    String last4Str = tmpStr.substring(tmpStr.length() - 5);
                    conversation.put("notification_id", Integer.valueOf(last4Str));
                    conversation.put("msgs", new JSONArray());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
            if (remoteInput != null || intent.hasExtra("reply")) {
                String reply = remoteInput != null ? remoteInput.getCharSequence("extra_reply").toString()
                        : intent.getStringExtra("reply");

                if (intent.hasExtra(Intent.EXTRA_STREAM)) {
                    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                            .setContentTitle("Uploading File").setProgress(0, 0, true).setLocalOnly(true)
                            .setOngoing(true).setSmallIcon(android.R.drawable.stat_sys_upload);
                    NotificationManagerCompat.from(this).notify(1337, notification.build());

                    InputStream fileIn = null;
                    InputStream responseIn = null;
                    HttpURLConnection http = null;
                    try {
                        String filename = "";
                        int total = 0;
                        String type = getContentResolver()
                                .getType((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
                        if (type == null || type.length() == 0)
                            type = "application/octet-stream";
                        fileIn = getContentResolver()
                                .openInputStream((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));

                        Cursor c = getContentResolver().query(
                                (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM),
                                new String[] { OpenableColumns.SIZE, OpenableColumns.DISPLAY_NAME }, null, null,
                                null);
                        if (c != null && c.moveToFirst()) {
                            total = c.getInt(0);
                            filename = c.getString(1);
                            c.close();
                        } else {
                            total = fileIn.available();
                        }

                        String boundary = UUID.randomUUID().toString();
                        http = (HttpURLConnection) new URL(
                                "http://" + getSharedPreferences("prefs", 0).getString("host", "") + "/upload")
                                        .openConnection();
                        http.setReadTimeout(60000);
                        http.setConnectTimeout(60000);
                        http.setDoOutput(true);
                        http.setFixedLengthStreamingMode(total + (boundary.length() * 5) + filename.length()
                                + type.length() + intent.getStringExtra("handle").length()
                                + intent.getStringExtra("service").length() + reply.length() + 251);
                        http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                        OutputStream out = http.getOutputStream();
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"handle\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("handle") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"service\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("service") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"msg\"\r\n\r\n").getBytes());
                        out.write((reply + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename
                                + "\"\r\n").getBytes());
                        out.write(("Content-Type: " + type + "\r\n\r\n").getBytes());

                        byte[] buffer = new byte[8192];
                        int count = 0;
                        int n = 0;
                        while (-1 != (n = fileIn.read(buffer))) {
                            out.write(buffer, 0, n);
                            count += n;

                            float progress = (float) count / (float) total;
                            if (progress < 1.0f)
                                notification.setProgress(1000, (int) (progress * 1000), false);
                            else
                                notification.setProgress(0, 0, true);
                            NotificationManagerCompat.from(this).notify(1337, notification.build());
                        }

                        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
                        out.flush();
                        out.close();
                        if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
                            responseIn = http.getInputStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.i("iMessage", "Upload result: " + sb.toString());
                            try {
                                if (conversation != null) {
                                    JSONArray msgs = conversation.getJSONArray("msgs");
                                    JSONObject m = new JSONObject();
                                    m.put("msg", filename);
                                    m.put("service", intent.getStringExtra("service"));
                                    m.put("handle", intent.getStringExtra("handle"));
                                    m.put("type", "sent_file");
                                    msgs.put(m);

                                    while (msgs.length() > 10) {
                                        msgs.remove(0);
                                    }

                                    GCMIntentService.notify(getApplicationContext(),
                                            intent.getIntExtra("notification_id", 0), msgs, intent, true);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            responseIn = http.getErrorStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.e("iMessage", "Upload failed: " + sb.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (responseIn != null)
                                responseIn.close();
                        } catch (Exception ignore) {
                        }
                        try {
                            if (http != null)
                                http.disconnect();
                        } catch (Exception ignore) {
                        }
                        try {
                            fileIn.close();
                        } catch (Exception ignore) {
                        }
                    }
                    NotificationManagerCompat.from(this).cancel(1337);
                } else if (reply.length() > 0) {
                    URL url = null;
                    try {
                        url = new URL("http://" + getSharedPreferences("prefs", 0).getString("host", "")
                                + "/send?service=" + intent.getStringExtra("service") + "&handle="
                                + intent.getStringExtra("handle") + "&msg="
                                + URLEncoder.encode(reply, "UTF-8"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    HttpURLConnection conn;

                    try {
                        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.setUseCaches(false);

                    BufferedReader reader = null;

                    try {
                        if (conn.getInputStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
                        }
                    } catch (IOException e) {
                        if (conn.getErrorStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512);
                        }
                    }

                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    conn.disconnect();
                    try {
                        if (conversation != null) {
                            JSONArray msgs = conversation.getJSONArray("msgs");
                            JSONObject m = new JSONObject();
                            m.put("msg", reply);
                            m.put("service", intent.getStringExtra("service"));
                            m.put("handle", intent.getStringExtra("handle"));
                            m.put("type", "sent");
                            msgs.put(m);

                            while (msgs.length() > 10) {
                                msgs.remove(0);
                            }

                            GCMIntentService.notify(getApplicationContext(),
                                    intent.getIntExtra("notification_id", 0), msgs, intent, true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                SharedPreferences.Editor e = getSharedPreferences("data", 0).edit();
                e.putString("conversations", conversations.toString());
                e.apply();
            }
        }
    }
}

From source file:me.kartikarora.transfersh.activities.TransferActivity.java

private void uploadFile(Uri uri) throws IOException {
    final ProgressDialog dialog = new ProgressDialog(TransferActivity.this);
    dialog.setMessage(getString(R.string.uploading_file));
    dialog.setCancelable(false);/*from  w  w  w  . j  a  v  a 2 s .co  m*/
    dialog.show();
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        final String name = cursor.getString(nameIndex);
        final String mimeType = getContentResolver().getType(uri);
        Log.d(this.getClass().getSimpleName(), cursor.getString(0));
        Log.d(this.getClass().getSimpleName(), name);
        Log.d(this.getClass().getSimpleName(), mimeType);
        InputStream inputStream = getContentResolver().openInputStream(uri);
        OutputStream outputStream = openFileOutput(name, MODE_PRIVATE);
        if (inputStream != null) {
            IOUtils.copy(inputStream, outputStream);
            final File file = new File(getFilesDir(), name);
            TypedFile typedFile = new TypedFile(mimeType, file);
            TransferClient.getInterface().uploadFile(typedFile, name, new ResponseCallback() {
                @Override
                public void success(Response response) {
                    BufferedReader reader;
                    StringBuilder sb = new StringBuilder();
                    try {
                        reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
                        String line;
                        try {
                            while ((line = reader.readLine()) != null) {
                                sb.append(line);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = sb.toString();
                    Snackbar.make(mCoordinatorLayout, name + " " + getString(R.string.uploaded),
                            Snackbar.LENGTH_SHORT).show();

                    ContentValues values = new ContentValues();
                    values.put(FilesContract.FilesEntry.COLUMN_NAME, name);
                    values.put(FilesContract.FilesEntry.COLUMN_TYPE, mimeType);
                    values.put(FilesContract.FilesEntry.COLUMN_URL, result);
                    values.put(FilesContract.FilesEntry.COLUMN_SIZE, String.valueOf(file.getTotalSpace()));
                    getContentResolver().insert(FilesContract.BASE_CONTENT_URI, values);
                    getSupportLoaderManager().restartLoader(BuildConfig.VERSION_CODE, null,
                            TransferActivity.this);
                    FileUtils.deleteQuietly(file);
                    if (dialog.isShowing())
                        dialog.hide();
                }

                @Override
                public void failure(RetrofitError error) {
                    error.printStackTrace();
                    if (dialog.isShowing())
                        dialog.hide();
                    Snackbar.make(mCoordinatorLayout, R.string.something_went_wrong, Snackbar.LENGTH_INDEFINITE)
                            .setAction(R.string.report, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    // TODO add feedback code
                                }
                            }).show();
                }
            });
        } else
            Snackbar.make(mCoordinatorLayout, R.string.unable_to_read, Snackbar.LENGTH_SHORT).show();
    }
}

From source file:com.wodify.cordova.plugin.filepicker.FilePicker.java

/**
 * Gets details of file stored externally, e.g. from Google Drive or Dropbox
 * // w  w  w  .jav  a2 s  .  c  o m
 * @param  uri 
 *         Uri of picked file
 */
private JSONArray getFileDetails(Uri uri) {
    Cursor cursor = this.cordova.getActivity().getContentResolver().query(uri, null, null, null, null);

    if (cursor != null && cursor.moveToFirst()) {
        String name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));

        cursor.close();

        try {
            InputStream is = this.cordova.getActivity().getContentResolver().openInputStream(uri);
            if (is != null) {
                try {
                    byte[] bytesOfFile = IOUtils.toByteArray(is);
                    return formatFileDetails(bytesOfFile, name);
                } catch (IOException e) {
                    return null;
                } catch (NullPointerException e) {
                    return null;
                }
            } else
                return null;
        } catch (FileNotFoundException e) {
            return null;
        }
    } else
        return null;
}

From source file:com.galois.qrstream.MainActivity.java

private String getNameFromURI(Uri uri) {
    String name;//from   w w w.  jav a2 s  .  c o  m
    Cursor metadata = getContentResolver().query(uri, new String[] { OpenableColumns.DISPLAY_NAME }, null, null,
            null);
    if (metadata != null && metadata.moveToFirst()) {
        name = metadata.getString(0);
    } else {
        name = uri.getLastPathSegment();
    }
    return name;
}

From source file:org.sufficientlysecure.keychain.util.FileHelper.java

public static String getFilename(Context context, Uri uri) {
    String filename = null;/*from   w ww  .  j a  va2s .com*/
    try {
        Cursor cursor = context.getContentResolver().query(uri, new String[] { OpenableColumns.DISPLAY_NAME },
                null, null, null);

        if (cursor != null) {
            if (cursor.moveToNext()) {
                filename = cursor.getString(0);
            }
            cursor.close();
        }
    } catch (Exception ignored) {
        // This happens in rare cases (eg: document deleted since selection) and should not cause a failure
    }
    if (filename == null) {
        String[] split = uri.toString().split("/");
        filename = split[split.length - 1];
    }
    return filename;
}

From source file:net.sf.fdshare.BaseProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final String filePath = uri.getPath();
    if (TextUtils.isEmpty(filePath))
        throw new IllegalArgumentException("Empty path!");

    if (projection == null) {
        projection = new String[] { MediaStore.MediaColumns.MIME_TYPE, OpenableColumns.DISPLAY_NAME,
                OpenableColumns.SIZE };/* w  w w  .  j  a va  2s. c  o  m*/
    }

    final MatrixCursor result = new MatrixCursor(projection);

    final TimestampedMime info = guessTypeInternal(filePath);

    final Object[] row = new Object[projection.length];
    for (int i = 0; i < projection.length; i++) {
        String projColumn = projection[i];

        if (TextUtils.isEmpty(projColumn))
            continue;

        switch (projColumn.toLowerCase()) {
        case OpenableColumns.DISPLAY_NAME:

            row[i] = uri.getLastPathSegment();

            break;
        case OpenableColumns.SIZE:

            row[i] = info.size >= 0 ? info.size : null;

            break;
        case MediaStore.MediaColumns.MIME_TYPE:

            final String forcedType = uri.getQueryParameter("type");

            if (!TextUtils.isEmpty(forcedType))
                row[i] = "null".equals(forcedType) ? null : forcedType;
            else
                row[i] = info.mime[0];

            break;
        case MediaStore.MediaColumns.DATA:
            Log.w("BaseProvider", "Relying on MediaColumns.DATA is unreliable and must be avoided!");
            row[i] = uri.getPath();
            break;
        }
    }

    result.addRow(row);
    return result;
}