Example usage for android.net Uri fromFile

List of usage examples for android.net Uri fromFile

Introduction

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

Prototype

public static Uri fromFile(File file) 

Source Link

Document

Creates a Uri from a file.

Usage

From source file:com.guinatal.refreshgallery.PluginRefreshGallery.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  A PluginResult object with a status and message.
 *///from ww w.ja v a 2s .c  o  m

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {

    this.callbackContext = callbackContext;

    try {

        if (action.equals("refresh")) {

            String filePath = checkFilePath(args.getString(0));

            if (filePath.equals("")) {
                PluginResult r = new PluginResult(PluginResult.Status.ERROR);
                callbackContext.sendPluginResult(r);
                return true;
            }

            File file = new File(filePath);

            Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            scanIntent.setData(Uri.fromFile(file));

            Context context = webView.getContext();
            context.sendBroadcast(scanIntent);
        }

        PluginResult r = new PluginResult(PluginResult.Status.OK);
        callbackContext.sendPluginResult(r);
        return true;

    } catch (JSONException e) {

        PluginResult r = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
        callbackContext.sendPluginResult(r);
        return true;

    } catch (Exception e) {

        PluginResult r = new PluginResult(PluginResult.Status.ERROR);
        callbackContext.sendPluginResult(r);
        return true;
    }
}

From source file:net.potterpcs.recipebook.DownloadImageTask.java

private Bitmap downloadImage(String... urls) {
    Bitmap bitmap = null;/*from  w  ww  . j  av a 2  s .  c  om*/
    RecipeData data = ((RecipeBook) parent.getApplication()).getData();

    AndroidHttpClient client = AndroidHttpClient.newInstance("A to Z Recipes for Android");

    if (data.isCached(urls[0])) {
        // Retrieve a cached image if we have one
        String pathName = data.findCacheEntry(urls[0]);
        Uri pathUri = Uri.fromFile(new File(parent.getCacheDir(), pathName));
        try {
            bitmap = RecipeBook.decodeScaledBitmap(parent, pathUri);
        } catch (IOException e) {
            e.printStackTrace();
            bitmap = null;
        }
    } else {
        try {
            // If the image isn't in the cache, we have to go and get it.
            // First, we set up the HTTP request.
            HttpGet request = new HttpGet(urls[0]);
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(params, 60000);
            request.setParams(params);

            // Let the UI know we're working.
            publishProgress(25);

            // Retrieve the image from the network.
            HttpResponse response = client.execute(request);
            publishProgress(50);

            // Create a bitmap to put in the ImageView.
            byte[] image = EntityUtils.toByteArray(response.getEntity());
            bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
            publishProgress(75);

            // Cache the file for offline use, and to lower data usage.
            File cachePath = parent.getCacheDir();
            String cacheFile = "recipecache-" + Long.toString(System.currentTimeMillis());
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 0,
                    new FileOutputStream(new File(cachePath, cacheFile)))) {
                RecipeData appData = ((RecipeBook) parent.getApplication()).getData();
                appData.insertCacheEntry(urls[0], cacheFile);
            }
            //            Log.v(TAG, cacheFile);

            // We're done!
            publishProgress(100);
        } catch (IOException e) {
            // TODO Maybe a dialog?
        }

    }
    client.close();
    return bitmap;
}

From source file:com.phonegap.plugins.pdfViewer.PdfViewer.java

public String showPdf(String fileName) {

    File file = new File(fileName);

    if (file.exists()) {
        try {//w  ww.j  ava  2s .  c  om
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            //intent.setData(Uri.parse(fileName));
            this.ctx.startActivity(intent);
            return "";
        } catch (android.content.ActivityNotFoundException e) {
            System.out.println("PdfViewer: Error loading url " + fileName + ":" + e.toString());
            return e.toString();
        }

    } else {
        return "file not found";
    }
}

From source file:org.jared.synodroid.ds.utils.Utils.java

