Example usage for android.content.res AssetFileDescriptor createInputStream

List of usage examples for android.content.res AssetFileDescriptor createInputStream

Introduction

In this page you can find the example usage for android.content.res AssetFileDescriptor createInputStream.

Prototype

public FileInputStream createInputStream() throws IOException 

Source Link

Document

Create and return a new auto-close input stream for this asset.

Usage

From source file:Main.java

private static InputStream openDisplayPhoto(final Context context, final Uri contactUri) {
    Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
    try {//from   w  w w  .j  a v a 2s.co  m
        AssetFileDescriptor fd = context.getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
        return fd.createInputStream();
    } catch (IOException e) {
        return null;
    }
}

From source file:Main.java

public static Bitmap getBitmapForDensity(Resources res, int displayDpi, int resId) {
    try {/* w  w  w.  j  a v  a 2 s .co  m*/
        TypedValue value = new TypedValue();
        res.getValueForDensity(resId, displayDpi, value, true);
        AssetFileDescriptor fd = res.getAssets().openNonAssetFd(value.assetCookie, value.string.toString());
        Options opt = new Options();
        opt.inTargetDensity = displayDpi;
        Bitmap bitmap = BitmapFactory.decodeResourceStream(res, value, fd.createInputStream(), null, opt);
        bitmap.setDensity(res.getDisplayMetrics().densityDpi);
        fd.close();
        return bitmap;
    } catch (Exception e) {
        return BitmapFactory.decodeResource(res, resId);
    }
}

From source file:com.phonegap.plugins.xapkreader.XAPKReader.java

private static byte[] readFile(Context ctx, String filename) throws IOException {
    // Get APKExpensionFile
    ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(ctx, XAPKReader.mainVersion,
            XAPKReader.patchVersion);//  w ww.jav  a2s . com

    if (null == expansionFile) {
        Log.e("XAPKReader", "APKExpansionFile not found.");
        return null;
    }

    // Find file in ExpansionFile
    String fileName = Helpers.getExpansionAPKFileName(ctx, true, XAPKReader.patchVersion);
    fileName = fileName.substring(0, fileName.lastIndexOf("."));
    AssetFileDescriptor file = expansionFile.getAssetFileDescriptor(fileName + "/" + filename);

    if (null == file) {
        Log.e("XAPKReader", "File not found (" + filename + ").");
        return null;
    }

    // Read file
    int size = (int) file.getLength();
    byte[] data = new byte[size];
    BufferedInputStream buf = new BufferedInputStream(file.createInputStream());
    buf.read(data, 0, data.length);
    buf.close();

    return data;
}

From source file:Main.java

/**
 * Reads a file that is embedded in our application and writes it to the device storage
 * @param context/*w w  w .java2s.  c  o m*/
 * @param file
 * @param assetFileDescriptor
 */
private static void saveFileToDevice(Context context, File file, AssetFileDescriptor assetFileDescriptor) {
    // The output stream is used to write the new file to the device storage
    FileOutputStream outputStream = null;
    // The input stream is used for reading the file that is embedded in our application
    FileInputStream inputStream = null;
    try {
        byte[] buffer = new byte[1024];
        // Create the input stream
        inputStream = (assetFileDescriptor != null) ? assetFileDescriptor.createInputStream() : null;
        // Create the output stream
        outputStream = new FileOutputStream(file, false);
        // Read the file into buffer
        int i = (inputStream != null) ? inputStream.read(buffer) : 0;
        // Continue writing and reading the file until we reach the end
        while (i != -1) {
            outputStream.write(buffer, 0, i);
            i = (inputStream != null) ? inputStream.read(buffer) : 0;
        }

        outputStream.flush();
    } catch (IOException io) {
        // Display a message to the user
        Toast toast = Toast.makeText(context, "Could not save the file", Toast.LENGTH_SHORT);
        toast.show();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                // We should really never get this far, but we might consider adding a
                // warning/log entry here...
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                // We should really never get this far, but we might consider adding a
                // warning/log entry here...
            }
        }
    }
}

From source file:com.digitalarx.android.syncadapter.ContactSyncAdapter.java

private FileInputStream getContactVcard(String lookupKey) throws IOException {
    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
    AssetFileDescriptor fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r");
    return fd.createInputStream();
}

From source file:org.anhonesteffort.flock.sync.addressbook.ContactFactory.java

protected static void addPicture(String path, ContentProviderClient client, Uri pictureUri, VCard vCard)
        throws InvalidComponentException, RemoteException {
    try {/*from   www  . ja v  a2s.c  om*/

        AssetFileDescriptor fileDescriptor = client.openAssetFile(pictureUri, "r");
        InputStream inputStream = fileDescriptor.createInputStream();

        Photo photo = new Photo(IOUtils.toByteArray(inputStream), ImageType.JPEG);
        vCard.addPhoto(photo);

    } catch (FileNotFoundException e) {
        // nothing to do...
    } catch (IOException e) {
        throw new InvalidComponentException("caught exception while adding picture", false,
                CardDavConstants.CARDDAV_NAMESPACE, path);
    }
}

