Java Code Examples for android.content.Context#getAssets()

The following examples show how to use android.content.Context#getAssets() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExampleInstrumentedTest.java    From XmlToJson with Apache License 2.0 6 votes vote down vote up
@Test
public void contentReplacementTest() throws Exception {

    Context context = InstrumentationRegistry.getTargetContext();
    AssetManager assetManager = context.getAssets();
    InputStream inputStream = assetManager.open("common.xml");

    XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null)
            .setContentName("/library/book", "contentReplacement")
            .build();

    inputStream.close();

    JSONObject result = xmlToJson.toJson();
    JSONObject library = result.getJSONObject("library");
    JSONArray books = library.getJSONArray("book");
    JSONObject book1 = books.getJSONObject(0);
    JSONObject book2 = books.getJSONObject(1);
    String content1 = book1.getString("contentReplacement");
    String content2 = book2.getString("contentReplacement");
    assertTrue(content1.equals("James Bond") || content1.equals("Book for the dummies"));
    assertTrue(content2.equals("James Bond") || content2.equals("Book for the dummies"));
}
 
Example 2
Source File: Utils.java    From Tutorials with Apache License 2.0 6 votes vote down vote up
private static String loadJSONFromAsset(Context context, String jsonFileName) {
    String json = null;
    InputStream is=null;
    try {
        AssetManager manager = context.getAssets();
        Log.d(TAG,"path "+jsonFileName);
        is = manager.open(jsonFileName);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}
 
Example 3
Source File: ResourceHelper.java    From MaterialDesignSupport with MIT License 6 votes vote down vote up
public static AssetFileDescriptor getAssetFileDescriptor(String assetName) {
    Context context = CoreMaterialApplication.getContext();
    if (context == null) {
        return null;
    }

    AssetManager assets = context.getAssets();
    if (assets == null) {
        return null;
    }

    try {
        return assets.openFd(assetName);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 4
Source File: JsonUtil.java    From Ticket-Analysis with MIT License 6 votes vote down vote up
/**
 * 从asset路径下读取对应文件转String输出
 * @param mContext
 * @return
 */
public static String getJson(Context mContext, String fileName) {
    // TODO Auto-generated method stub
    StringBuilder sb = new StringBuilder();
    AssetManager am = mContext.getAssets();
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                am.open(fileName)));
        String next = "";
        while (null != (next = br.readLine())) {
            sb.append(next);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        sb.delete(0, sb.length());
    }
    return sb.toString().trim();
}
 
Example 5
Source File: ExampleInstrumentedTest.java    From XmlToJson with Apache License 2.0 6 votes vote down vote up
@Test
public void skipTagTest() throws Exception {
    Context context = InstrumentationRegistry.getTargetContext();
    AssetManager assetManager = context.getAssets();
    InputStream inputStream = assetManager.open("common.xml");

    XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null)
            .skipTag("/library/owner")
            .build();

    inputStream.close();

    JSONObject result = xmlToJson.toJson();
    assertTrue(result.has("library"));
    JSONObject library = result.getJSONObject("library");
    assertTrue(library.has("book"));
    assertFalse(library.has("owner"));

}
 
Example 6
Source File: FileHelper.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 5 votes vote down vote up
public static @Nullable Bitmap getBitmapFromAsset(@NonNull Context context, String filePath) {
    AssetManager assetManager = context.getAssets();

    InputStream istr;
    Bitmap bitmap = null;
    try {
        istr = assetManager.open(filePath);
        bitmap = BitmapFactory.decodeStream(istr);
    } catch (IOException e) {
        Log.e(TAG, "getBitmapFromAsset: " + e);
    }

    return bitmap;
}
 
Example 7
Source File: InstallTask.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
InstallTask(final Context context,
            final String assetPath,
            final File directory,
            final Handler handler) {
    super(context, handler);
    mAssetManager = context.getAssets();
    mAssetPath = assetPath;
    mDirectory = directory;
}
 