public static Uri moveToStorage(Activity a, Uri uri) {
    ContentResolver cr = a.getContentResolver();
    try {//from   www  .ja v  a 2 s . c  o  m
        InputStream is = cr.openInputStream(uri);

        File path = Environment.getExternalStorageDirectory();
        path = new File(path, "Android/data/org.jared.synodroid.ds/cache/");
        path.mkdirs();

        String fname = getContentName(cr, uri);
        File file = null;
        if (fname != null) {
            file = new File(path, fname);
        } else {
            file = new File(path, "attachment.att");
        }

        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();

        return uri = Uri.fromFile(file);
    } catch (FileNotFoundException e) {
        // do nothing
    } catch (IOException e) {
        // do nothing
    }

    return null;
}

From source file:com.jumpbyte.mobile.plugin.PdfViewer.java

public String showPdf(String fileName) {

    File file = new File(fileName);

    Log.i("PdfViewer", "open file " + fileName);
    //        if (file.exists()) {
    Log.i("PdfViewer", "file exist");
    try {//from   ww  w . j  a v a  2s  . co m
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        //intent.setData(Uri.parse(fileName));
        this.ctx.startActivity(intent);
        return "";
    } catch (android.content.ActivityNotFoundException e) {
        System.out.println("PdfViewer: Error loading url " + fileName + ":" + e.toString());
        return e.toString();
    }
    /*
            }else{
               Log.i("PdfViewer", "file not exist");
               return "file not found";
            }
      */

}

From source file:com.matthewtamlin.soundsword.Song.java

@Override
public Uri getUri() {
    return Uri.fromFile(file);
}

From source file:com.kircherelectronics.gyroscopeexplorer.datalogger.CsvDataLogger.java

public String writeToFile() {
    try {//from  ww w . jav  a 2 s  .  c  o  m
        fileWriter.flush();
        fileWriter.close();
        csv.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

    return file.getPath();
}

From source file:com.darktalker.cordova.screenshot.Screenshot.java

private void scanPhoto(String imageFileName) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(imageFileName);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.cordova.getActivity().sendBroadcast(mediaScanIntent);
}

From source file:edu.stanford.mobisocial.dungbeetle.obj.action.ExportPhotoAction.java

@Override
public void onAct(Context context, DbEntryHandler objType, DbObj obj) {
    byte[] raw = obj.getRaw();
    if (raw == null) {
        String b64Bytes = obj.getJson().optString(PictureObj.DATA);
        raw = FastBase64.decode(b64Bytes);
    }//from  ww  w. j a v a 2s  .c om
    OutputStream outStream = null;
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp_share.png");
    try {
        outStream = new FileOutputStream(file);

        BitmapManager mgr = new BitmapManager(1);
        Bitmap bitmap = mgr.getBitmap(raw.hashCode(), raw);

        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
        outStream.flush();
        outStream.close();

        bitmap.recycle();
        bitmap = null;
        System.gc();
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("image/png");
        Log.w("ResharePhotoAction",
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp_share.png");
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        context.startActivity(Intent.createChooser(intent, "Export image to"));

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

}

From source file:es.deustotech.piramide.utils.tts.TextToSpeechWeb.java

private static synchronized void speech(final Context context, final String text, final String language) {
    executor.submit(new Runnable() {
        @Override/*from  w w w. j a v a  2  s  . c om*/
        public void run() {
            try {
                final String encodedUrl = Constants.URL + language + "&q="
                        + URLEncoder.encode(text, Encoding.UTF_8.name());
                final DefaultHttpClient client = new DefaultHttpClient();
                HttpParams params = new BasicHttpParams();
                params.setParameter("http.protocol.content-charset", "UTF-8");
                client.setParams(params);
                final FileOutputStream fos = context.openFileOutput(Constants.MP3_FILE,
                        Context.MODE_WORLD_READABLE);
                try {
                    try {
                        final HttpResponse response = client.execute(new HttpGet(encodedUrl));
                        downloadFile(response, fos);
                    } finally {
                        fos.close();
                    }
                    final String filePath = context.getFilesDir().getAbsolutePath() + "/" + Constants.MP3_FILE;
                    final MediaPlayer player = MediaPlayer.create(context.getApplicationContext(),
                            Uri.fromFile(new File(filePath)));
                    player.start();
                    Thread.sleep(player.getDuration());
                    while (player.isPlaying()) {
                        Thread.sleep(100);
                    }
                    player.stop();

                } finally {
                    context.deleteFile(Constants.MP3_FILE);
                }
            } catch (InterruptedException ie) {
                // ok
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}