Example usage for android.content Context getAssets

List of usage examples for android.content Context getAssets

Introduction

In this page you can find the example usage for android.content Context getAssets.

Prototype

public abstract AssetManager getAssets();

Source Link

Document

Returns an AssetManager instance for the application's package.

Usage

From source file:net.wequick.small.Bundle.java

private static void loadBundles(Context context) {
    JSONObject manifestData;// w  ww .  jav a 2s  .co m
    try {
        File patchManifestFile = getPatchManifestFile();
        String manifestJson = getCacheManifest();
        if (manifestJson != null) {
            // Load from cache and save as patch
            if (!patchManifestFile.exists())
                patchManifestFile.createNewFile();
            PrintWriter pw = new PrintWriter(new FileOutputStream(patchManifestFile));
            pw.print(manifestJson);
            pw.flush();
            pw.close();
            // Clear cache
            setCacheManifest(null);
        } else if (patchManifestFile.exists()) {
            // Load from patch
            BufferedReader br = new BufferedReader(new FileReader(patchManifestFile));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            br.close();
            manifestJson = sb.toString();
        } else {
            // Load from built-in `assets/bundle.json'
            InputStream builtinManifestStream = context.getAssets().open(BUNDLE_MANIFEST_NAME);
            int builtinSize = builtinManifestStream.available();
            byte[] buffer = new byte[builtinSize];
            builtinManifestStream.read(buffer);
            builtinManifestStream.close();
            manifestJson = new String(buffer, 0, builtinSize);
        }

        // Parse manifest file
        manifestData = new JSONObject(manifestJson);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    Manifest manifest = parseManifest(manifestData);
    if (manifest == null)
        return;

    loadBundles(manifest.bundles);
}

From source file:de.enlightened.peris.MessageActivity.java

private void renderMessage(final Message message) {
    final Context context = this.getApplicationContext();
    final SharedPreferences appPreferences = context.getSharedPreferences("prefs", 0);
    final boolean useShading = appPreferences.getBoolean("use_shading", false);
    final boolean useOpenSans = appPreferences.getBoolean("use_opensans", false);
    final int fontSize = appPreferences.getInt("font_size", DEFAULT_FONT_SIZE);
    final boolean currentAvatarSetting = appPreferences.getBoolean("show_images", true);
    final Typeface opensans = Typeface.createFromAsset(context.getAssets(), "fonts/opensans.ttf");

    final View view = this.findViewById(R.id.message_layout);
    final TextView poAuthor = (TextView) view.findViewById(R.id.message_author);
    final TextView poTimestamp = (TextView) view.findViewById(R.id.message_timestamp);
    final TextView tvOnline = (TextView) view.findViewById(R.id.message_online_status);

    final LinearLayout llBorderBackground = (LinearLayout) view.findViewById(R.id.ll_border_background);
    final LinearLayout llColorBackground = (LinearLayout) view.findViewById(R.id.ll_color_background);

    String textColor = context.getString(R.string.default_text_color);
    if (this.application.getSession().getServer().serverTextColor.contains("#")) {
        textColor = this.application.getSession().getServer().serverTextColor;
    }/*from  www. ja  v  a  2s .c o m*/

    String boxColor = context.getString(R.string.default_element_background);
    if (this.application.getSession().getServer().serverBoxColor != null) {
        boxColor = this.application.getSession().getServer().serverBoxColor;
    }

    if (boxColor.contains("#")) {
        llColorBackground.setBackgroundColor(Color.parseColor(boxColor));
    } else {
        llColorBackground.setBackgroundColor(Color.TRANSPARENT);
    }

    //TODO: remove border?
    String boxBorder = context.getString(R.string.default_element_border);
    if (this.application.getSession().getServer().serverBoxBorder != null) {
        boxBorder = this.application.getSession().getServer().serverBoxBorder;
    }

    if (boxBorder.contentEquals("1")) {
        llBorderBackground.setBackgroundResource(R.drawable.element_border);
    } else {
        llBorderBackground.setBackgroundColor(Color.TRANSPARENT);
    }

    if (useOpenSans) {
        poAuthor.setTypeface(opensans);
        poTimestamp.setTypeface(opensans);
        tvOnline.setTypeface(opensans);
    }

    if (useShading) {
        poAuthor.setShadowLayer(2, 0, 0, Color.parseColor("#66000000"));
        tvOnline.setShadowLayer(2, 0, 0, Color.parseColor("#66000000"));
    }

    final LinearLayout llPostBodyHolder = (LinearLayout) view.findViewById(R.id.message_body_holder);
    llPostBodyHolder.removeAllViews();

    final ImageView poAvatar = (ImageView) view.findViewById(R.id.message_avatar);

    if (boxColor != null && boxColor.contains("#") && boxColor.length() == 7) {
        final ImageView postAvatarFrame = (ImageView) view.findViewById(R.id.message_avatar_frame);
        postAvatarFrame.setColorFilter(Color.parseColor(boxColor));
    } else {
        final ImageView postAvatarFrame = (ImageView) view.findViewById(R.id.message_avatar_frame);
        postAvatarFrame.setVisibility(View.GONE);
    }

    if (message.isAuthorOnline()) {
        tvOnline.setText("ONLINE");
        tvOnline.setVisibility(View.VISIBLE);
    } else {
        tvOnline.setVisibility(View.GONE);
    }

    poAuthor.setText(message.getAuthor());
    poTimestamp.setText(DateTimeUtils.getTimeAgo(message.getTimestamp()));

    final String postContent = message.getBody();
    // TODO: add attachments
    BBCodeParser.parseCode(context, llPostBodyHolder, postContent, opensans, useOpenSans, useShading,
            new ArrayList<PostAttachment>(), fontSize, true, textColor, this.application);

    poAuthor.setTextColor(Color.parseColor(textColor));
    poTimestamp.setTextColor(Color.parseColor(textColor));

    if (currentAvatarSetting) {
        if (Net.isUrl(message.getAuthorAvatar())) {
            final String imageUrl = message.getAuthorAvatar();
            ImageLoader.getInstance().displayImage(imageUrl, poAvatar);
        } else {
            poAvatar.setImageResource(R.drawable.no_avatar);
        }
    } else {
        poAvatar.setVisibility(View.GONE);
    }
}

From source file:com.denel.facepatrol.MainActivity.java

public void copydatabase(Context mcontext) {

    String dbname = "DenelDB";
    File outfile = mcontext.getDatabasePath(dbname);
    if (outfile.exists()) {
        return;//from w  ww .  ja  va2s.  c  o  m
    }
    outfile = mcontext.getDatabasePath(dbname + ".temp");
    // parent directory for his file if it doesn't exist,
    // in this case it returns a false.
    outfile.getParentFile().mkdirs();
    try {
        InputStream instream = mcontext.getAssets().open(dbname);
        OutputStream outstream = new FileOutputStream(outfile);
        //transfer bytes from instream to outstream
        byte[] buffer = new byte[1024];
        int length;
        while ((length = instream.read(buffer)) > 0) {
            outstream.write(buffer, 0, length);
        }
        outstream.flush();
        outstream.close();
        instream.close();
        outfile.renameTo(mcontext.getDatabasePath(dbname));
    } catch (IOException e) {
        if (outfile.exists()) {
            outfile.delete();
        }
    }
}

From source file:net.smart_json_database.JSONDatabase.java

private JSONDatabase(Context context, String configurationName) throws InitJSONDatabaseExcepiton {

    AssetManager assetManager = context.getAssets();
    InputStream stream = null;/*  w w w  .java 2  s.  c om*/

    String configXML = null;
    try {
        configXML = configurationName + ".xml";
        stream = assetManager.open(configXML);

    } catch (IOException e) {
        throw new InitJSONDatabaseExcepiton("Could not load asset " + configXML);
    } finally {
        if (stream != null) {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLConfigHandler handler = new XMLConfigHandler();
            SAXParser saxparser;
            try {
                saxparser = factory.newSAXParser();
                saxparser.parse(stream, handler);
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("Parser-Error while reading the " + configXML, e);
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("SAX-Error while reading the " + configXML, e);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("IO-Error while reading the " + configXML, e);
            }

            mDbName = handler.getDbName();

            if (Util.IsNullOrEmpty(mDbName))
                throw new InitJSONDatabaseExcepiton("db name is empty check the xml configuration");

            mDbVersion = handler.getDbVersion();

            if (mDbVersion < 1)
                throw new InitJSONDatabaseExcepiton(
                        "db version must be 1 or greater -  check the xml configuration");

            mUpgradeClassPath = handler.getUpgradeClass();

            if (!Util.IsNullOrEmpty(mUpgradeClassPath)) {
                try {
                    Class<?> x = Class.forName(mUpgradeClassPath);
                    dbUpgrade = (IUpgrade) x.newInstance();
                } catch (Exception e) {
                }
            }

            dbHelper = new DBHelper(context, mDbName, mDbVersion);
            listeners = new ArrayList<IDatabaseChangeListener>();
            tags = new HashMap<String, Integer>();
            invertedTags = new HashMap<Integer, String>();
            updateTagMap();

        } else {
            throw new InitJSONDatabaseExcepiton(configXML + " is empty");
        }
    }
}

From source file:de.appplant.cordova.emailcomposer.EmailComposerImpl.java

/**
 * The URI for an asset.// w  ww .j av a2s  .co  m
 *
 * @param path
 * The given asset path.
 * @param ctx
 * The application context.
 * @return
 * The URI pointing to the given path.
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
private Uri getUriForAssetPath(String path, Context ctx) {
    String resPath = path.replaceFirst("file:/", "www");
    String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
    File dir = ctx.getExternalCacheDir();

    if (dir == null) {
        Log.e("EmailComposer", "Missing external cache dir");
        return Uri.EMPTY;
    }

    String storage = dir.toString() + ATTACHMENT_FOLDER;
    File file = new File(storage, fileName);

    new File(storage).mkdir();

    try {
        AssetManager assets = ctx.getAssets();

        FileOutputStream outStream = new FileOutputStream(file);
        InputStream inputStream = assets.open(resPath);

        copyFile(inputStream, outStream);
        outStream.flush();
        outStream.close();
    } catch (Exception e) {
        Log.e("EmailComposer", "File not found: assets/" + resPath);
        e.printStackTrace();
    }

    return Uri.fromFile(file);
}

From source file:com.udacity.movietimes.adapter.MovieDetailAdapter.java

public void updateFavoriteButton(final MovieViewHolder viewHolder, final Context context, final Cursor cursor) {
    // set the favorite button of the movie. First we check in the database if the favorite column
    // is Y or N. Based on that we switch the indicator as well as update the data in Movie DB.
    // Its basically act like a switch to update favorite column in the Movie Table
    Uri uri = MovieContract.MovieEntry.buildMovieWithMovieId(cursor.getLong(COL_ID));
    Cursor temp = context.getContentResolver().query(uri, null, null, null, null, null);
    temp.moveToFirst();/*from w w w . j  av  a 2s  . co  m*/
    final ContentValues values = new ContentValues();
    DatabaseUtils.cursorRowToContentValues(temp, values);

    Typeface fontFamily = Typeface.createFromAsset(context.getAssets(), "fonts/fontawesome.ttf");
    viewHolder.favorite.setTypeface(fontFamily);

    if (values.get(MovieContract.MovieEntry.COLUMN_FAVORITE).equals("N")) {
        viewHolder.favorite.setText("\uf196");
    } else {
        viewHolder.favorite.setText("\uf14a");
    }

    viewHolder.favorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String movieId = (String) values.get(MovieContract.MovieEntry.COLUMN_MOVIE_ID);
            if (values.get(MovieContract.MovieEntry.COLUMN_FAVORITE).equals("N")) {
                values.put(MovieContract.MovieEntry.COLUMN_FAVORITE, "Y");
                viewHolder.favorite.setText("\uf14a");

            } else {
                values.put(MovieContract.MovieEntry.COLUMN_FAVORITE, "N");
                viewHolder.favorite.setText("\uf196");

            }
            context.getContentResolver().update(MovieContract.MovieEntry.CONTENT_URI, values,
                    MovieContract.MovieEntry.COLUMN_MOVIE_ID + " = ? ", new String[] { movieId });

        }
    });

}

