Java Code Examples for android.content.res.AssetManager#open()

The following examples show how to use android.content.res.AssetManager#open() . 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: MonsterSummaryFragment.java    From MonsterHunter4UDatabase with MIT License 6 votes vote down vote up
private void updateUI() {

		LayoutInflater inflater = getLayoutInflater(mBundle);

		// Header
		String cellText = mMonster.getName();
		String cellImage = "icons_monster/" + mMonster.getFileLocation();

		mMonsterLabelTextView.setText(cellText);
        AssetManager manager = getActivity().getAssets();
        try {
            InputStream open = manager.open(cellImage);
            Bitmap bitmap = BitmapFactory.decodeStream(open);
            // Assign the bitmap to an ImageView in this layout
            mMonsterIconImageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }

		updateWeaknessUI();

	}
 
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: FacebookActivityTestCase.java    From FacebookImageShareIntent with MIT License 6 votes vote down vote up
protected File createTempFileFromAsset(String assetPath) throws IOException {
    InputStream inputStream = null;
    FileOutputStream outStream = null;

    try {
        AssetManager assets = getActivity().getResources().getAssets();
        inputStream = assets.open(assetPath);

        File outputDir = getActivity().getCacheDir(); // context being the Activity pointer
        File outputFile = File.createTempFile("prefix", assetPath, outputDir);
        outStream = new FileOutputStream(outputFile);

        final int bufferSize = 1024 * 2;
        byte[] buffer = new byte[bufferSize];
        int n = 0;
        while ((n = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, n);
        }

        return outputFile;
    } finally {
        Utility.closeQuietly(outStream);
        Utility.closeQuietly(inputStream);
    }
}
 
Example 4
Source File: CoreSDKVersionTest.java    From mapbox-events-android with MIT License 6 votes vote down vote up
@Test
public void testPersistedCoreSDKInfo() {
  Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
  AssetManager assetManager = context.getAssets();
  InputStream inputStream = null;

  try {
    String packageName = context.getPackageName().replace(".test", "");
    inputStream = assetManager.open(SDK_VERSIONS_FOLDER + File.separator + packageName);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    Assert.assertEquals(reader.readLine().split("/")[1], BuildConfig.VERSION_NAME);
    Assert.assertEquals(reader.readLine(), String.format(SECOND_LINE_FORMAT, BuildConfig.VERSION_CODE));
  } catch (IOException exception) {
    Log.e(LOG_TAG, exception.toString());
    fail(exception.toString());
  } finally {
    FileUtils.closeQuietly(inputStream);
  }
}
 
Example 5
Source File: KcaUtils.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
public static JsonObject getJsonObjectFromAsset(Context context, String name, KcaDBHelper helper) {
    ContextWrapper cw = new ContextWrapper(context);
    JsonObject data = null;
    AssetManager am = cw.getAssets();
    try {
        AssetManager.AssetInputStream ais =
                (AssetManager.AssetInputStream) am.open(name);
        byte[] bytes = ByteStreams.toByteArray(ais);
        data = new JsonParser().parse(new String(bytes)).getAsJsonObject();
        ais.close();
    } catch (IOException e1) {
        e1.printStackTrace();
        if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, name, "getJsonObjectFromStorage", "1", getStringFromException(e1));
    }
    return data;
}
 
Example 6
Source File: AFCertificateUtil.java    From AFBaseLibrary with Apache License 2.0 6 votes vote down vote up
private static InputStream[] getCertificatesByAssert(Context context, String... certificateNames) {
    if (context == null) {
        Logger.d("context is empty");
        return null;
    }
    if (certificateNames == null) {
        Logger.d("certificate is empty");
        return null;
    }

    AssetManager assets = context.getAssets();
    InputStream[] certificates = new InputStream[certificateNames.length];
    for (int i = 0; i < certificateNames.length; i++) {
        String certificateName = certificateNames[i];
        try {
            certificates[i] = assets.open(certificateName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return certificates;
}
 
Example 7
Source File: KcaUtils.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
public static JsonArray getJsonArrayFromAsset(Context context, String name, KcaDBHelper helper) {
    ContextWrapper cw = new ContextWrapper(context);
    JsonArray data = new JsonArray();
    AssetManager am = cw.getAssets();
    try {
        AssetManager.AssetInputStream ais =
                (AssetManager.AssetInputStream) am.open(name);
        byte[] bytes = ByteStreams.toByteArray(ais);
        data = new JsonParser().parse(new String(bytes)).getAsJsonArray();
        ais.close();
    } catch (IOException e1) {
        e1.printStackTrace();
        if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, name, "getJsonArrayFromStorage", "1", getStringFromException(e1));
    }
    return data;
}
 
Example 8
Source File: LabelUtils.java    From rscnn with MIT License 6 votes vote down vote up
public static String[] loadLabels(AssetManager assetManager, String file){
    try {
        String[] labels;
        InputStream labelFile = assetManager.open(file);
        byte[] buffer = new byte[labelFile.available()];
        labelFile.read(buffer);
        labelFile.close();
        String labelString = new String(buffer);
        labels = labelString.split("\n");
        for(int i=0;i<labels.length;i++){
            labels[i] = labels[i].split(",")[0].trim();
        }
        return labels;
    } catch (IOException e) {
        LogUtil.e(TAG, "load label error:" + e.getMessage());
        LogUtil.e(TAG, "use default voc 20 class label");
        e.printStackTrace();
    }
    return null;
}
 
Example 9
Source File: FileManager.java    From jxcore-android-basics with MIT License 6 votes vote down vote up
public static String readFile(String location, String encoding) {
    StringBuilder sb = new StringBuilder();
    try {
        AssetManager asm = AppManager.currentContext.getAssets();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                asm.open(location), encoding));

        String str = br.readLine();
        while (str != null) {
            sb.append(str + "\n");
            str = br.readLine();
        }

        br.close();
    } catch (IOException e) {
        Log.w("jxcore-FileManager", "readfile failed");
        e.printStackTrace();
        return null;
    }

    return sb.toString();
}
 
