Java Code Examples for android.content.res.AssetManager

The following are top voted examples for showing how to use android.content.res.AssetManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Sense-Hub-Android-Things   File: FileUtils.java   View source code 8 votes vote down vote up
public static InputStream readAssetsFileToStream(String fileName, Context context) {
    AssetManager assManager = context.getAssets();
    InputStream is = null;
    try {
        is = assManager.open(fileName);
    } catch (Exception e) {
        e.getMessage();
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (Exception e2) {
            e2.getMessage();
        }
    }
    InputStream isOutput = new BufferedInputStream(is);
    return isOutput;
}
 
Example 2
Project: LiuAGeAndroid   File: StreamUtils.java   View source code 8 votes vote down vote up
/**
 * 读取Assets下的文本文件
 *
 * @param context  上下文
 * @param fileName 文件名
 * @return 读取到的字符串
 */
public static String readAssetsFile(Context context, String fileName) {

    StringBuilder stringBuffer = new StringBuilder();
    AssetManager assetManager = context.getAssets();
    try {
        InputStream is = assetManager.open(fileName);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String str = null;
        while ((str = br.readLine()) != null) {
            stringBuffer.append(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stringBuffer.toString();
}
 
Example 3
Project: LaunchEnr   File: IconThemer.java   View source code 7 votes vote down vote up
private Drawable getRoundIcon(Context context,String packageName, int iconDpi) {

        mPackageManager = context.getPackageManager();

        try {
            Resources resourcesForApplication = mPackageManager.getResourcesForApplication(packageName);
            AssetManager assets = resourcesForApplication.getAssets();
            XmlResourceParser parseXml = assets.openXmlResourceParser("AndroidManifest.xml");
            int eventType;
            while ((eventType = parseXml.nextToken()) != XmlPullParser.END_DOCUMENT)
                if (eventType == XmlPullParser.START_TAG && parseXml.getName().equals("application"))
                    for (int i = 0; i < parseXml.getAttributeCount(); i++)
                        if (parseXml.getAttributeName(i).equals("roundIcon"))
                            return resourcesForApplication.getDrawableForDensity(Integer.parseInt(parseXml.getAttributeValue(i).substring(1)), iconDpi, context.getTheme());
            parseXml.close();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
 
Example 4
Project: VirtualHook   File: AppAccountParser.java   View source code 6 votes vote down vote up
@Override
public Resources getResources(Context context, ApplicationInfo appInfo) throws Exception {
    InstalledAppInfo appSetting = VAppManagerService.get().getInstalledAppInfo(appInfo.packageName, 0);
    if (appSetting != null) {
        AssetManager assets = mirror.android.content.res.AssetManager.ctor.newInstance();
        mirror.android.content.res.AssetManager.addAssetPath.call(assets, appSetting.apkPath);
        Resources hostRes = context.getResources();
        return new Resources(assets, hostRes.getDisplayMetrics(), hostRes.getConfiguration());
    }
    return null;
}
 
Example 5
Project: ShangHanLun   File: UILabel.java   View source code 6 votes vote down vote up
@Override
public void setTypeface(Typeface tf, int style) {
    //super.setTypeface(tf, style);
    if (!isInEditMode()) {
        String customTypefacePath = REGULAR_FONT_PATH;
        if (style == Typeface.BOLD) {
            customTypefacePath = BOLD_FONT_PATH;
        }

        // load custom font if available on app bundle.
        if (assetExists(getContext(), customTypefacePath)) {
            AssetManager assets = getContext().getAssets();
            tf = Typeface.createFromAsset(assets, customTypefacePath);
        }

        super.setTypeface(tf, style);
    }
}
 
Example 6
Project: exciting-app   File: FileUtils_zm.java   View source code 6 votes vote down vote up
public boolean copyAssetDirToFiles(Context context, String dirname) {
    try {
        AssetManager assetManager = context.getAssets();
        String[] children = assetManager.list(dirname);
        for (String child : children) {
            child = dirname + '/' + child;
            String[] grandChildren = assetManager.list(child);
            if (0 == grandChildren.length)
                copyAssetFileToFiles(context, child);
            else
                copyAssetDirToFiles(context, child);
        }
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 7
Project: AOdia   File: AOdiaActivity.java   View source code 6 votes vote down vote up
/**
 * sample.oudをdataフォルダにコピーする
 */
private void createSample() {
    File file = new File(getExternalFilesDir(null), "sample.oud");
    if(file.exists()){
        //return;
    }
    try {
        AssetManager assetManager = getAssets();
        ;
        InputStream is = assetManager.open("sample.oud");

        OutputStream os = new FileOutputStream(file);
        byte[] data = new byte[is.available()];
        is.read(data);
        os.write(data);
        is.close();
        os.close();
    } catch (IOException e) {
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
}
 
Example 8
Project: phonk   File: FileIO.java   View source code 6 votes vote down vote up
public static boolean copyAssetFolder(AssetManager assetManager, String fromAssetPath, String toPath) {
    try {
        String[] files = assetManager.list(fromAssetPath);
        new File(toPath).mkdirs();
        boolean res = true;
        for (String file : files) {
            if (file.contains(".")) {
                res &= copyAsset(assetManager, fromAssetPath + "/" + file, toPath + "/" + file);
            } else {
                res &= copyAssetFolder(assetManager, fromAssetPath + "/" + file, toPath + "/" + file);
            }
        }
        return res;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 9
Project: Dynamic   File: MainActivity.java   View source code 6 votes vote down vote up
protected void loadResources() {
    try {
        AssetManager assetManager = AssetManager.class.newInstance();
        Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
        addAssetPath.invoke(assetManager, dexpath);
        mAssetManager = assetManager;
    } catch (Exception e) {
        e.printStackTrace();
    }
    Resources superRes = super.getResources();
    superRes.getDisplayMetrics();
    superRes.getConfiguration();
    mResources = new Resources(mAssetManager, superRes.getDisplayMetrics(),superRes.getConfiguration());
    mTheme = mResources.newTheme();
    mTheme.setTo(super.getTheme());
}
 
Example 10
Project: style-transfer   File: Convolution2D.java   View source code 6 votes vote down vote up
public void loadModel(String path) throws IOException {
    mInputStream = mContext.getAssets().open(path + "/W", AssetManager.ACCESS_BUFFER);
    ByteBuffer bb = readInput(mInputStream);
    FloatBuffer.wrap(W).put(bb.asFloatBuffer());

    // padding for GPU BLAS when necessary.
    int W_height_input = in_channels * ksize * ksize;
    if (padded_Y_blas == W_height_input) {
        // If the input width already satisfies the requirement, just copy to the Allocation.
        W_alloc.copyFrom(W);
    } else {
        // If not, a temp allocation needs to be created.
        Allocation input = Allocation.createTyped(mRS,
                Type.createXY(mRS, Element.F32(mRS), W_height_input, out_channels));
        input.copyFrom(W);
        W_alloc.copy2DRangeFrom(0, 0, W_height_input, out_channels, input, 0, 0);
    }

    mInputStream = mContext.getAssets().open(path + "/b", AssetManager.ACCESS_BUFFER);
    bb = readInput(mInputStream);
    FloatBuffer.wrap(b).put(bb.asFloatBuffer());
    b_alloc.copyFrom(b);

    mInputStream.close();
    Log.v(TAG, "Convolution2D loaded: " + b[0]);
}
 
Example 11
Project: javaide   File: AssetUtil.java   View source code 6 votes vote down vote up
public static boolean copyAssetFolder(AssetManager assetManager,
                                      String fromAssetPath, String toPath) {
    try {
        String[] files = assetManager.list(fromAssetPath);
        new File(toPath).mkdirs();
        boolean res = true;
        for (String file : files)
            if (file.contains(".")) {
                res &= copyAsset(assetManager,
                        fromAssetPath + "/" + file,
                        toPath + "/" + file);
            } else {
                res &= copyAssetFolder(assetManager,
                        fromAssetPath + "/" + file,
                        toPath + "/" + file);
            }
        return res;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 12
Project: RNLearn_Project1   File: ReactFontManager.java   View source code 6 votes vote down vote up
public
@Nullable Typeface getTypeface(
    String fontFamilyName,
    int style,
    AssetManager assetManager) {
  FontFamily fontFamily = mFontCache.get(fontFamilyName);
  if (fontFamily == null) {
    fontFamily = new FontFamily();
    mFontCache.put(fontFamilyName, fontFamily);
  }

  Typeface typeface = fontFamily.getTypeface(style);
  if (typeface == null) {
    typeface = createTypeface(fontFamilyName, style, assetManager);
    if (typeface != null) {
      fontFamily.setTypeface(style, typeface);
    }
  }

  return typeface;
}
 
Example 13
Project: OffIt   File: CallUtils.java   View source code 6 votes vote down vote up
public static String getJsonFromAssetsPath(AssetManager assetManager, String fileName) {
    String json;
    try {
        InputStream is = assetManager.open(fileName);

        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 14
Project: BilibiliClient   File: HomeRegionFragment.java   View source code 6 votes vote down vote up
private String readAssetJson() {
    AssetManager assetManager = getActivity().getAssets();
    try {
        InputStream in = assetManager.open("region.json");
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null){
            builder.append(line);
        }
        return builder.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 15
Project: GitHub   File: LocalAssetFetchProducerTest.java   View source code 6 votes vote down vote up
@Test
public void testFetchAssetResource() throws Exception {
  PooledByteBuffer pooledByteBuffer = mock(PooledByteBuffer.class);
  when(mAssetManager.open(eq(TEST_FILENAME), eq(AssetManager.ACCESS_STREAMING)))
      .thenReturn(new ByteArrayInputStream(new byte[TEST_DATA_LENGTH]));
  when(mPooledByteBufferFactory.newByteBuffer(any(InputStream.class), eq(TEST_DATA_LENGTH)))
      .thenReturn(pooledByteBuffer);

  mLocalAssetFetchProducer.produceResults(mConsumer, mProducerContext);
  mExecutor.runUntilIdle();

  assertEquals(
      2,
      mCapturedEncodedImage.getByteBufferRef()
          .getUnderlyingReferenceTestOnly().getRefCountTestOnly());
  assertSame(pooledByteBuffer, mCapturedEncodedImage.getByteBufferRef().get());
  verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
  verify(mProducerListener).onProducerFinishWithSuccess(mRequestId, PRODUCER_NAME, null);
  verify(mProducerListener).onUltimateProducerReached(mRequestId, PRODUCER_NAME, true);
}
 
Example 16
Project: BilibiliClient   File: HomeRegionFragment.java   View source code 6 votes vote down vote up
/**
 * 读取assets下的json数据
 */
private String readAssetsJson() {

  AssetManager assetManager = getActivity().getAssets();
  try {
    InputStream is = assetManager.open("region.json");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder stringBuilder = new StringBuilder();
    String str;
    while ((str = br.readLine()) != null) {
      stringBuilder.append(str);
    }
    return stringBuilder.toString();
  } catch (IOException e) {
    e.printStackTrace();
    return null;
  }
}
 
Example 17
Project: Phoenicia   File: SplashScene.java   View source code 6 votes vote down vote up
public SplashScene(TextureManager textureManager, AssetManager assetManager, VertexBufferObjectManager vbo, Camera camera) {
    super();
    this.setBackground(new Background(new Color(100, 100, 100)));
    try {
        splashTexture = new AssetBitmapTexture(textureManager, assetManager, "textures/splash.png", TextureOptions.BILINEAR);
        splashTextureRegion = TextureRegionFactory.extractFromTexture(splashTexture);
        splashTexture.load();
        splash = new Sprite(0, 0, splashTextureRegion, vbo);

        final float scale_factor = GameActivity.CAMERA_HEIGHT / splashTextureRegion.getHeight();
        splash.setScale(scale_factor+0.1f);
        splash.setPosition((camera.getWidth()) * 0.5f, (camera.getHeight()) * 0.5f);
        this.attachChild(splash);
    } catch (final IOException e) {
        System.err.println("Error loading splash!");
        e.printStackTrace(System.err);
    }
}
 
Example 18
Project: Android-Music-Player   File: songSliderThumb.java   View source code 6 votes vote down vote up
public Bitmap setImg(String str){
    if(str != null){
        AssetManager assetManager = getContext().getAssets();
        InputStream in;
        byte[] bt = null;
        try {
            in = assetManager.open("imgs/"+str);
            bt = new byte[in.available()];
            in.read(bt);
        } catch (IOException e) {
            e.printStackTrace();
        }
        notBitmap = true;
        Bitmap myBitmap = BitmapFactory.decodeByteArray(bt,0,bt.length);
        Iv.setImageBitmap(myBitmap);
        //Iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        return myBitmap;
    }else{
        Iv.setImageBitmap(null);
        return null;
    }
}
 
Example 19
Project: GenericModuleRouter   File: PicActivity.java   View source code 6 votes vote down vote up
private Bitmap getImageFromAssetsFile(String fileName)
{
    Bitmap image = null;
    AssetManager am = getResources().getAssets();
    try
    {
        InputStream is = am.open(fileName);
        image = BitmapFactory.decodeStream(is);
        is.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    return image;
}
 
Example 20
Project: IslamicLibraryAndroid   File: SplashActivity.java   View source code 6 votes vote down vote up
@Override
protected Boolean doInBackground(Void... voids) {
    SplashActivity activity = activityReference.get();
    StorageUtils.makeIslamicLibraryShamelaDirectory(activity);
    if (activity != null) {
        AssetManager assetManager = activity.getAssets();
        InputStream in;
        try {
            in = assetManager.open(DownloadFileConstants.COMPRESSED_ONLINE_DATABASE_NAME);
            if (!UnZipIntentService.unzip(in,
                    StorageUtils.getIslamicLibraryShamelaBooksDir(activity),
                    this::publishProgress)) {
                throw new IOException("unzip failed for main database");
            }
        } catch (IOException e) {
            Timber.e(e);
            return false;
        }
    }
    return true;
}
 
Example 21
Project: phonk   File: FileIO.java   View source code 6 votes vote down vote up
public static void copyFileOrDir(Context c, String path) {
    AssetManager assetManager = c.getAssets();
    String assets[] = null;
    try {
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(c, path);
        } else {
            String fullPath = AppRunnerSettings.getBaseDir() + path;
            File dir = new File(fullPath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            for (String asset : assets) {
                copyFileOrDir(c, path + "/" + asset);
            }
        }
    } catch (IOException ex) {
        Log.e(TAG, ex.toString());
    }
}
 
Example 22
Project: mobile-store   File: App.java   View source code 6 votes vote down vote up
/**
 * {@link PackageManager} doesn't give us {@code minSdkVersion}, {@code targetSdkVersion},
 * and {@code maxSdkVersion}, so we have to parse it straight from {@code <uses-sdk>} in
 * {@code AndroidManifest.xml}.  If {@code targetSdkVersion} is not set, then it is
 * equal to {@code minSdkVersion}
 *
 * @see <a href="https://developer.android.com/guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a>
 */
private static int[] getMinTargetMaxSdkVersions(Context context, String packageName) {
    int minSdkVersion = Apk.SDK_VERSION_MIN_VALUE;
    int targetSdkVersion = Apk.SDK_VERSION_MIN_VALUE;
    int maxSdkVersion = Apk.SDK_VERSION_MAX_VALUE;
    try {
        AssetManager am = context.createPackageContext(packageName, 0).getAssets();
        XmlResourceParser xml = am.openXmlResourceParser("AndroidManifest.xml");
        int eventType = xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG && "uses-sdk".equals(xml.getName())) {
                for (int j = 0; j < xml.getAttributeCount(); j++) {
                    if (xml.getAttributeName(j).equals("minSdkVersion")) {
                        minSdkVersion = Integer.parseInt(xml.getAttributeValue(j));
                    } else if (xml.getAttributeName(j).equals("targetSdkVersion")) {
                        targetSdkVersion = Integer.parseInt(xml.getAttributeValue(j));
                    } else if (xml.getAttributeName(j).equals("maxSdkVersion")) {
                        maxSdkVersion = Integer.parseInt(xml.getAttributeValue(j));
                    }
                }
                break;
            }
            eventType = xml.nextToken();
        }
    } catch (PackageManager.NameNotFoundException | IOException | XmlPullParserException e) {
        Log.e(TAG, "Could not get min/max sdk version", e);
    }
    if (targetSdkVersion < minSdkVersion) {
        targetSdkVersion = minSdkVersion;
    }
    return new int[]{minSdkVersion, targetSdkVersion, maxSdkVersion};
}
 
Example 23
Project: LiveNotes   File: SeeScoreView.java   View source code 6 votes vote down vote up
/**
    * construct the SeeScore scrollable View
    * @param context (usually the MainActivity)
    * @param am the asset manager for font handling
    * @param zn the zoom notification which is called on (pinch) zoom change
    * @param tn the tap notification which is called on a tap in the view with info about what was tapped
 *           if tn == null then taps will not be intercepted and pinch-zoom is enabled
 *           NB tn disables pinch-zoom
    */
public SeeScoreView(Activity context, AssetManager am, ZoomNotification zn, TapNotification tn) {
	super(context);
	setOrientation(VERTICAL);
	this.assetManager = am;
	this.magnification = 1.0F;
	this.zoomNotify = zn;
       this.tapNotify = tn;
	DisplayMetrics displayMetrics = new android.util.DisplayMetrics();
	Display display = context.getWindowManager().getDefaultDisplay();
	display.getMetrics(displayMetrics);
	displayDPI = displayMetrics.densityDpi;
	android.graphics.Point screenSize = new android.graphics.Point();
	display.getSize(screenSize);
	screenHeight = screenSize.y;
}
 
Example 24
Project: Blockly   File: BlocklyActivityHelper.java   View source code 6 votes vote down vote up
/**
 * Resets the {@link BlockFactory} with the provided block definitions and extensions.
 * @param blockDefinitionsJsonPaths The list of definition asset paths.
 * @throws IllegalStateException On any issues with the input.
 */
public void resetBlockFactory(
        @Nullable List<String> blockDefinitionsJsonPaths) {
    AssetManager assets = mActivity.getAssets();
    BlockFactory factory = mController.getBlockFactory();
    factory.clear();

    String assetPath = null;
    try {
        if (blockDefinitionsJsonPaths != null) {
            for (String path : blockDefinitionsJsonPaths) {
                assetPath = path;
                factory.addJsonDefinitions(assets.open(path));
            }
        }
    } catch (IOException | BlockLoadingException e) {
        throw new IllegalStateException(
                "Failed to load block definition asset file: " + assetPath, e);
    }
}
 
Example 25
Project: LuaViewPlayground   File: ScriptBundleUnpackDelegate.java   View source code 6 votes vote down vote up
/**
 * 将所有assert下面的脚本解压缩到文件系统
 *
 * @param assetFolderPath
 */
public static void unpackAllAssetScripts(final Context context, final String assetFolderPath) {
    if (context != null && assetFolderPath != null) {
        new SimpleTask1<Object>() {//起simple task 来解压包
            @Override
            protected Object doInBackground(Object[] params) {
                final AssetManager assetManager = context.getAssets();
                if (assetManager != null) {
                    try {
                        final String[] assetBundles = assetManager.list(assetFolderPath);//list 耗时
                        if (assetBundles != null) {
                            for (final String assetBundleFileName : assetBundles) {
                                if (LuaScriptManager.isLuaScriptZip(assetBundleFileName)) {//如果是luaview zip,则解包
                                    unpack(context, FileUtil.removePostfix(assetBundleFileName), assetFolderPath + File.separator + assetBundleFileName);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }
        }.executeInPool();
    }
}
 
Example 26
Project: LiveWallPaper   File: VideoLiveWallpaper.java   View source code 6 votes vote down vote up
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
    L.d("VideoEngine#onSurfaceCreated ");
    super.onSurfaceCreated(holder);
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setSurface(holder.getSurface());
    try {
        AssetManager assetMg = getApplicationContext().getAssets();
        AssetFileDescriptor fileDescriptor = assetMg.openFd("test1.mp4");
        mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                fileDescriptor.getStartOffset(), fileDescriptor.getLength());
        mMediaPlayer.setLooping(true);
        mMediaPlayer.setVolume(0, 0);
        mMediaPlayer.prepare();
        mMediaPlayer.start();

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

}
 
Example 27
Project: https-github.com-hyb1996-NoRootScriptDroid   File: SampleFileManager.java   View source code 5 votes vote down vote up
public List<SampleGroup> getSamplesFromAssets(AssetManager assets, String path) {
    List<SampleGroup> sampleGroups = new ArrayList<>();
    try {
        String[] groups = assets.list(path);
        for (String groupName : groups) {
            sampleGroups.add(getSampleGroupFromAssets(assets, groupName, path + "/" + groupName));
        }
        return sampleGroups;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 28
Project: Exoplayer2Radio   File: AssetDataSource.java   View source code 5 votes vote down vote up
@Override
public long open(DataSpec dataSpec) throws AssetDataSourceException {
  try {
    uri = dataSpec.uri;
    String path = uri.getPath();
    if (path.startsWith("/android_asset/")) {
      path = path.substring(15);
    } else if (path.startsWith("/")) {
      path = path.substring(1);
    }
    inputStream = assetManager.open(path, AssetManager.ACCESS_RANDOM);
    long skipped = inputStream.skip(dataSpec.position);
    if (skipped < dataSpec.position) {
      // assetManager.open() returns an AssetInputStream, whose skip() implementation only skips
      // fewer bytes than requested if the skip is beyond the end of the asset's data.
      throw new EOFException();
    }
    if (dataSpec.length != C.LENGTH_UNSET) {
      bytesRemaining = dataSpec.length;
    } else {
      bytesRemaining = inputStream.available();
      if (bytesRemaining == Integer.MAX_VALUE) {
        // assetManager.open() returns an AssetInputStream, whose available() implementation
        // returns Integer.MAX_VALUE if the remaining length is greater than (or equal to)
        // Integer.MAX_VALUE. We don't know the true length in this case, so treat as unbounded.
        bytesRemaining = C.LENGTH_UNSET;
      }
    }
  } catch (IOException e) {
    throw new AssetDataSourceException(e);
  }

  opened = true;
  if (listener != null) {
    listener.onTransferStart(this, dataSpec);
  }
  return bytesRemaining;
}
 
Example 29
Project: blastar   File: Level5.java   View source code 5 votes vote down vote up
public Level5(PlayScreen ps, MainActivity act){

        this.ps = ps;

        try {
            AssetManager assetManager = act.getAssets();
            InputStream inputStream = assetManager.open("maps/map5.jpg");
            map = BitmapFactory.decodeStream(inputStream);
            mapEdge = BitmapFactory.decodeStream(assetManager.open("maps/map5edges.png"));
            inputStream.close();

        }catch(Exception e){
            //dont care sorry
        }
    }
 
Example 30
Project: ClassLoader   File: MyApplication.java   View source code 5 votes vote down vote up
protected void loadResources() throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
    Log.d(TAG, "MyApplication : loadResources()");
    AssetManager am = (AssetManager) AssetManager.class.newInstance();
    am.getClass().getMethod("addAssetPath", String.class).invoke(am, dexPath);
    mAssetManager = am;
    Constructor<?> constructor_Resources = Resources.class.getConstructor(AssetManager.class, cc.getResources()
            .getDisplayMetrics().getClass(), cc.getResources().getConfiguration().getClass());
    mResources = (Resources) constructor_Resources.newInstance(am, cc.getResources().getDisplayMetrics(), cc.getResources().getConfiguration());
    mTheme = mResources.newTheme();
    mTheme.applyStyle(android.R.style.Theme_Light_NoTitleBar_Fullscreen, true);
}
 
Example 31
Project: SmartMath   File: MFPAdapter.java   View source code 5 votes vote down vote up
public static boolean copyAssetCharts2SD(AssetManager am, String strSrcPath, String strDestPath) {
    String strAssetFiles[] = null;
    boolean bReturnValue = true;
    try {
    	String strScriptExt = MFPFileManagerActivity.STRING_CHART_EXTENSION;
        if (strSrcPath.substring(strSrcPath.length() - strScriptExt.length())
        		.toLowerCase(Locale.US).equals(strScriptExt)
        	&& (strSrcPath.equals(STRING_ASSET_CHARTS_FOLDER
        						+ MFPFileManagerActivity.STRING_PATH_DIV
        						+ STRING_ASSET_CHART_EXAMPLE1_FILE)
        		|| strSrcPath.equals(STRING_ASSET_CHARTS_FOLDER
   						+ MFPFileManagerActivity.STRING_PATH_DIV
   						+ STRING_ASSET_CHART_EXAMPLE2_FILE))) {
        	// this is a chart.
            if (copyAssetFile2SD(am, strSrcPath, strDestPath) == false)	{
				return false;
			}
        } else if (strSrcPath.substring(strSrcPath.length() - STRING_ASSET_CHARTS_FOLDER_EXTENSION.length())
				.toLowerCase(Locale.US).equals(STRING_ASSET_CHARTS_FOLDER_EXTENSION))	{
            File dir = new File(strDestPath);
            if (!dir.exists())	{
                if (!dir.mkdirs())	{
                    return false;	// cannot create destination folder
				}
			}
	        strAssetFiles = am.list(strSrcPath);
            for (int i = 0; i < strAssetFiles.length; ++i) {
            	boolean bThisCpyReturn = copyAssetCharts2SD(am, strSrcPath + MFPFileManagerActivity.STRING_PATH_DIV + strAssetFiles[i],
							strDestPath + MFPFileManagerActivity.STRING_PATH_DIV + strAssetFiles[i]);
            	if (!bThisCpyReturn) {
            		bReturnValue = false;
            	}
            }
        }
    } catch (IOException ex) {
        return false;
    }
	return bReturnValue;
}
 
Example 32
Project: Phoenicia   File: TMXParser.java   View source code 5 votes vote down vote up
public TMXParser(final AssetManager pAssetManager, final TextureManager pTextureManager, final TextureOptions pTextureOptions, final VertexBufferObjectManager pVertexBufferObjectManager, final ITMXTilePropertiesListener pTMXTilePropertyListener, TMXTileSetSourceManager pTMXTileSetSourceManager, boolean pUseLowMemoryVBO, boolean pAllocateTiles) {
	this.mAssetManager = pAssetManager;
	this.mTextureManager = pTextureManager;
	this.mTextureOptions = pTextureOptions;
	this.mVertexBufferObjectManager = pVertexBufferObjectManager;
	this.mTMXTilePropertyListener = pTMXTilePropertyListener;
	this.mTMXTileSetSourceManager = pTMXTileSetSourceManager;
	this.mUseLowMemoryVBO = pUseLowMemoryVBO;
	this.mAllocateTiles = pAllocateTiles;
}
 
Example 33
Project: Watermark   File: Utils.java   View source code 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 34
Project: tuxguitar   File: TGResourceLoaderImpl.java   View source code 5 votes vote down vote up
public List<String> unpackPlugins(String path) {
	try {
		List<String> fileNames = new ArrayList<String>();
		
		AssetManager assetManager = this.activity.getAssets();
		String[] assets = assetManager.list(ASSET_PLUGINS);
		if( assets != null ) {
			for(String asset : assets) {
				File pluginFileName = new File(path, asset);
				
				InputStream inputStream = new BufferedInputStream(assetManager.open(ASSET_PLUGINS + File.separator + asset));
				OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pluginFileName));
				byte[] buffer = new byte[ASSET_BUFFER_SIZE];
				int length = 0;
				while((length = inputStream.read(buffer, 0, ASSET_BUFFER_SIZE)) > 0) {
					outputStream.write(buffer, 0, length);
				}
				outputStream.close();
				inputStream.close();
				
				fileNames.add(pluginFileName.getAbsolutePath());
			}
		}
		
		return fileNames;
	} catch (IOException e) {
		throw new TGResourceException(e);
	}
}
 
Example 35
Project: android-mvp-interactor-architecture   File: FileUtils.java   View source code 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 36
Project: boohee_v5.6   File: TinkerApplication.java   View source code 5 votes vote down vote up
protected TinkerApplication(int tinkerFlags, String delegateClassName, String
        loaderClassName, boolean tinkerLoadVerifyFlag) {
    this.delegate = null;
    this.resources = new Resources[1];
    this.classLoader = new ClassLoader[1];
    this.assetManager = new AssetManager[1];
    this.tinkerFlags = tinkerFlags;
    this.delegateClassName = delegateClassName;
    this.loaderClassName = loaderClassName;
    this.tinkerLoadVerifyFlag = tinkerLoadVerifyFlag;
}
 
Example 37
Project: GitHub   File: utils.java   View source code 5 votes vote down vote up
public static String getJson(Context context, String fileName) {
    StringBuilder stringBuilder = new StringBuilder();
    try {
        AssetManager assetManager = context.getAssets();
        BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
        String line;
        while ((line = bf.readLine()) != null) {
            stringBuilder.append(line);
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return stringBuilder.toString();
}
 
Example 38
Project: GitHub   File: CommonUtils.java   View source code 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 39
Project: microMathematics   File: SVG.java   View source code 5 votes vote down vote up
/**
 * Read and parse an SVG from the assets folder.
 * 
 * @param assetManager
 *            the AssetManager instance to use when reading the file.
 * @param filename
 *            the filename of the SVG document within assets.
 * @return an SVG instance on which you can call one of the render methods.
 * @throws SVGParseException
 *             if there is an error parsing the document.
 * @throws IOException
 *             if there is some IO error while reading the file.
 */
public static SVG getFromAsset(AssetManager assetManager, String filename)
		throws SVGParseException, IOException {
	SVGParser parser = new SVGParser();
	InputStream is = assetManager.open(filename);
	try {
		return parser.parse(is);
	} finally {
		try {
			is.close();
		} catch (IOException e) {
			// Do nothing
		}
	}
}
 
Example 40
Project: GitHub   File: ModelListActivity.java   View source code 5 votes vote down vote up
private InputStream getInputStream() throws IOException {
	AssetManager assetManager = LitePalApplication.getContext().getAssets();
	String[] fileNames = assetManager.list("");
	if (fileNames != null && fileNames.length > 0) {
		for (String fileName : fileNames) {
			if (Const.Config.CONFIGURATION_FILE_NAME.equalsIgnoreCase(fileName)) {
				return assetManager.open(fileName, AssetManager.ACCESS_BUFFER);
			}
		}
	}
	throw new ParseConfigurationFileException(
			ParseConfigurationFileException.CAN_NOT_FIND_LITEPAL_FILE);
}