From source file:com.chalmers.feedlr.adapter.FeedAdapter.java

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    super.newView(context, cursor, parent);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View tempView = inflater.inflate(R.layout.feed_item, null);

    // Find views
    ViewHolder viewHolder = new ViewHolder();
    viewHolder.text = (TextView) tempView.findViewById(R.id.feed_item_text);
    viewHolder.author = (TextView) tempView.findViewById(R.id.feed_item_author);
    viewHolder.timestamp = (TextView) tempView.findViewById(R.id.feed_item_timestamp);
    viewHolder.profilePicture = (ImageView) tempView.findViewById(R.id.feed_item_author_image);
    viewHolder.source = (ImageView) tempView.findViewById(R.id.feed_item_source_image);

    // Set fonts//from   www.  j  a  va2 s .c o  m
    Typeface robotoThinItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-ThinItalic.ttf");
    Typeface robotoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf");
    Typeface robotoLight = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
    viewHolder.text.setTypeface(robotoLight);
    viewHolder.timestamp.setTypeface(robotoThinItalic);
    viewHolder.author.setTypeface(robotoMedium);

    tempView.setTag(viewHolder);
    return tempView;
}

From source file:org.appcelerator.titanium.util.TiUIHelper.java

@SuppressLint("DefaultLocale")
private static Typeface loadTypeface(final Context context, final String fontFamily) {
    if (context == null) {
        return null;
    }/*from www  .j a v a  2 s .  com*/
    if (mCustomTypeFaces.containsKey(fontFamily)) {
        return mCustomTypeFaces.get(fontFamily);
    }
    if (mCustomTypeFacesList == null) {
        AssetManager mgr = context.getAssets();
        try {
            ArrayList<String> fileList = new ArrayList<String>(Arrays.asList(mgr.list(customFontPath)));
            Iterator it = fileList.iterator();
            while (it.hasNext()) {
                String text = (String) it.next();
                if (!text.endsWith(".ttf") && !text.endsWith(".otf")) {
                    it.remove();
                }
            }
            mCustomTypeFacesList = fileList.toArray(new String[] {});
        } catch (Exception e) {
            Log.e(TAG, "Unable to load 'fonts' assets. Perhaps doesn't exist? " + e.getMessage());
        }
    }
    if (mCustomTypeFacesList != null) {
        Typeface tf = null;
        AssetManager mgr = context.getAssets();
        for (String f : mCustomTypeFacesList) {
            if (f.equals(fontFamily) || f.startsWith(fontFamily + ".") || f.startsWith(fontFamily + "-")) {
                tf = Typeface.createFromAsset(mgr, customFontPath + "/" + f);
                synchronized (mCustomTypeFaces) {
                    mCustomTypeFaces.put(fontFamily, tf);
                }
                return tf;
            }
        }
        tf = Typeface.create(fontFamily, Typeface.NORMAL);
        if (tf != null) {
            synchronized (mCustomTypeFaces) {
                mCustomTypeFaces.put(fontFamily, tf);
            }
            return tf;
        }
    }

    mCustomTypeFaces.put(fontFamily, null);
    return null;
}