Example 10
Source File: ExampleInstrumentedTest.java    From XmlToJson with Apache License 2.0 6 votes vote down vote up
@Test
public void skipAttributeTest() throws Exception {
    Context context = InstrumentationRegistry.getTargetContext();
    AssetManager assetManager = context.getAssets();
    InputStream inputStream = assetManager.open("common.xml");

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

    inputStream.close();

    JSONObject result = xmlToJson.toJson();
    assertTrue(result.has("library"));
    JSONObject library = result.getJSONObject("library");
    assertTrue(library.has("book"));
    JSONArray books = library.getJSONArray("book");
    int size = books.length();
    assertTrue(size == 2);
    for (int i = 0; i < size; ++i) {
        JSONObject book = books.getJSONObject(i);
        assertFalse(book.has("id"));
    }

}
 
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: ClassAttrProvider.java    From android-yolo-v2 with Do What The F*ck You Want To Public License 5 votes vote down vote up
private void init(final AssetManager assetManager) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(assetManager.open(Config.LABEL_FILE)))) {
        String line;
        while ((line = br.readLine()) != null) {
            labels.add(line);
            colors.add(convertClassNameToColor(line));
        }
    } catch (IOException ex) {
        throw new RuntimeException("Problem reading label file!", ex);
    }
}
 
Example 13
Source File: ReminderNlu.java    From EasyNLU with Apache License 2.0 5 votes vote down vote up
private Map<String, Float> loadWeights(AssetManager assets){
    Map<String, Float> weights = Collections.emptyMap();

    try {
        Reader reader = new InputStreamReader(assets.open(WEIGHTS_FILE));
        weights = Weights.fromText(reader);
        reader.close();

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

    return weights;
}
 
Example 14
Source File: WordSelectionActivity.java    From jterm-cswithandroid with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_word_selection);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    AssetManager assetManager = getAssets();
    try {
        InputStream inputStream = assetManager.open("words.txt");
        dictionary = new PathDictionary(inputStream);
    } catch (IOException e) {
        Toast toast = Toast.makeText(this, "Could not load dictionary", Toast.LENGTH_LONG);
        toast.show();
    }
}
 
