Example usage for android.content.res AssetManager open

List of usage examples for android.content.res AssetManager open

Introduction

In this page you can find the example usage for android.content.res AssetManager open.

Prototype

public @NonNull InputStream open(@NonNull String fileName) throws IOException 

Source Link

Document

Open an asset using ACCESS_STREAMING mode.

Usage

From source file:com.bazaarvoice.test.SubmissionTests.PhotoSubmissionTest.java

public void testPhotoSubmit5() {

    OnBazaarResponseHelper bazaarResponse = new OnBazaarResponseHelper() {
        @Override// ww  w . jav a2s.  c  o m
        public void onResponseHelper(JSONObject response) throws JSONException {
            Log.e(tag, "End of photo submit transmission : END " + System.currentTimeMillis());

            Log.i(tag, "Response = \n" + response);
            assertFalse("The test returned errors! ", response.getBoolean("HasErrors"));
            assertNotNull(response.getJSONObject("Photo"));
        }
    };

    SubmissionMediaParams mediaParams = new SubmissionMediaParams(MediaParamsContentType.REVIEW_COMMENT);
    mediaParams.setUserId(
            "735688f97b74996e214f5df79bff9e8b7573657269643d393274796630666f793026646174653d3230313130353234");

    AssetManager assets = this.mContext.getAssets();

    InputStream in = null;

    try {
        in = assets.open("RalphRocks.jpg");
        Bitmap bmp = BitmapFactory.decodeStream(in);

        mediaParams.setPhoto(bmp, "RalphRocks.jpg");

        in.close();
        in = null;
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.e(tag, "Begin of photo submit transmission : BEGIN " + System.currentTimeMillis());
    submitMedia.postSubmission(RequestType.PHOTOS, mediaParams, bazaarResponse);
    bazaarResponse.waitForTestToFinish();
}

From source file:com.luongbui.andersenfestival.muzei.AndersenFestivalSource.java

/**
 * Copy the file using the asset manager.<br>
 * //w ww .j  a va2s  .co m
 * @param assetManager
 * @param fileName Relative to assets folder.
 * @throws IOException
 */
protected void copyFileToDataDir(android.content.res.AssetManager assetManager, String fileName)
        throws IOException {
    // Open the asset file.
    InputStream in = assetManager.open(fileName);
    // Open the target file.
    File outFile = new File(getApplicationContext().getFilesDir(), fileName);
    OutputStream out = new FileOutputStream(outFile);
    // Actual copy.
    streamCopy(in, out);
    // Close everything.
    in.close();
    in = null;
    out.flush();
    out.close();
    out = null;
}

From source file:com.sogrey.sinaweibo.utils.FileUtil.java

/**
 * ???Asset?./* w  ww. j a  v  a 2  s  .c o m*/
 * 
 * @param context
 *            the context
 * @param fileName
 *            the file name
 * @return Bitmap 
 */
public static Bitmap getBitmapFromAsset(Context context, String fileName) {
    Bitmap bit = null;
    try {
        AssetManager assetManager = context.getAssets();
        InputStream is = assetManager.open(fileName);
        bit = BitmapFactory.decodeStream(is);
    } catch (Exception e) {
        LogUtil.d(FileUtil.class, "?" + e.getMessage());
    }
    return bit;
}

From source file:com.sogrey.sinaweibo.utils.FileUtil.java

/**
 * ???Asset?./*  w  w  w  .j  a  v a  2  s  .co m*/
 * 
 * @param context
 *            the context
 * @param fileName
 *            the file name
 * @return Drawable 
 */
public static Drawable getDrawableFromAsset(Context context, String fileName) {
    Drawable drawable = null;
    try {
        AssetManager assetManager = context.getAssets();
        InputStream is = assetManager.open(fileName);
        drawable = Drawable.createFromStream(is, null);
    } catch (Exception e) {
        LogUtil.d(FileUtil.class, "?" + e.getMessage());
    }
    return drawable;
}

From source file:com.ecml.FileUri.java

/** Return the file contents as a byte array.
 *  If any IO error occurs, return null.
 *///from  w w  w  .  j a  v  a2s  . co  m
public byte[] getData(Activity activity) {
    try {
        byte[] data;
        int totallen, len, offset;

        // First, determine the file length
        data = new byte[4096];
        InputStream file;
        String uriString = uri.toString();
        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        totallen = 0;
        len = file.read(data, 0, 4096);
        while (len > 0) {
            totallen += len;
            len = file.read(data, 0, 4096);
        }
        file.close();

        // Now read in the data
        offset = 0;
        data = new byte[totallen];

        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        while (offset < totallen) {
            len = file.read(data, offset, totallen - offset);
            if (len <= 0) {
                throw new MidiFileException("Error reading midi file", offset);
            }
            offset += len;
        }
        return data;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.mobiquitynetworks.cordova.mnnotifications.NotificationsManager.java

Properties readSDKProperties(Context ctx) {
    Properties properties = new Properties();
    AssetManager assetManager = ctx.getAssets();
    if (assetManager == null)
        return properties;

    try {//from   ww  w  .  j a va2s .c om
        InputStream is = assetManager.open("properties/mobiquity.properties");
        properties.load(is);
        return properties;
    } catch (IOException ioe) { //Empty properties
        return properties;
    }
}

From source file:Main.java

private static void copyAsset(AssetManager am, File rep, boolean force) {
    try {/* ww  w  .  j a  v a  2  s.  c  o  m*/
        String assets[] = am.list("");
        for (int i = 0; i < assets.length; i++) {
            boolean hp48 = assets[i].equals("hp48");
            boolean hp48s = assets[i].equals("hp48s");
            boolean ram = assets[i].equals("ram");
            boolean rom = assets[i].equals("rom");
            boolean rams = assets[i].equals("rams");
            boolean roms = assets[i].equals("roms");
            int required = 0;
            if (ram)
                required = 131072;
            else if (rams)
                required = 32768;
            else if (rom)
                required = 524288;
            else if (roms)
                required = 262144;
            //boolean SKUNK = assets[i].equals("SKUNK");
            if (hp48 || rom || ram || hp48s || roms || rams) {
                File fout = new File(rep, assets[i]);
                if (!fout.exists() || fout.length() == 0 || (required > 0 && fout.length() != required)
                        || force) {
                    Log.i("x48", "Overwriting " + assets[i]);
                    FileOutputStream out = new FileOutputStream(fout);
                    InputStream in = am.open(assets[i]);
                    byte buffer[] = new byte[8192];
                    int n = -1;
                    while ((n = in.read(buffer)) > -1) {
                        out.write(buffer, 0, n);
                    }
                    out.close();
                    in.close();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.alfresco.mobile.android.application.fragments.create.DocumentPropertiesDialogFragment.java

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AnalyticsHelper.reportScreen(getActivity(), AnalyticsManager.SCREEN_NODE_CREATE_FORM);

    final String fragmentTag = (String) getArguments().get(ARGUMENT_FRAGMENT_TAG);
    final AlfrescoAccount currentAccount = (AlfrescoAccount) getArguments().get(ARGUMENT_ACCOUNT);
    final DocumentTypeRecord documentType = (DocumentTypeRecord) getArguments().get(ARGUMENT_DOCUMENT_TYPE);
    final ResolveInfo editor = (ResolveInfo) getArguments().get(ARGUMENT_EDITOR);

    File f = null;// w  ww  .jav  a2s.c  o m
    if (FileExplorerFragment.TAG.equals(fragmentTag)) {
        // If creation inside the download area, we store it inside
        // download.
        f = AlfrescoStorageManager.getInstance(getActivity()).getDownloadFolder(currentAccount);
    } else {
        // If creation inside a repository folder, we store temporarly
        // inside the capture.
        f = AlfrescoStorageManager.getInstance(getActivity()).getCaptureFolder(currentAccount);
    }

    final File folderStorage = f;

    LayoutInflater inflater = LayoutInflater.from(getActivity());
    final View v = inflater.inflate(R.layout.app_create_document, (ViewGroup) this.getView());

    ((TextView) v.findViewById(R.id.document_extension)).setText(documentType.extension);

    final MaterialEditText textName = ((MaterialEditText) v.findViewById(R.id.document_name));
    // This Listener is responsible to enable or not the validate button and
    // error message.
    textName.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            if (s.length() > 0) {
                textName.setFloatingLabelText(getString(R.string.content_name));
                ((MaterialDialog) getDialog()).getActionButton(DialogAction.POSITIVE).setEnabled(true);
                if (UIUtils.hasInvalidName(s.toString().trim())) {
                    textName.setError(getString(R.string.filename_error_character));
                    ((MaterialDialog) getDialog()).getActionButton(DialogAction.POSITIVE).setEnabled(false);
                } else {
                    textName.setError(null);
                }
            } else {
                textName.setHint(R.string.create_document_name_hint);
                ((MaterialDialog) getDialog()).getActionButton(DialogAction.POSITIVE).setEnabled(false);
                textName.setError(null);
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    MaterialDialog dialog = new MaterialDialog.Builder(getActivity()).iconRes(R.drawable.ic_application_logo)
            .title(R.string.create_document_title).customView(v, true).positiveText(R.string.create)
            .negativeText(R.string.cancel).callback(new MaterialDialog.ButtonCallback() {
                @Override
                public void onNegative(MaterialDialog dialog) {
                    dialog.dismiss();
                }

                @Override
                public void onPositive(MaterialDialog dialog) {
                    String fileName = textName.getText().toString().trim().concat(documentType.extension);

                    File newFile = new File(folderStorage, fileName);

                    if (newFile.exists() && FileExplorerFragment.TAG.equals(fragmentTag)) {
                        // If the file already exist, we prompt a warning
                        // message.
                        textName.setError(getString(R.string.create_document_filename_error));
                        return;
                    } else {
                        try {
                            // If there's a template we create the file
                            // based on
                            // this template.
                            if (documentType.templatePath != null) {
                                AssetManager assetManager = getActivity().getAssets();
                                IOUtils.copyFile(assetManager.open(documentType.templatePath), newFile);
                            } else {
                                newFile.createNewFile();
                            }
                        } catch (IOException e1) {
                            Log.e(TAG, Log.getStackTraceString(e1));
                        }
                    }

                    // We create the Intent based on informations we grab
                    // previously.
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    Uri data = Uri.fromFile(newFile);
                    intent.setDataAndType(data, documentType.mimetype);
                    intent.setComponent(new ComponentName(editor.activityInfo.applicationInfo.packageName,
                            editor.activityInfo.name));

                    try {
                        Fragment fr = getFragmentManager().findFragmentByTag(fragmentTag);
                        if (fr != null && fr.isVisible()) {
                            if (fr instanceof DocumentFolderBrowserFragment) {
                                // During Creation on a specific folder.
                                ((DocumentFolderBrowserFragment) fr).setCreateFile(newFile);
                            } else if (fr instanceof FileExplorerFragment) {
                                // During Creation inside the download
                                // folder.
                                ((FileExplorerFragment) fr).setCreateFile(newFile);
                            }
                            fr.startActivity(intent);
                        }
                    } catch (ActivityNotFoundException e) {
                        AlfrescoNotificationManager.getInstance(getActivity())
                                .showToast(R.string.error_unable_open_file);
                    }
                    dismiss();
                }
            }).build();

    dialog.getActionButton(DialogAction.POSITIVE).setEnabled(false);

    return dialog;
}

From source file:Main.java

public static void copyFolder(AssetManager assetManager, String source, String target) {
    // "Name" is the name of your folder!
    String[] files = null;// ww  w .jav a2  s  .c o  m

    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        // Checking file on assets subfolder
        try {
            files = assetManager.list(source);
        } catch (IOException e) {
            Log.e("ERROR", "Failed to get asset file list.", e);
        }
        // Analyzing all file on assets subfolder
        for (String filename : files) {
            InputStream in = null;
            OutputStream out = null;
            // First: checking if there is already a target folder
            File folder = new File(target);
            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }
            if (success) {
                // Moving all the files on external SD
                String sourceFile = source + "/" + filename;
                String targetFile = folder.getAbsolutePath() + "/" + filename;
                try {
                    in = assetManager.open(sourceFile);
                    out = new FileOutputStream(targetFile);
                    /*Log.i("WEBVIEW",
                      Environment.getExternalStorageDirectory()
                            + "/yourTargetFolder/" + name + "/"
                            + filename);*/
                    copyFile(in, out);
                    in.close();
                    in = null;
                    out.flush();
                    out.close();
                    out = null;
                } catch (IOException e) {
                    try {
                        assetManager.list(sourceFile);
                    } catch (IOException f) {
                        Log.e("ERROR", "Failed to copy asset file: " + filename, f);
                        continue;
                    }

                    copyFolder(assetManager, sourceFile, targetFile);
                }
            } else {
                // Do something else on failure
            }
        }
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
    } else {
        // Something else is wrong. It may be one of many other states, but
        // all we need
        // is to know is we can neither read nor write
    }
}

From source file:in.co.praveenkumar.tumtumtracker.LeftNavigationFragment.java

void InitRoutesIfRequired() {
    List<TTTRoute> routes = TTTRoute.listAll(TTTRoute.class);
    if (routes.size() != 0)
        return;/*  w ww  .  j  a va  2 s  .c  o m*/

    AssetManager assetManager = context.getAssets();
    try {
        InputStreamReader reader = new InputStreamReader(assetManager.open("routes.json"));
        GsonExclude ex = new GsonExclude();
        Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(ex)
                .addSerializationExclusionStrategy(ex).create();
        TTTRouteResponse response = gson.fromJson(reader, TTTRouteResponse.class);
        reader.close();

        routes = response.getRoutes();
    } catch (Exception e) {
        e.printStackTrace();
    }

    for (int i = 0; i < routes.size(); i++)
        routes.get(i).save();
}