Example usage for android.graphics.drawable Drawable createFromStream

List of usage examples for android.graphics.drawable Drawable createFromStream

Introduction

In this page you can find the example usage for android.graphics.drawable Drawable createFromStream.

Prototype

public static Drawable createFromStream(InputStream is, String srcName) 

Source Link

Document

Create a drawable from an inputstream

Usage

From source file:com.temboo.example.YouTubeResultView.java

/**
 * A utility method to retrieve the thumbnail image on a separate thread, and populate
 * the image view with that thumbnail/*from w w w.j ava  2s  .  co m*/
 * @param urlString - the URL of the thumbnail to retrieve
 * @param imageView - the view to populate with the thumbnail
 */
private void fetchDrawableOnThread(final String urlString, final ImageView imageView) {

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            imageView.setImageDrawable((Drawable) message.obj);
        }
    };

    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet request = new HttpGet(urlString);
                HttpResponse response = httpClient.execute(request);
                InputStream is = response.getEntity().getContent();
                Drawable drawable = Drawable.createFromStream(is, "src");

                Message message = handler.obtainMessage(1, drawable);
                handler.sendMessage(message);
            } catch (Exception e) {
                Toast.makeText(getContext(), "An error occurred retrieving the video thumbnail",
                        Toast.LENGTH_LONG).show();
            }
        }
    };
    thread.start();
}

From source file:org.dmfs.webcal.utils.ImageProxy.java

/**
 * Return the image with then given id. If the icon is not present in the memory or filesystem cache this method returns <code>null</code>. The caller is
 * notified via the given {@link ImageAvailableListener} when the image has been loaded.
 * // w w w .  ja va  2 s.co m
 * @param iconId
 *            The id of the icon to load.
 * @param callback
 *            The {@link ImageAvailableListener} to notify when the icon has been loaded.
 * @return A {@link Drawable} or null of the icon is loaded asynchronously or the id is invalid.
 */
public Drawable getImage(long iconId, ImageAvailableListener callback) {
    if (iconId == -1) {
        return null;
    }

    Drawable iconDrawable = mImageCache.get(iconId);
    if (iconDrawable == null) {
        try {
            AssetFileDescriptor afd = CalendarContentContract.Icon.getIcon(mAppContext, iconId, false);
            FileInputStream inputStream = afd.createInputStream();
            iconDrawable = Drawable.createFromStream(inputStream, null);
            if (iconDrawable != null) {
                mImageCache.put(iconId, iconDrawable);
            }
        } catch (FileNotFoundException e) {
            registerImageRequest(iconId, callback);
        } catch (IOException e) {
            registerImageRequest(iconId, callback);
        }
    }
    return iconDrawable;
}