From source file:com.denel.facepatrol.MainActivity.java

private void encryptfile(Context mcontext, SecretKey key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

    // This will probably change when I will the database will be downloaded from the server
    boolean db_file_exists = mcontext.getDatabasePath(dbname).exists();
    InputStream fis = null;//w  w  w.java2  s  . c o m
    File infile = mcontext.getDatabasePath(dbname);
    // check if database file exists to prevent downloading the file each start
    if (db_file_exists) {
        fis = new FileInputStream(infile);
    } else {
        fis = mcontext.getAssets().open(dbname);
    }
    // This stream write the encrypted text. This stream will be wrapped by another stream. 
    FileOutputStream fos = new FileOutputStream(mcontext.getDatabasePath(dbname_en).getAbsolutePath());
    // Length is 16 byte // Careful when taking user input!!! http://stackoverflow.com/a/3452620/1188357 
    SecretKeySpec sks = new SecretKeySpec(key.getEncoded(), "AES");
    // Create cipher 
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks);
    // Wrap the output stream 
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);
    // Write bytes 
    int b;
    byte[] d = new byte[8];
    while ((b = fis.read(d)) != -1) {
        cos.write(d, 0, b);
    } // Flush and close streams. 
    cos.flush();
    cos.close();
    fis.close();
    // delete the decrypted file
    if (infile.exists()) {
        infile.delete();
    }
}

