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:de.appplant.cordova.emailcomposer.EmailComposerImpl.java

/**
 * The URI for a file.//from   ww  w .  ja  v  a  2 s. co  m
 *
 * @param path
 * The given absolute path.
 * @return
 * The URI pointing to the given path.
 */
private Uri getUriForAbsolutePath(String path) {
    String absPath = path.replaceFirst("file://", "");
    File file = new File(absPath);

    if (!file.exists()) {
        Log.e("EmailComposer", "File not found: " + file.getAbsolutePath());
    }

    return Uri.fromFile(file);
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Take a picture with the camera./*from   www  .  j  ava  2s.  c o  m*/
 * When an image is captured or the camera view is cancelled, the result is returned
 * in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult.
 *
 * The image can either be returned as a base64 string or a URI that points to the file.
 * To display base64 string in an img tag, set the source to:
 *      img.src="data:image/jpeg;base64,"+result;
 * or to display URI in an img tag
 *      img.src=result;
 *
 * @param quality           Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
 * @param returnType        Set the type of image to return.
 */
public void takePicture(int returnType, int encodingType) {
    // Save the number of images currently on disk for later
    this.numPics = queryImgDB(whichContentStore()).getCount();

    // Display camera
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

    // Specify file so that large image is captured and returned
    File photo = createCaptureFile(encodingType);
    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    this.imageUri = Uri.fromFile(photo);

    if (this.cordova != null) {
        this.cordova.startActivityForResult((Plugin) this, intent, (CAMERA + 1) * 16 + returnType + 1);
    }
    //        else
    //            LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
}

From source file:com.wikonos.fingerprint.activities.MainActivity.java

/**
 * Create dialog list of logs/*from ww w  .  j  av  a2  s. c om*/
 * 
 * @return
 */
public AlertDialog getDialogReviewLogs() {
    /**
     * List of logs
     */
    File folder = new File(LogWriter.APPEND_PATH);
    final String[] files = folder.list(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            if (filename.contains(".log") && !filename.equals(LogWriter.DEFAULT_NAME)
                    && !filename.equals(LogWriterSensors.DEFAULT_NAME)
                    && !filename.equals(ErrorLog.DEFAULT_NAME))
                return true;
            else
                return false;
        }
    });

    Arrays.sort(files);
    ArrayUtils.reverse(files);

    String[] files_with_status = new String[files.length];
    String[] sent_mode = { "", "(s) ", "(e) ", "(s+e) " };
    for (int i = 0; i < files.length; ++i) {
        //0 -- not sent
        //1 -- server
        //2 -- email
        files_with_status[i] = sent_mode[getSentFlags(files[i], this)] + files[i];
    }

    if (files != null && files.length > 0) {

        final boolean[] selected = new boolean[files.length];

        final AlertDialog ald = new AlertDialog.Builder(MainActivity.this)
                .setMultiChoiceItems(files_with_status, selected,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                selected[which] = isChecked;
                            }
                        })
                .setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                })
                /**
                * Delete log
                */
                .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        //Show delete confirm
                        standardConfirmDialog("Delete Logs", "Are you sure you want to delete selected logs?",
                                new OnClickListener() {
                                    //Confrim Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        int deleteCount = 0;
                                        boolean flagSelected = false;
                                        for (int i = 0; i < selected.length; i++) {
                                            if (selected[i]) {
                                                flagSelected = true;
                                                LogWriter.delete(files[i]);
                                                LogWriter.delete(files[i].replace(".log", ".dev"));
                                                deleteCount++;
                                            }
                                        }

                                        reviewLogsCheckItems(flagSelected);

                                        removeDialog(DIALOG_ID_REVIEW);

                                        Toast.makeText(getApplicationContext(), deleteCount + " logs deleted.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, new OnClickListener() {
                                    //Cancel Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //Do nothing
                                        dialog.dismiss();
                                        Toast.makeText(getApplicationContext(), "Delete cancelled.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, false);
                    }
                })
                /**
                * Send to server functional
                **/
                .setNeutralButton("Send to Server", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (isOnline()) {
                            ArrayList<String> filesList = new ArrayList<String>();

                            for (int i = 0; i < selected.length; i++)
                                if (selected[i]) {

                                    filesList.add(LogWriter.APPEND_PATH + files[i]);
                                    //Move to httplogsender
                                    //setSentFlags(files[i], 1, MainActivity.this);   //Mark file as sent
                                }

                            if (reviewLogsCheckItems(filesList.size() > 0 ? true : false)) {
                                DataPersistence d = new DataPersistence(getApplicationContext());
                                new HttpLogSender(MainActivity.this,
                                        d.getServerName() + getString(R.string.submit_log_url), filesList)
                                                .setToken(getToken()).execute();
                            }

                            // removeDialog(DIALOG_ID_REVIEW);
                        } else {
                            standardAlertDialog(getString(R.string.msg_alert),
                                    getString(R.string.msg_no_internet), null);
                        }
                    }
                })
                /**
                * Email
                **/
                .setPositiveButton("eMail", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        boolean flagSelected = false;
                        // convert from paths to Android friendly
                        // Parcelable Uri's
                        ArrayList<Uri> uris = new ArrayList<Uri>();
                        for (int i = 0; i < selected.length; i++)
                            if (selected[i]) {
                                flagSelected = true;
                                /** wifi **/
                                File fileIn = new File(LogWriter.APPEND_PATH + files[i]);
                                Uri u = Uri.fromFile(fileIn);
                                uris.add(u);

                                /** sensors **/
                                File fileInSensors = new File(
                                        LogWriter.APPEND_PATH + files[i].replace(".log", ".dev"));
                                Uri uSens = Uri.fromFile(fileInSensors);
                                uris.add(uSens);

                                setSentFlags(files[i], 2, MainActivity.this); //Mark file as emailed
                            }

                        if (reviewLogsCheckItems(flagSelected)) {
                            /**
                             * Run sending email activity
                             */
                            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
                            emailIntent.setType("plain/text");
                            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                    "Wifi Searcher Scan Log");
                            emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                            startActivity(Intent.createChooser(emailIntent, "Send mail..."));
                        }

                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                }).create();

        ald.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                AlertDialog segmentNameAlert = segmentNameDailog("Rename Segment", ald.getContext(),
                        files[position], null, view, files, position);
                segmentNameAlert.setCanceledOnTouchOutside(false);
                segmentNameAlert.show();
                return false;
            }
        });
        return ald;
    } else {
        return standardAlertDialog(getString(R.string.msg_alert), getString(R.string.msg_log_nocount),
                new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        removeDialog(DIALOG_ID_REVIEW);
                    }
                });
    }
}

