Example usage for android.content ContentResolver openInputStream

List of usage examples for android.content ContentResolver openInputStream

Introduction

In this page you can find the example usage for android.content ContentResolver openInputStream.

Prototype

public final @Nullable InputStream openInputStream(@NonNull Uri uri) throws FileNotFoundException 

Source Link

Document

Open a stream on to the content associated with a content URI.

Usage

From source file:org.mdc.chess.MDChess.java

/**
 * Return PGN/FEN data or filename from the Intent. Both can not be non-null.
 *
 * @return Pair of PGN/FEN data and filename.
 *//* w w  w  . ja  v a 2  s . c o m*/
private Pair<String, String> getPgnOrFenIntent() {
    String pgnOrFen = null;
    String filename = null;
    try {
        Intent intent = getIntent();
        Uri data = intent.getData();
        if (data == null) {
            Bundle b = intent.getExtras();
            if (b != null) {
                Object strm = b.get(Intent.EXTRA_STREAM);
                if (strm instanceof Uri) {
                    data = (Uri) strm;
                    if ("file".equals(data.getScheme())) {
                        filename = data.getEncodedPath();
                        if (filename != null) {
                            filename = Uri.decode(filename);
                        }
                    }
                }
            }
        }
        if (data == null) {
            if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction()))
                    && ("application/x-chess-pgn".equals(intent.getType())
                            || "application/x-chess-fen".equals(intent.getType()))) {
                pgnOrFen = intent.getStringExtra(Intent.EXTRA_TEXT);
            }
        } else {
            String scheme = intent.getScheme();
            if ("file".equals(scheme)) {
                filename = data.getEncodedPath();
                if (filename != null) {
                    filename = Uri.decode(filename);
                }
            }
            if ((filename == null) && ("content".equals(scheme) || "file".equals(scheme))) {
                ContentResolver resolver = getContentResolver();
                InputStream in = resolver.openInputStream(intent.getData());
                StringBuilder sb = new StringBuilder();
                while (true) {
                    byte[] buffer = new byte[16384];
                    int len = in != null ? in.read(buffer) : 0;
                    if (len <= 0) {
                        break;
                    }
                    sb.append(new String(buffer, 0, len));
                }
                pgnOrFen = sb.toString();
            }
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), R.string.failed_to_read_pgn_data, Toast.LENGTH_SHORT).show();
    }
    return new Pair<>(pgnOrFen, filename);
}

From source file:org.mozilla.gecko.GeckoApp.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case FILE_PICKER_REQUEST:
        String filePickerResult = "";
        if (data != null && resultCode == RESULT_OK) {
            try {
                ContentResolver cr = getContentResolver();
                Uri uri = data.getData();
                Cursor cursor = GeckoApp.mAppContext.getContentResolver().query(uri,
                        new String[] { OpenableColumns.DISPLAY_NAME }, null, null, null);
                String name = null;
                if (cursor != null) {
                    try {
                        if (cursor.moveToNext()) {
                            name = cursor.getString(0);
                        }//from  ww  w  . j a  v  a 2  s.  c  o  m
                    } finally {
                        cursor.close();
                    }
                }
                String fileName = "tmp_";
                String fileExt = null;
                int period;
                if (name == null || (period = name.lastIndexOf('.')) == -1) {
                    String mimeType = cr.getType(uri);
                    fileExt = "." + GeckoAppShell.getExtensionFromMimeType(mimeType);
                } else {
                    fileExt = name.substring(period);
                    fileName = name.substring(0, period);
                }
                File file = File.createTempFile(fileName, fileExt, sGREDir);

                FileOutputStream fos = new FileOutputStream(file);
                InputStream is = cr.openInputStream(uri);
                byte[] buf = new byte[4096];
                int len = is.read(buf);
                while (len != -1) {
                    fos.write(buf, 0, len);
                    len = is.read(buf);
                }
                fos.close();
                filePickerResult = file.getAbsolutePath();
            } catch (Exception e) {
                Log.e(LOGTAG, "showing file picker", e);
            }
        }
        try {
            mFilePickerResult.put(filePickerResult);
        } catch (InterruptedException e) {
            Log.i(LOGTAG, "error returning file picker result", e);
        }
        break;
    case AWESOMEBAR_REQUEST:
        if (data != null) {
            String url = data.getStringExtra(AwesomeBar.URL_KEY);
            AwesomeBar.Type type = AwesomeBar.Type.valueOf(data.getStringExtra(AwesomeBar.TYPE_KEY));
            String searchEngine = data.getStringExtra(AwesomeBar.SEARCH_KEY);
            boolean userEntered = data.getBooleanExtra(AwesomeBar.USER_ENTERED_KEY, false);
            if (url != null && url.length() > 0)
                loadRequest(url, type, searchEngine, userEntered);
        }
        break;
    case CAMERA_CAPTURE_REQUEST:
        Log.i(LOGTAG, "Returning from CAMERA_CAPTURE_REQUEST: " + resultCode);
        File file = new File(Environment.getExternalStorageDirectory(),
                "cameraCapture-" + Integer.toString(kCaptureIndex) + ".jpg");
        kCaptureIndex++;
        GeckoEvent e = GeckoEvent.createBroadcastEvent("cameraCaptureDone",
                resultCode == Activity.RESULT_OK ? "{\"ok\": true,  \"path\": \"" + file.getPath() + "\" }"
                        : "{\"ok\": false, \"path\": \"" + file.getPath() + "\" }");
        GeckoAppShell.sendEventToGecko(e);
        break;
    }
}

From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java