Example 15
Source File: StringUtils.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 5 votes vote down vote up
public static String getStringFromAssets(String path) {
    AssetManager assetManager = ContextUtils.getContext().getAssets();
    try (InputStream is = assetManager.open(path)) {
        int length = is.available();
        byte[] buffer = new byte[length];
        is.read(buffer);
        return new String(buffer, StandardCharsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 16
Source File: OpenGlUtils.java    From TikTok with Apache License 2.0 5 votes vote down vote up
public static Bitmap getImageFromAssetsFile(Context context, String fileName){
	Bitmap image = null;
    AssetManager am = context.getResources().getAssets();
    try{  
		InputStream is = am.open(fileName);
		image = BitmapFactory.decodeStream(is);
		is.close();
         	}catch (IOException e){
          e.printStackTrace();  
      }  	  
      return image;  	  
}
 
Example 17
Source File: TFLiteObjectDetectionAPIModel.java    From FimiX8-RE with MIT License 5 votes vote down vote up
public static Classifier create(AssetManager assetManager, String modelFilename, String labelFilename, int inputSize, boolean isQuantized) throws IOException {
    TFLiteObjectDetectionAPIModel d = new TFLiteObjectDetectionAPIModel();
    BufferedReader br = new BufferedReader(new InputStreamReader(assetManager.open(labelFilename.split("file:///android_asset/")[1])));
    while (true) {
        String line = br.readLine();
        if (line == null) {
            break;
        }
        d.labels.add(line);
    }
    br.close();
    d.inputSize = inputSize;
    try {
        int numBytesPerChannel;
        d.tfLite = new Interpreter(loadModelFile(assetManager, modelFilename));
        d.isModelQuantized = isQuantized;
        if (isQuantized) {
            numBytesPerChannel = 1;
        } else {
            numBytesPerChannel = 4;
        }
        d.imgData = ByteBuffer.allocateDirect((((d.inputSize * 1) * d.inputSize) * 3) * numBytesPerChannel);
        d.imgData.order(ByteOrder.nativeOrder());
        d.intValues = new int[(d.inputSize * d.inputSize)];
        d.tfLite.setNumThreads(6);
        d.outputLocations = (float[][][]) Array.newInstance(Float.TYPE, new int[]{1, 2, 4});
        d.outputClasses = (float[][]) Array.newInstance(Float.TYPE, new int[]{1, 2});
        d.outputScores = (float[][]) Array.newInstance(Float.TYPE, new int[]{1, 2});
        d.numDetections = new float[1];
        return d;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Source File: ResourceUtil.java    From AndroidBasicProject with MIT License 5 votes vote down vote up
/**
 * 描述:获取Asset中的图片资源.
 *
 * @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) {
        e.printStackTrace();
    }
    return drawable;
}
 
Example 19
Source File: MonsterDamageFragment.java    From MonsterHunter4UDatabase with MIT License 4 votes vote down vote up
private void updateUI() {
	String cellText = mMonster.getName();
	String cellImage = "icons_monster/" + mMonster.getFileLocation();
	
	mMonsterLabelTextView.setText(cellText);
       AssetManager manager = getActivity().getAssets();
       try {
           InputStream open = manager.open(cellImage);
           Bitmap bitmap = BitmapFactory.decodeStream(open);
           // Assign the bitmap to an ImageView in this layout
           mMonsterIconImageView.setImageBitmap(bitmap);
       } catch (IOException e) {
           e.printStackTrace();
       }
       
	// Draw Drawable
	mCutImageView.setImageResource(R.drawable.cut);
	mImpactImageView.setImageResource(R.drawable.impact);
	mShotImageView.setImageResource(R.drawable.shot);
	mKOImageView.setImageResource(R.drawable.stun);
	mFireImageView.setImageResource(R.drawable.fire);
	mWaterImageView.setImageResource(R.drawable.water);
	mIceImageView.setImageResource(R.drawable.ice);
	mThunderImageView.setImageResource(R.drawable.thunder);
	mDragonImageView.setImageResource(R.drawable.dragon);
	
	ArrayList<MonsterDamage> damages = 
			DataManager.get(getActivity()).queryMonsterDamageArray(mMonster.getId());

	MonsterDamage damage = null;
	String body_part, cut, impact, shot, ko, fire, water, ice, thunder, dragon;
	
	LayoutInflater inflater = getLayoutInflater(mBundle);

	// build each row of both tables per record
	for(int i = 0; i < damages.size(); i++) {
		LinearLayout wdRow = (LinearLayout) inflater.inflate(
				R.layout.fragment_monster_damage_listitem, mWeaponDamageTL, false);
		LinearLayout edRow = (LinearLayout) inflater.inflate(
				R.layout.fragment_monster_damage_listitem, mElementalDamageTL, false);
		  
		damage = damages.get(i);
		
		body_part = checkDamageValue(damage.getBodyPart());
		cut = checkDamageValue("" + damage.getCut());
		impact = checkDamageValue("" + damage.getImpact());
		shot = checkDamageValue("" + damage.getShot());
		ko = checkDamageValue("" + damage.getKo());
		fire = checkDamageValue("" + damage.getFire());
		water = checkDamageValue("" + damage.getWater());
		ice = checkDamageValue("" + damage.getIce());
		thunder = checkDamageValue("" + damage.getThunder());
		dragon = checkDamageValue("" + damage.getDragon());

		// Table 1
		TextView body_part_tv1 = (TextView) wdRow.findViewById(R.id.body_part);
		TextView dummy_tv = (TextView) wdRow.findViewById(R.id.dmg1);
		TextView cut_tv = (TextView) wdRow.findViewById(R.id.dmg2);
		TextView impact_tv = (TextView) wdRow.findViewById(R.id.dmg3);
		TextView shot_tv = (TextView) wdRow.findViewById(R.id.dmg4);
		TextView ko_tv = (TextView) wdRow.findViewById(R.id.dmg5);

		// Table 2
		TextView body_part_tv2 = (TextView) edRow.findViewById(R.id.body_part);
		TextView fire_tv = (TextView) edRow.findViewById(R.id.dmg1);
		TextView water_tv = (TextView) edRow.findViewById(R.id.dmg2);
		TextView ice_tv = (TextView) edRow.findViewById(R.id.dmg3);
		TextView thunder_tv = (TextView) edRow.findViewById(R.id.dmg4);
		TextView dragon_tv = (TextView) edRow.findViewById(R.id.dmg5);
		
		body_part_tv1.setText(body_part);
		body_part_tv2.setText(body_part);
		cut_tv.setText(cut);
		impact_tv.setText(impact);
		shot_tv.setText(shot);
		ko_tv.setText(ko);
		fire_tv.setText(fire);
		water_tv.setText(water);
		ice_tv.setText(ice);
		thunder_tv.setText(thunder);
		dragon_tv.setText(dragon);
		dummy_tv.setText("");

		mWeaponDamageTL.addView(wdRow);
		mElementalDamageTL.addView(edRow);
	}
}
 
Example 20
Source File: KcaUtils.java    From kcanotify_h5-master 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;
}