From source file:org.mobisocial.corral.ContentCorral.java

public static Uri storeContent(Context context, Uri contentUri, String type) {
    File contentDir;/*from   w w w.j av a2  s.co m*/
    if (type != null && (type.startsWith("image/") || type.startsWith("video/"))) {
        contentDir = new File(Environment.getExternalStorageDirectory(), PICTURE_SUBFOLDER);
    } else {
        contentDir = new File(Environment.getExternalStorageDirectory(), FILES_SUBFOLDER);
    }

    if (!contentDir.exists() && !contentDir.mkdirs()) {
        Log.e(TAG, "failed to create musubi corral directory");
        return null;
    }
    int timestamp = (int) (System.currentTimeMillis() / 1000L);
    String ext = CorralDownloadClient.extensionForType(type);
    String fname = timestamp + "-" + contentUri.getLastPathSegment() + "." + ext;
    File copy = new File(contentDir, fname);
    FileOutputStream out = null;
    InputStream in = null;
    try {
        contentDir.mkdirs();
        in = context.getContentResolver().openInputStream(contentUri);
        BufferedInputStream bin = new BufferedInputStream(in);
        byte[] buff = new byte[1024];
        out = new FileOutputStream(copy);
        int r;
        while ((r = bin.read(buff)) > 0) {
            out.write(buff, 0, r);
        }
        bin.close();
        return Uri.fromFile(copy);
    } catch (IOException e) {
        Log.w(TAG, "Error copying file", e);
        if (copy.exists()) {
            copy.delete();
        }
        return null;
    } finally {
        try {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        } catch (IOException e) {
            Log.e(TAG, "failed to close handle on store corral content", e);
        }
    }
}

From source file:es.uja.photofirma.android.CameraActivity.java