From source file:de.storyquest.client.ContentActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // enable immersive mode
    getWindow().getDecorView()//from w ww. j  ava 2s  .  c  o  m
            .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    getWindow().addFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

    // load initial layout
    setContentView(R.layout.activity_content);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    View header = navigationView.getHeaderView(0);

    // apply theme
    try {
        Drawable d = Drawable.createFromStream(getAssets().open("sidebar.jpg"), null);
        navigationView.setBackground(d);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // wire the drawer open event to the character sheet refresh
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer != null) {
        drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                execJavaScriptInCharactersheet("if(typeof refresh!='undefined')refresh()");
            }
        });
    }

    // get extra data with bookmark to load
    Intent intent = getIntent();
    if (intent.hasExtra(BOOKMARKID))
        bookmarkId = intent.getStringExtra(BOOKMARKID);

    // set the cover image from assets
    ImageView coverImage = (ImageView) header.findViewById(R.id.coverImage);
    try {
        InputStream ims = getAssets().open("cover.png");
        Drawable d = Drawable.createFromStream(ims, null);
        coverImage.setImageDrawable(d);
    } catch (Exception e) {
        throw new RuntimeException("Error loading cover image. Is 'cover.png' available in assets?", e);
    }

    // make the web content debuggable from external chrome tools
    WebView.setWebContentsDebuggingEnabled(true);

    // enable script interfaces
    scriptSystem = new ScriptSystem(this);
    scriptStorage = new ScriptStorage(this,
            getApplicationContext().getSharedPreferences(ScriptStorage.CONTEXT, Context.MODE_PRIVATE));
    scriptSound = new ScriptSound(this);
    scriptGameServices = new ScriptGameServices(this);

    // setup character webview
    character = (WebView) header.findViewById(R.id.characterView);
    character.getSettings().setJavaScriptEnabled(true);
    character.getSettings().setDomStorageEnabled(true);
    character.getSettings().setAllowFileAccess(true);
    character.getSettings().setAppCacheEnabled(true);
    character.addJavascriptInterface(scriptSystem, "sqSystem");
    character.addJavascriptInterface(scriptStorage, "nativeStorage");
    character.addJavascriptInterface(scriptSound, "sqSound");
    character.addJavascriptInterface(scriptGameServices, "sqGameServices");
    character.loadUrl("file:///android_asset/character.html");

    // setup web view
    web = (WebView) findViewById(R.id.webView);
    web.getSettings().setJavaScriptEnabled(true);
    web.getSettings().setDomStorageEnabled(true);
    web.getSettings().setAllowFileAccess(true);
    web.getSettings().setAppCacheEnabled(true);
    web.addJavascriptInterface(scriptSystem, "sqSystem");
    web.addJavascriptInterface(scriptStorage, "nativeStorage");
    web.addJavascriptInterface(scriptSound, "sqSound");
    web.addJavascriptInterface(scriptGameServices, "sqGameServices");

    // adding event overrides for the web view
    web.setWebChromeClient(new WebChromeClient());
    web.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String urlText) {
            if (urlText.startsWith("http")) { // Could be cleverer and use a regex
                Log.d(LOGTAG, "Opening standard web intent window for " + urlText);
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(urlText));
                startActivity(i);
                return true;
            } else {
                Log.d(LOGTAG, "Loading in webview: " + urlText);
                web.loadUrl(urlText);
                return true;
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d(LOGTAG, "Page rendering started: " + url + ".");
            displaySpinner(R.string.loading);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d(LOGTAG, "Page rendering finished: " + url + ".");
            hideSpinner();
            if (bookmarkId != null && url.startsWith("file:///android_asset/content.html")) {
                Log.i(LOGTAG, "Loading bookmark " + bookmarkId + ".");
                execJavaScriptInContent("loadBookmark('" + bookmarkId + "')");
                bookmarkId = null;
            }
            super.onPageFinished(view, url);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            Log.d(LOGTAG, "Intercepted call: " + url + ".");
            return null;
        }
    });
    web.setWebChromeClient(new WebChromeClient() {
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.d(LOGTAG, cm.message() + " - from line " + cm.lineNumber() + " of " + cm.sourceId());
            return true;
        }
    });
    web.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    web.requestFocus(View.FOCUS_DOWN);

    // finally loading content bootstrap
    Log.i(LOGTAG, "Loading index.html");
    web.loadUrl("file:///android_asset/index.html");
}

From source file:com.cm.beer.util.DrawableManager.java

/**
 * //  w  w  w  .jav  a 2 s .  co m
 * @param urlString
 * @return
 */