private long getOutStreamSizeAndData(Uri uri, String contentType) throws IOException {

    String name = null;/* w  ww  .  j  a v  a 2s.c  om*/
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.DISPLAY_NAME }, null, null,
                null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    name = c.getString(c.getColumnIndex(MediaColumns.DISPLAY_NAME));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    long size = -1;
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.SIZE }, null, null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    size = c.getInt(c.getColumnIndex(MediaColumns.SIZE));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    String data = null;
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.DATA }, null, null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    data = c.getString(c.getColumnIndex(MediaColumns.DATA));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    if (name == null) {
        name = uri.getLastPathSegment();
    }

    File f = null;
    if (size <= 0) {
        String uriString = uri.toString();
        if (uriString.startsWith("file://")) {
            MyLog.v(TAG, uriString.substring("file://".length()));
            f = new File(uriString.substring("file://".length()));
            size = f.length();
        } else {
            MyLog.v(TAG, "not a file: " + uriString);
        }
    }

    ContentResolver cr = getContentResolver();
    InputStream is;
    // read file bytes
    try {
        is = cr.openInputStream(uri);
    } catch (FileNotFoundException e) {
        if (!TextUtils.isEmpty(data)) {
            is = new FileInputStream(data);
        } else {
            return -1; // unable to load file at all
        }
    }

    if ((contentType != null) && (contentType.indexOf('*') != -1)) {
        contentType = getContentResolver().getType(uri);
    }

    if (contentType == null) {
        contentType = URLConnection.guessContentTypeFromStream(is);
        if (contentType == null) {
            String extension = SSUtil.getFileExtensionOnly(name);
            contentType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            if (contentType == null) {
                contentType = SafeSlingerConfig.MIMETYPE_OPEN_ATTACH_DEF;
            }
        }
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[4096];
    while (is.read(buf) > -1) {
        baos.write(buf);
    }
    baos.flush();

    final byte[] fileBytes = baos.toByteArray();
    DraftData d = DraftData.INSTANCE;
    d.setFileData(fileBytes);
    d.setFileSize(fileBytes.length);
    d.setFileType(contentType);
    d.setFileName(name);
    if (f != null && f.exists()) {
        d.setFileDir(f.getAbsolutePath());
    } else if (!TextUtils.isEmpty(data)) {
        d.setFileDir(new File(data).getAbsolutePath());
    }
    return d.getFileSize();
}

From source file:edu.mit.viral.shen.DroidFish.java

private final Pair<String, String> getPgnOrFenIntent() {
    String pgnOrFen = null;//from w w w  .j a  v a2s  . c  o  m
    String filename = null;
    try {
        Intent intent = getIntent();
        Uri data = intent.getData();
        if (data == null) {
            if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction()))
                    && ("application/x-chess-pgn".equals(intent.getType())
                            || "application/x-chess-fen".equals(intent.getType())))
                pgnOrFen = intent.getStringExtra(Intent.EXTRA_TEXT);
        } else {
            String scheme = intent.getScheme();
            if ("file".equals(scheme)) {
                filename = data.getEncodedPath();
                if (filename != null)
                    filename = Uri.decode(filename);
            }
            if ((filename == null) && ("content".equals(scheme) || "file".equals(scheme))) {
                ContentResolver resolver = getContentResolver();
                InputStream in = resolver.openInputStream(intent.getData());
                StringBuilder sb = new StringBuilder();
                while (true) {
                    byte[] buffer = new byte[16384];
                    int len = in.read(buffer);
                    if (len <= 0)
                        break;
                    sb.append(new String(buffer, 0, len));
                }
                pgnOrFen = sb.toString();
            }
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), R.string.failed_to_read_pgn_data, Toast.LENGTH_SHORT).show();
    }
    return new Pair<String, String>(pgnOrFen, filename);
}

From source file:com.if3games.chessonline.DroidFish.java

/**
 * Return PGN/FEN data or filename from the Intent. Both can not be non-null.
 * @return Pair of PGN/FEN data and filename.
 *//* w w  w.  ja  v a2s .  c  o m*/
private final Pair<String, String> getPgnOrFenIntent() {
    String pgnOrFen = null;
    String filename = null;
    try {
        Intent intent = getIntent();
        Uri data = intent.getData();
        if (data == null) {
            Bundle b = intent.getExtras();
            if (b != null) {
                Object strm = b.get(Intent.EXTRA_STREAM);
                if (strm instanceof Uri) {
                    data = (Uri) strm;
                    if ("file".equals(data.getScheme())) {
                        filename = data.getEncodedPath();
                        if (filename != null)
                            filename = Uri.decode(filename);
                    }
                }
            }
        }
        if (data == null) {
            if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction()))
                    && ("application/x-chess-pgn".equals(intent.getType())
                            || "application/x-chess-fen".equals(intent.getType())))
                pgnOrFen = intent.getStringExtra(Intent.EXTRA_TEXT);
        } else {
            String scheme = intent.getScheme();
            if ("file".equals(scheme)) {
                filename = data.getEncodedPath();
                if (filename != null)
                    filename = Uri.decode(filename);
            }
            if ((filename == null) && ("content".equals(scheme) || "file".equals(scheme))) {
                ContentResolver resolver = getContentResolver();
                InputStream in = resolver.openInputStream(intent.getData());
                StringBuilder sb = new StringBuilder();
                while (true) {
                    byte[] buffer = new byte[16384];
                    int len = in.read(buffer);
                    if (len <= 0)
                        break;
                    sb.append(new String(buffer, 0, len));
                }
                pgnOrFen = sb.toString();
            }
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), R.string.failed_to_read_pgn_data, Toast.LENGTH_SHORT).show();
    }
    return new Pair<String, String>(pgnOrFen, filename);
}