/**
 * Se ejecuta al pulsar sobre el boton para abrir la captura de fotos, inicia la captura y almacena la fotografa realizada
 */// w w w .  java  2  s  .c om
public void onTakeAPhoto(View view) {
    logger.appendLog(300, "el usuario abre la aplicacion de fotos");

    //Se crea nueva instancia de la clase PhotoMaker() para automatizar el proceso de trabajo con fotografas
    PhotoCapture = new PhotoMaker();
    File imagen = PhotoCapture.savePhoto();
    photoLocation = imagen.getAbsolutePath();

    //Se redirige al usuario a la app de captura de fotografas
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(imagen));
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        //         Toast.makeText(getApplicationContext(), getString(R.string.privacy_alert), Toast.LENGTH_LONG).show();
        startActivityForResult(takePictureIntent, CameraActivity.REQUEST_IMAGE_CAPTURE);
    }
}

From source file:de.appplant.cordova.plugin.emailcomposer.EmailComposer.java

/**
 * The URI for an asset./*  w ww .  j  av a 2  s .  co m*/
 *
 * @param {String} path
 *      The given asset path
 *
 * @return The URI pointing to the given path
 */
private Uri getUriForAssetPath(String path) {
    String resPath = path.replaceFirst("www:/", "www");
    String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
    String storage = cordova.getActivity().getExternalCacheDir().toString() + STORAGE_FOLDER;

    File file = new File(storage, fileName);

    new File(storage).mkdir();

    try {
        AssetManager assets = cordova.getActivity().getAssets();

        FileOutputStream outStream = new FileOutputStream(file);
        InputStream inputStream = assets.open(resPath);

        copyFile(inputStream, outStream);
        outStream.flush();
        outStream.close();
    } catch (Exception e) {
        System.err.println("Attachment asset not found: assets/" + resPath);
        e.printStackTrace();
    }

    return Uri.fromFile(file);
}

From source file:com.support.android.designlibdemo.activities.CampaignDetailActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    imageUrls = new ArrayList<String>();
    customProgress = (CustomProgress) findViewById(R.id.pbGoal);
    ivCampaignImage = (ImageView) findViewById(R.id.ivCampaighnImage);
    tvCampaignOverview = (TextView) findViewById(R.id.tvCampaignOverview);
    ivArrowDown = (ImageView) findViewById(R.id.ivArrowDown);
    //   tvCampaignText = (TextView) findViewById(R.id.tvCampaignDetails);
    tvGoal = (TextView) findViewById(R.id.tvCampaignGoal);
    btTakeActionRipple = (RippleView) findViewById(R.id.bt_take_an_action_ripple);
    campaign = (Campaign) getIntent().getSerializableExtra(ITENT_TAG);

    if (campaign.getIsSupported()) {
        btTakeActionRipple.setVisibility(View.GONE);
        ivArrowDown.setImageResource(R.drawable.ic_checked);
    } else {//w w  w.  ja  v  a  2 s.  c  o  m
        btTakeActionRipple.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
            @Override
            public void onComplete(RippleView rippleView) {
                Intent i = new Intent(CampaignDetailActivity.this, SignPetitionActivity.class);
                i.putExtra(ITENT_TAG, campaign);
                startActivity(i);
            }
        });
    }

    getImagesUploadedByUserForCampaign(campaign.getObjectId());

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);

    collapsingToolbar.setTitle(campaign.getTitle());
    collapsingToolbar.getCollapsedTitleGravity();
    loadBackdrop(campaign.getImageUrl(), ivCampaignImage);

    PrettyText goal = new PrettyText();
    String decimalGoal = "";
    String decimalCount = "";

    //setting up progress bar
    customProgress.setProgressColor(getResources().getColor(R.color.green_500));
    customProgress.setProgressBackgroundColor(getResources().getColor(R.color.green_200));
    customProgress.setMaximumPercentage(calculatePercentage(campaign.getGoal(), campaign.getGoalCount()));
    customProgress.useRoundedRectangleShape(30.0f);
    customProgress.setShowingPercentage(true);
    //set text above progress
    tvCampaignOverview.setText(campaign.getShortDescription());

    expandableTextView = (ExpandableTextView) findViewById(R.id.viewmore);

    expandableTextView.setText(campaign.getLongDescription());

    //  tvCampaignText.setText(campaign.getLongDescription());

    //set goal text
    decimalGoal = goal.addComma(campaign.getGoal()) + " signatures";
    decimalCount = goal.addComma(campaign.getGoalCount());
    tvGoal.setText(decimalCount + " out of " + decimalGoal);

    ivCampaignImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (imageUrls.size() > 0) {
                Intent i = new Intent(CampaignDetailActivity.this, PhotoGalleryActivity.class);
                i.putExtra(ITENT_TAG, campaign.getObjectId());
                i.putStringArrayListExtra(ITENT_TAG, imageUrls);
                startActivity(i);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            } else {
                buildDialogNoPictures(CampaignDetailActivity.this).show();
            }
        }
    });

    //set floating action button
    floatingCamera = (FloatingActionButton) findViewById(R.id.bt_camera);
    final int[] selection = new int[1];

    floatingCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FragmentManager fm = getSupportFragmentManager();
            final CameraDialog dialog = CameraDialog.newInstance("Add a new picture:");

            dialog.setOnChoiceClickListener(new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    selection[0] = which;
                }
            });

            dialog.setPositiveListener(new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    if (selection[0] == 0) {
                        // create Intent to take a picture and return control to the calling application
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        photoUri = Uri.fromFile(getOutputMediaFile()); // create a file to save the image
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); // set the image file name
                        // Start the image capture intent to take photo
                        startActivityForResult(intent, TAKE_PHOTO_CODE);
                    } else {
                        // Take the user to the gallery app to pick a photo
                        Intent photoGalleryIntent = new Intent(Intent.ACTION_PICK,
                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(photoGalleryIntent, PICK_PHOTO_CODE);

                    }
                    dialog.dismiss();

                }
            });

            dialog.setCancelClickListener(new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                }

            });

            dialog.show(fm, "TAG_DIALOG");

        }

    });

}