public Drawable fetchDrawable(String urlString) {
    if (mDrawableCache.containsKey(urlString)) {
        if (Logger.isLogEnabled())
            Logger.log("Returning Drawable from Cache:" + urlString);
        SoftReference<Drawable> softReference = mDrawableCache.get(urlString);
        if ((softReference == null) || (softReference.get() == null)) {
            mDrawableCache.remove(urlString);
            if (Logger.isLogEnabled())
                Logger.log("fetchDrawable():Soft Reference has been Garbage Collected:" + urlString);
        } else {
            return softReference.get();
        }
    }

    if (Logger.isLogEnabled())
        Logger.log("image url:" + urlString);
    try {
        // prevents multithreaded fetches for the same image
        mLockCache.put(urlString, urlString);
        if (Logger.isLogEnabled())
            Logger.log("Begin Downloading:" + urlString);
        InputStream is = fetch(urlString);
        if (Logger.isLogEnabled())
            Logger.log("End Downloading:" + urlString);
        Drawable drawable = Drawable.createFromStream(is, "src");
        mDrawableCache.put(urlString, new SoftReference<Drawable>(drawable));
        mLockCache.remove(urlString);
        if (Logger.isLogEnabled())
            Logger.log("got a thumbnail drawable: " + drawable.getBounds() + ", "
                    + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
                    + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
        return drawable;
    } catch (Throwable e) {
        Log.e(this.getClass().getName(), "fetchDrawable failed", e);
        return null;
    }
}

From source file:org.jinzora.util.DrawableManager.java

public Drawable fetchDrawable(String urlString) {
    if (drawableMap.containsKey(urlString)) {
        SoftReference<Drawable> reference = drawableMap.get(urlString);
        Drawable drawable = reference.get();
        if (drawable != null) {
            if (DBG)
                Log.d(TAG, "Using cached image");
            return drawable;
        } else {//  w w w .ja  v a  2 s  .  c  om
            if (DBG)
                Log.d(TAG, "Soft reference cleared.");
            drawableMap.remove(urlString);
        }
    }

    if (DBG)
        Log.d(TAG, "Fetching image");
    try {
        InputStream is = fetch(urlString);
        Drawable drawable = Drawable.createFromStream(is, "src");

        if (drawable != null) {
            drawableMap.put(urlString, new SoftReference<Drawable>(drawable));
        } else {
            Log.w(this.getClass().getSimpleName(), "could not get thumbnail for " + urlString);
        }

        return drawable;
    } catch (MalformedURLException e) {
        Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
        return null;
    } catch (IOException e) {
        Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
        return null;
    }
}

From source file:ar.com.lapotoca.resiliencia.gallery.util.ImageWorker.java

/**
 * Load an image specified by the data parameter into an ImageView (override
 * {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and
 * disk cache will be used if an {@link ImageCache} has been added using
 * {@link ImageWorker#addImageCache(android.support.v4.app.FragmentManager, ImageCache.ImageCacheParams)}. If the
 * image is found in the memory cache, it is set immediately, otherwise an {@link AsyncTask}
 * will be created to asynchronously load the bitmap.
 *
 * @param data The URL of the image to download.
 * @param imageView The ImageView to bind the downloaded image to.
 * @param listener A listener that will be called back once the image has been loaded.
 *///ww w.  j a v a  2  s .  c o  m
public void loadImage(Object data, boolean localSource, ImageView imageView, OnImageLoadedListener listener) {
    if (data == null) {
        return;
    }

    BitmapDrawable value = null;

    if (mImageCache != null) {
        value = mImageCache.getBitmapFromMemCache(String.valueOf(data));
    }

    if (value != null) {
        // Bitmap found in memory cache
        imageView.setImageDrawable(value);
        if (listener != null) {
            listener.onImageLoaded(true);
        }
    } else {
        if (localSource) {
            Drawable drawable = null;
            try {
                drawable = Drawable.createFromStream(mAssets.open(data.toString()), null);
                imageView.setImageDrawable(drawable);
            } catch (Exception e) {
                Log.e(TAG, "No se pudo cargar la imagen", e);
            }
        } else if (cancelPotentialWork(data, imageView)) {
            //BEGIN_INCLUDE(execute_background_task)
            final BitmapWorkerTask task = new BitmapWorkerTask(data, imageView, listener);
            final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, mLoadingBitmap, task);
            imageView.setImageDrawable(asyncDrawable);

            // NOTE: This uses a custom version of AsyncTask that has been pulled from the
            // framework and slightly modified. Refer to the docs at the top of the class
            // for more info on what was changed.
            task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR);
            //END_INCLUDE(execute_background_task)
        }
    }
}

From source file:org.sigimera.app.android.ProfileFragment.java