From source file:org.apache.cordova.contactVcardpicker.ContactVcardPicker.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d("customPlugin", "Calling onActivityResult");

    if (resultCode == Activity.RESULT_OK && requestCode == 5) {
        String vCard = null;// w  w w .  j a va  2 s. c o m
        try {
            Uri contactData = data.getData();

            @SuppressWarnings("deprecation")
            Cursor cursor = cordova.getActivity().getContentResolver().query(contactData, null, null, null,
                    null);

            cursor.moveToFirst();
            String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
            Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
            AssetFileDescriptor fd = cordova.getActivity().getContentResolver().openAssetFileDescriptor(uri,
                    "r");
            FileInputStream fis = fd.createInputStream();
            byte[] b = new byte[(int) fd.getDeclaredLength()];
            fis.read(b);
            vCard = new String(b);
            System.out.println("VACRD :" + vCard);

            String contactId = data.getData().getLastPathSegment();
            Cursor c = this.cordova.getActivity().getContentResolver().query(RawContacts.CONTENT_URI,
                    new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + " = " + contactId, null, null);
            if (!c.moveToFirst()) {
                this.callbackContext.error("Error occured while retrieving contact raw id");
                return;
            }
            String id = c.getString(c.getColumnIndex(RawContacts._ID));
            c.close();
            this.contactAccessor = new ContactAccessorSdk5(this.cordova);
            JSONObject contact = contactAccessor.getContactById(id);

            String returnText = "{\"contact\": {\"contactData\": \"" + contact.toString() + "\",\"vCard\": \""
                    + vCard + "\"}}";
            System.out.println("returnText :" + returnText);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, returnText);
            pluginResult.setKeepCallback(true);
            this.callbackContext.sendPluginResult(pluginResult);

            // readVCard(vCard);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:org.apache.cordova.plugin.ExportVCFsToFilePlugin.java

private String getVcardString(String fileName, String fileExtension) throws IOException {
    contactsSet = new HashSet<String>();
    cursor = this.cordova.getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
            null, null, null);// ww w.  j  av  a2s.  c o m
    if (cursor != null && cursor.getCount() > 0) {
        int i;
        File outputDir = this.cordova.getActivity().getCacheDir();
        String fullFilePath = outputDir.getAbsolutePath() + "/" + fileName + "." + fileExtension;
        FileOutputStream mFileOutputStream = new FileOutputStream(fullFilePath, false);

        cursor.moveToFirst();

        for (i = 0; i < cursor.getCount(); i++) {
            Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI,
                    cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)));
            AssetFileDescriptor fd;
            try {
                fd = this.cordova.getActivity().getContentResolver().openAssetFileDescriptor(uri, "r");
                FileInputStream fis = fd.createInputStream();
                byte[] buf = new byte[(int) fd.getDeclaredLength()];
                fis.read(buf);
                contactsSet.add(new String(buf));
            } catch (Exception e1) {
            }
            cursor.moveToNext();
        }
        Iterator it = contactsSet.iterator();
        while (it.hasNext()) {
            try {
                mFileOutputStream.write(it.next().toString().getBytes());
            } catch (IOException e) {
            }
        }
        mFileOutputStream.close();
        cursor.close();
        return fullFilePath;
    } else {
        Log.d("TAG", "No Contacts in Your Phone");
        return "";
    }
}

From source file:org.dmfs.webcal.utils.ImageProxy.java

/**
 * Return the image with then given id. If the icon is not present in the memory or filesystem cache this method returns <code>null</code>. The caller is
 * notified via the given {@link ImageAvailableListener} when the image has been loaded.
 * /*  w ww . ja  v a  2s. c  o  m*/
 * @param iconId
 *            The id of the icon to load.
 * @param callback
 *            The {@link ImageAvailableListener} to notify when the icon has been loaded.
 * @return A {@link Drawable} or null of the icon is loaded asynchronously or the id is invalid.
 */
public Drawable getImage(long iconId, ImageAvailableListener callback) {
    if (iconId == -1) {
        return null;
    }

    Drawable iconDrawable = mImageCache.get(iconId);
    if (iconDrawable == null) {
        try {
            AssetFileDescriptor afd = CalendarContentContract.Icon.getIcon(mAppContext, iconId, false);
            FileInputStream inputStream = afd.createInputStream();
            iconDrawable = Drawable.createFromStream(inputStream, null);
            if (iconDrawable != null) {
                mImageCache.put(iconId, iconDrawable);
            }
        } catch (FileNotFoundException e) {
            registerImageRequest(iconId, callback);
        } catch (IOException e) {
            registerImageRequest(iconId, callback);
        }
    }
    return iconDrawable;
}

From source file:eu.sathra.io.IO.java

public <T> T load(AssetFileDescriptor afd, Class<T> clazz) throws Exception {

    BufferedReader reader = new BufferedReader(new InputStreamReader(afd.createInputStream(), "UTF-8"));

    // do reading, usually loop until end of file reading
    String line;/*from  ww  w. j  a  v  a2 s  .c o m*/
    StringBuilder myBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        myBuilder.append(line);
    }

    reader.close();
    afd.close();

    return load(myBuilder.toString(), clazz);
}