From source file:it.telecomitalia.my.base_struct_apps.VersionUpdate.java

@Override
protected Void doInBackground(String... urls) {
    /* metodo principale per aggiornamento */
    String xml = "";
    try {/*from  www. j  a v  a 2  s  .  c o m*/
        /* tento di leggermi il file XML remoto */
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(SERVER + PATH + VERSIONFILE);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
        /* ora in xml c' il codice della pagina degli aggiornamenti */
    } catch (IOException e) {
        e.printStackTrace();
    }
    // TODO: org.apache.http.conn.HttpHostConnectException ovvero host non raggiungibile
    try {
        /* nella variabile xml, c' il codice della pagina remota per gli aggiornamenti.
        * Per le mie esigenze, prendo dall'xml l'attributo value per vedere a che versione  la
        * applicazione sul server.*/
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        // http://stackoverflow.com/questions/1706493/java-net-malformedurlexception-no-protocol
        InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        Document dom = db.parse(is);
        Element element = dom.getDocumentElement();
        Element current = (Element) element.getElementsByTagName("current").item(0);
        currentVersion = current.getAttribute("value");
        currentApkName = current.getAttribute("apk");
    } catch (Exception e) {
        e.printStackTrace();
    }
    /* con il costruttore ho stabilito quale versione sta girando sul terminale, e con questi
    * due try, mi son letto XML remoto e preso la versione disponibile sul server e il relativo
    * nome dell'apk, caso ai dovesse servirmi. Ora li confronto e decido che fare */
    if (currentVersion != null & runningVersion != null) {
        /* esistono, li trasformo in double */
        Double serverVersion = Double.parseDouble(currentVersion);
        Double localVersion = Double.parseDouble(runningVersion);
        /* La versione server  superiore alla mia ! Occorre aggiornare */
        if (serverVersion > localVersion) {
            try {
                /* connessione al server */
                URL urlAPK = new URL(SERVER + PATH + currentApkName);
                HttpURLConnection con = (HttpURLConnection) urlAPK.openConnection();
                con.setRequestMethod("GET");
                con.setDoOutput(true);
                con.connect();
                // qual' la tua directory di sistema Download ?
                File downloadPath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                File outputFile = new File(downloadPath, currentApkName);
                //Log.i("test", downloadPath.getAbsolutePath());
                //Log.i("test", outputFile.getAbsolutePath());
                // se esistono download parziali o vecchi, li elimino.
                if (outputFile.exists())
                    outputFile.delete();
                /* mi creo due File Stream uno di input, quello che sto scaricando dal server,
                * e l'altro di output, quello che sto creando nella directory Download*/
                InputStream input = con.getInputStream();
                FileOutputStream output = new FileOutputStream(outputFile);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = input.read(buffer)) != -1) {
                    output.write(buffer, 0, count);
                }
                output.close();
                input.close();
                /* una volta terminato il processo, attraverso un intent lancio il file che ho
                * appena scaricato in modo da installare immediatamente l'aggiornamento come
                * specificato qui
                * http://stackoverflow.com/questions/4967669/android-install-apk-programmatically*/
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(new File(outputFile.getAbsolutePath())),
                        "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:com.esri.arcgisruntime.sample.editfeatureattachments.EditAttachmentActivity.java

private void fetchAttachmentAsync(final int position, final View view) {

    progressDialog.setTitle(getApplication().getString(R.string.downloading_attachments));
    progressDialog.setMessage(getApplication().getString(R.string.wait));
    progressDialog.show();//from  w w w .j  a v  a2  s .  c  o m

    // create a listenableFuture to fetch the attachment asynchronously
    final ListenableFuture<InputStream> listenableFuture = attachments.get(position).fetchDataAsync();
    listenableFuture.addDoneListener(new Runnable() {
        @Override
        public void run() {
            try {
                String fileName = attachmentList.get(position);
                // create a drawable from InputStream
                Drawable d = Drawable.createFromStream(listenableFuture.get(), fileName);
                // create a bitmap from drawable
                Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
                File root = Environment.getExternalStorageDirectory();
                File fileDir = new File(root.getAbsolutePath() + "/ArcGIS/Attachments");
                // create folder /ArcGIS/Attachments in external storage
                boolean isDirectoryCreated = fileDir.exists();
                if (!isDirectoryCreated) {
                    isDirectoryCreated = fileDir.mkdirs();
                }
                File file = null;
                if (isDirectoryCreated) {
                    file = new File(fileDir, fileName);
                    FileOutputStream fos = new FileOutputStream(file);
                    // compress the bitmap to PNG format
                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
                    fos.flush();
                    fos.close();
                }

                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                // open the file in gallery
                Intent i = new Intent();
                i.setAction(android.content.Intent.ACTION_VIEW);
                i.setDataAndType(Uri.fromFile(file), "image/png");
                startActivity(i);

            } catch (Exception e) {
                Log.d(TAG, e.toString());
            }

        }
    });
}

From source file:mobisocial.musubi.objects.FileObj.java

@Override
synchronized public void activate(final Context context, final DbObj obj) {
    CorralDownloadClient client = CorralDownloadClient.getInstance(context);
    JSONObject json = obj.getJson();//from   w w  w . j a v  a2  s. c om
    final String mimeType;
    try {
        mimeType = json.getString(CorralDownloadClient.OBJ_MIME_TYPE);
    } catch (JSONException e) {
        Toast.makeText(context, "Could not view this file.", Toast.LENGTH_SHORT);
        Log.e(TAG, "Error viewing file", e);
        return;
    }

    if (client.fileAvailableLocally(obj)) {
        Uri uri = client.getAvailableContentUri(obj);
        viewfile(context, uri, mimeType);
        return;
    }

    if (obj.getRaw() != null) {
        // in-place file delivery. How convenient.
        File cacheFile = CorralDownloadClient.localFileForContent(obj, false);
        try {
            FileOutputStream output = new FileOutputStream(cacheFile);
            output.write(obj.getRaw());
            output.close();
            viewfile(context, Uri.fromFile(cacheFile), mimeType);
        } catch (IOException e) {
            Toast.makeText(context, "Error loading this file.", Toast.LENGTH_SHORT).show();
        }
        return;
    }

    // attempt a download.
    CorralDownloadFuture future = CorralDownloadHandler.startOrFetchDownload(context, obj);
    FileDownloadDialogFragment f = new FileDownloadDialogFragment(future, mimeType);
    future.registerCallback(f);
    ((MusubiBaseActivity) context).showDialog(f, false);
}