From source file:com.codename1.impl.android.LocalNotificationPublisher.java

private Notification createAndroidNotification(Context context, LocalNotification localNotif,
        PendingIntent content) {/*w w w.j ava2 s . c  o  m*/
    Context ctx = context;
    int smallIcon = ctx.getResources().getIdentifier("ic_stat_notify", "drawable",
            ctx.getApplicationInfo().packageName);
    int icon = ctx.getResources().getIdentifier("icon", "drawable", ctx.getApplicationInfo().packageName);

    if (smallIcon == 0) {
        smallIcon = icon;
    } else {
        icon = smallIcon;
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
    builder.setContentTitle(localNotif.getAlertTitle());
    builder.setContentText(localNotif.getAlertBody());
    builder.setAutoCancel(true);
    if (localNotif.getBadgeNumber() >= 0) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
            builder.setNumber(localNotif.getBadgeNumber());
        }
    }
    String image = localNotif.getAlertImage();
    if (image != null && image.length() > 0) {
        if (image.startsWith("/")) {
            image = image.substring(1);
        }
        InputStream in;
        try {
            in = context.getAssets().open(image);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
            Bitmap im = BitmapFactory.decodeStream(in, null, opts);
            builder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(im));
        } catch (IOException ex) {
            Logger.getLogger(LocalNotificationPublisher.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    builder.setSmallIcon(smallIcon);
    builder.setContentIntent(content);
    AndroidImplementation.setNotificationChannel(
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE), builder, context);
    String sound = localNotif.getAlertSound();
    if (sound != null && sound.length() > 0) {
        sound = sound.toLowerCase();
        builder.setSound(android.net.Uri.parse("android.resource://" + ctx.getApplicationInfo().packageName
                + "/raw" + sound.substring(0, sound.indexOf("."))));
    }
    Notification n = builder.build();
    n.icon = icon;
    if (sound == null || sound.length() == 0) {
        n.defaults |= Notification.DEFAULT_SOUND;
    }
    return n;
}