Example 8
Source File: AssetUtil.java    From pandora with Apache License 2.0 5 votes vote down vote up
private static void copyFileOrDir(Context context, String path) {
    AssetManager assetManager = context.getAssets();
    String assets[];
    try {
        Log.i("tag", "copyFileOrDir() " + path);
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(context, path);
        } else {
            String fullPath = TARGET_BASE_PATH + path;
            Log.i("tag", "path=" + fullPath);
            File dir = new File(fullPath);
            if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                if (!dir.mkdirs())
                    Log.i("tag", "could not create dir " + fullPath);
            for (int i = 0; i < assets.length; ++i) {
                String p;
                if (path.equals(""))
                    p = "";
                else
                    p = path + "/";

                if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                    copyFileOrDir(context, p + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}
 
Example 9
Source File: LanguagesUtils.java    From MultiLanguages with Apache License 2.0 5 votes vote down vote up
/**
 * 获取某个语种下的 Resources 对象
 */
static Resources getLanguageResources(Context context, Locale locale) {
    Configuration config = new Configuration();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        config.setLocale(locale);
        return context.createConfigurationContext(config).getResources();
    } else {
        config.locale = locale;
        return new Resources(context.getAssets(), context.getResources().getDisplayMetrics(), config);
    }
}
 
Example 10
Source File: FileUtils.java    From android-mvp-interactor-architecture with Apache License 2.0 5 votes vote down vote up
public static String loadJSONFromAsset(Context context, String jsonFileName)
        throws IOException {

    AssetManager manager = context.getAssets();
    InputStream is = manager.open(jsonFileName);

    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();

    return new String(buffer, "UTF-8");
}
 
Example 11
Source File: Utils.java    From secure-quick-reliable-login with MIT License 5 votes vote down vote up
public static byte[] getAssetContent(Context context, String assetName) {
    AssetManager am = context.getAssets();

    try {
        InputStream is = am.open(assetName);
        return readFullInputStreamBytes(is);
    } catch (Exception e) {
        return null;
    }
}
 
Example 12
Source File: AndroidFFMPEGLocator.java    From cythara with GNU General Public License v3.0 5 votes vote down vote up
public AndroidFFMPEGLocator(Context context){
    CPUArchitecture architecture = getCPUArchitecture();

    Log.i(TAG,"Detected Native CPU Architecture: " + architecture.name());

    if(!ffmpegIsCorrectlyInstalled()){
        String ffmpegFileName = getFFMPEGFileName(architecture);
        AssetManager assetManager = context.getAssets();
        unpackFFmpeg(assetManager,ffmpegFileName);
    }
    File ffmpegTargetLocation = AndroidFFMPEGLocator.ffmpegTargetLocation();
    Log.i(TAG, "Ffmpeg binary location: " + ffmpegTargetLocation.getAbsolutePath() + " is executable? " + ffmpegTargetLocation.canExecute() + " size: " + ffmpegTargetLocation.length() + " bytes");
}
 
Example 13
Source File: AssetRequestHandler.java    From DoraemonKit with Apache License 2.0 4 votes vote down vote up
public AssetRequestHandler(Context context) {
  assetManager = context.getAssets();
}
 
Example 14
Source File: CalligraphyUtils.java    From UltimateAndroid with Apache License 2.0 4 votes vote down vote up
public static boolean applyFontToTextView(final Context context, final TextView textView, final String filePath) {
    if (textView == null || context == null) return false;
    final AssetManager assetManager = context.getAssets();
    final Typeface typeface = TypefaceUtils.load(assetManager, filePath);
    return applyFontToTextView(textView, typeface);
}
 
Example 15
Source File: CordovaResourceApi.java    From cordova-plugin-intent with MIT License 4 votes vote down vote up
public CordovaResourceApi(Context context, PluginManager pluginManager) {
    this.contentResolver = context.getContentResolver();
    this.assetManager = context.getAssets();
    this.pluginManager = pluginManager;
}
 
Example 16
Source File: CordovaResourceApi.java    From react-native-cordova with MIT License 4 votes vote down vote up
public CordovaResourceApi(Context context) {
    this.contentResolver = context.getContentResolver();
    this.assetManager = context.getAssets();
}
 
Example 17
Source File: OptionsManager.java    From Aria2App with GNU General Public License v3.0 4 votes vote down vote up
private OptionsManager(@NonNull Context context) {
    manager = context.getAssets();
}
 
Example 18
Source File: CustomTextView.java    From OpenEyes with Apache License 2.0 4 votes vote down vote up
/**
 * 设置字体
 * @param context
 */
private void init(Context context){
    AssetManager assets = context.getAssets();
    Typeface font = Typeface.createFromAsset(assets, "fonts/Lobster-1.4.otf");
    setTypeface(font);
}
 
Example 19
Source File: KcaUtils.java    From kcanotify with GNU General Public License v3.0 4 votes vote down vote up
public static String getRSAEncodedString(Context context, String value) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException {
    /*
    Example:
    try {
        JsonObject data = new JsonObject();
        data.addProperty("userid", 20181234);
        data.addProperty("data", "416D341GX141JI0318W");
        String encoded = KcaUtils.getRSAEncodedString(getApplicationContext(), data.toString());
        Log.e("KCA", encoded);
        data.remove("data");
        encoded = KcaUtils.getRSAEncodedString(getApplicationContext(), data.toString());
        Log.e("KCA", data.toString());
        Log.e("KCA", encoded);
    } catch (Exception e) {
        e.printStackTrace();
    }
    */

    List<String> value_list = new ArrayList<>();
    for (int i = 0; i < (int) Math.ceil(value.length() / 96.0); i++) {
        value_list.add(value.substring(i*96, Math.min((i+1)*96, value.length()) ));
    }

    AssetManager am = context.getAssets();
    AssetManager.AssetInputStream ais =
            (AssetManager.AssetInputStream) am.open("kcaqsync_pubkey.txt");
    byte[] bytes = ByteStreams.toByteArray(ais);
    String publicKeyContent = new String(bytes)
            .replaceAll("\\n", "")
            .replace("-----BEGIN PUBLIC KEY-----", "")
            .replace("-----END PUBLIC KEY-----", "").trim();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.decode(publicKeyContent, Base64.DEFAULT));
    Key encryptionKey = keyFactory.generatePublic(pubSpec);
    Cipher rsa = Cipher.getInstance("RSA/None/PKCS1Padding");
    rsa.init(Cipher.ENCRYPT_MODE, encryptionKey);

    byte[] data_all = {};
    for (String item : value_list) {
        byte[] item_byte = rsa.doFinal(item.getBytes("utf-8"));
        data_all = addAll(data_all, item_byte);
    }

    String result = Base64.encodeToString(rsa.doFinal(value.getBytes("utf-8")), Base64.DEFAULT).replace("\n", "");
    return result;
}
 
Example 20
Source File: ContextUtils.java    From cronet with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * In most cases, {@link Context#getAssets()} can be used directly. Modified resources are
 * used downstream and are set up on application startup, and this method provides access to
 * regular assets before that initialization is complete.
 *
 * This method should ONLY be used for accessing files within the assets folder.
 *
 * @return Application assets.
 */
public static AssetManager getApplicationAssets() {
    Context context = getApplicationContext();
    while (context instanceof ContextWrapper) {
        context = ((ContextWrapper) context).getBaseContext();
    }
    return context.getAssets();
}