@Override
public final View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.profile_fragment, container, false);

    progessDialog = ProgressDialog.show(getActivity(), "Preparing profile information!",
            "Please be patient until the information are ready...", true);
    progessDialog.setCancelable(true);//  w  w  w. java2  s .  c  om
    Thread worker = new Thread() {
        @Override
        public void run() {
            try {
                Looper.prepare();
                authToken = ApplicationController.getInstance().getSessionHandler().getAuthenticationToken();

                stats = PersistanceController.getInstance().getUsersStats(authToken);

                if (stats == null) {
                    Log.d("[PROFILE FRAGMENT]", "User stats are empty.");
                }

                if (stats != null && stats.getUsername() != null) {
                    InputStream is = (InputStream) getAvatarURL(stats.getEmail()).getContent();
                    drawable = Drawable.createFromStream(is, "src name");
                    radius = stats.getRadius();
                }

                guiHandler.post(updateGUI);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (AuthenticationErrorException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    worker.start();

    return view;
}

From source file:gr.scify.newsum.ui.GooglePlus.java

private Drawable LoadImageFromWebOperations(String url) {
    try {/*from   w w  w .j ava 2s  .c om*/
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
    } catch (Exception e) {
        System.out.println("Exc=" + e);
        return null;
    }
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.ui.BrandInfoActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_brand_info);

    final Activity activity = this;
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);

    ImageView imageBrandLabel = (ImageView) findViewById(R.id.imageBrandLabel);

    // To start Camera
    Button buttonPrepareTest = (Button) findViewById(R.id.button_prepare);
    buttonPrepareTest.setOnClickListener(new View.OnClickListener() {
        @Override//  w w  w.j a va  2  s .com
        public void onClick(View view) {
            if (!ApiUtil.hasPermissions(activity, PERMISSIONS)) {
                ActivityCompat.requestPermissions(activity, PERMISSIONS, PERMISSION_ALL);
            } else {
                startCamera();
            }
        }
    });

    // To display Instructions
    Button buttonInstruction = (Button) findViewById(R.id.button_instructions);
    buttonInstruction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getBaseContext(), InstructionActivity.class);
            intent.putExtra(Constant.UUID, mUuid);
            startActivity(intent);
        }
    });

    mUuid = getIntent().getStringExtra(Constant.UUID);

    if (mUuid != null) {
        StripTest stripTest = new StripTest();

        // Display the brand in title
        setTitle(stripTest.getBrand(mUuid).getName());

        //            try {
        //                imageBrandLabel.setBackgroundColor(Color.parseColor(stripTest.getBrand(this, mUuid).getBackground()));
        //            } catch (Exception ignored) {
        //
        //            }

        // Display the brand photo
        InputStream ims = null;
        try {
            Drawable drawable;
            String image = stripTest.getBrand(mUuid).getImage();

            if (image.contains(File.separator)) {
                if (!image.contains(".")) {
                    image = image + ".webp";
                }
                drawable = Drawable.createFromPath(image);
            } else {
                String path = getResources().getString(R.string.striptest_images);
                ims = getAssets().open(path + File.separator + image + ".webp");
                drawable = Drawable.createFromStream(ims, null);
            }

            imageBrandLabel.setImageDrawable(drawable);
            imageBrandLabel.setScaleType(stripTest.getBrand(mUuid).getImageScale().equals("centerCrop")
                    ? ImageView.ScaleType.CENTER_CROP
                    : ImageView.ScaleType.FIT_CENTER);
        } catch (Exception ex) {
            Timber.e(ex);
        } finally {
            if (ims != null) {
                try {
                    ims.close();
                } catch (IOException e) {
                    Timber.e(e);
                }
            }

        }

        JSONArray instructions = stripTest.getBrand(mUuid).getInstructions();
        if (instructions == null || instructions.length() == 0) {
            buttonInstruction.setVisibility(View.INVISIBLE);
        }
    }
}

From source file:org.onepf.opfmaps.osmdroid.model.BitmapDescriptor.java

@Nullable
private Drawable createFromStream(@NonNull final Context context) {
    OPFLog.logMethod();// w  w  w .  j  av  a  2  s .  c  o m
    if (path == null) {
        return null;
    }

    InputStream inputStream = null;
    try {
        inputStream = createStream(context);
        return Drawable.createFromStream(inputStream, null);
    } catch (IOException e) {
        OPFLog.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                OPFLog.e(e.getMessage());
            }
        }
    }
    return null;
}