image in the middle of my html text - android

I get an xml with command html text and images. I want when I fetch the tag img generate the image inside the text. in IOS works correctly
namespace A.iOS.Renderer
{
public class CustomLabelRenderer : LabelRenderer
{
protected LineSpacingLabel LineSpacingLabel { get; private set; }
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var attr = new NSAttributedStringDocumentAttributes();
var nsError = new NSError();
attr.DocumentType = NSDocumentType.HTML;
Control.AdjustsFontSizeToFitWidth = true;
var myHtmlData = NSData.FromString(Control.Text, NSStringEncoding.Unicode);
this.Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
this.Control.Font = UIFont.FromName("Lato", 20f);
Control.LineBreakMode = UILineBreakMode.Clip;
}
}
}
in android he even identifies the image, but just shows me a little square without image
namespace A.Droid.Renderer
{
public class CustomLabelRenderer : LabelRenderer
{
protected LineSpacingLabel LineSpacingLabel { get; private set; }
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var label = (TextView)Control;
label.SetLineSpacing(11, 1);
label.TextFormatted = Html.FromHtml(Control.Text);
Control.MovementMethod = LinkMovementMethod.Instance; // Makes links clickable
this.UpdateLayout();
}
}
}
what I have to change in my command in android so that my images are displayed on the label ?

I hope it works for you.
onCreate()
Spanned spannedValue = Html.fromHtml("Your Html", getImageHTML(), null);
YourTextView.setText(spannedValue);
functions:
public Html.ImageGetter getImageHTML() {
Html.ImageGetter imageGetter = new Html.ImageGetter() {
public Drawable getDrawable(String source) {
DownloadImageTask task = new DownloadImageTask();
try {
return task.execute(new String[] { source }).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
};
return imageGetter;
}
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
for(String s : urls) {
try {
Drawable drawable = Drawable.createFromStream(new URL(s).openStream(), "src name");
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
Integer width = size.x;
Integer height = size.y;
Integer heigtbol = height / 3;
drawable.setBounds(0, 0, width, heigtbol);
return drawable;
} catch (IOException exception) {
Log.v("IOException", exception.getMessage());
return null;
}
}
return null;
}
#Override
protected void onPostExecute(Drawable drawable) {
super.onPostExecute(drawable);
}
}

Related

Map marker icons are not loading using Picasso

I am trying to load marker icons from URL but it's not showing me the icons on a map.What thing I am doing wrong.When I am using Bitmap to load icons it's working.
Picasso image load is not working for me.
I got the item name in a log:
>
....
D/success: #+ Set bitmap for Duke Of Wellington PT size: #3
D/success: #+ Set bitmap for Dante Gabriel Rossetti PT size: #2
D/success: #+ Set bitmap for Pierre Teilhard de Chardin PT size: #1
Here is my complete code :
private class CreateProductListTask extends AsyncTask<Void, Void, List<Product>> {
private String serverUrl;
public CreateProductListTask(String url) {
super();
this.serverUrl = url;
}
#Override
protected List<Product> doInBackground(Void... params) {
.....
JSONObject response = new JSONObject(stringBuffer.toString());
List<Product> products = new ArrayList<>();
HashMap<String, Bitmap> iconsMap = new HashMap<>();
try {
JSONArray productsJSON = response.getJSONArray("all_products");
for (int ixProduct = 0; ixProduct < productsJSON.length(); ixProduct++) {
JSONObject productJSON = productsJSON.getJSONObject(ixProduct);
String mapIconStr = productJSON.getString("map_icon");
URI uri = new URI(mapIconStr);
String[] segments = uri.getPath().split("/");
String iconName = segments[segments.length - 1];
// percetn-encode URL
String mapIconPath = mapIconStr.substring(0, mapIconStr.indexOf(iconName));
String iconUrlString = mapIconPath + URLEncoder.encode(iconName, "UTF-8");
// replace "http:" with "https:"
iconUrlString = iconUrlString.replace("http:", "https:");
try {
Product product = new Product();
product.id = productJSON.getString("ID");
product.name = productJSON.getString("post_title");
product.lat = productJSON.getDouble("latitude");
product.lon = productJSON.getDouble("longitude");
id = product.id;
System.out.println("my Id stored" + id);
product.icons= iconUrlString;
products.add(product);
} catch (Exception ignore) {
}
}
} catch (JSONException ex) {
Log.e("App", "Failure", ex);
}
return products;
} catch (Exception ex) {
Log.e("App", "yourDataTask", ex);
return null;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(List<Product> products) {
if (products != null) {
PoiTarget pt;
for (final Product product : products) {
Marker marker = googlemap.addMarker(new MarkerOptions()
.position(new LatLng(product.lat, product.lon))
.title(product.name)
/* .icon(BitmapDescriptorFactory.fromBitmap(product.icon))*/);
pt = new PoiTarget(marker);
poiTargets.add(pt);
Picasso.with(Frnt_mapActivity.this)
.load(product.icons)
.into(pt);
markerIds.put(marker, product.id);
}
}
}
}
//--------------------------------------------------------
// Inner class
//--------------------------------------------------------
class PoiTarget implements Target {
private Marker m;
public PoiTarget(Marker m) { this.m = m; }
#Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
m.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
poiTargets.remove(this);
Log.d("success"," #+ Set bitmap for "+m.getTitle()+" PT size: #"+poiTargets.size());
}
#Override public void onBitmapFailed(Drawable errorDrawable) {
Log.e("Load Image Failed"," #+ [ERROR] Don't set bitmap for "+m.getTitle());
poiTargets.remove(this);
}
#Override public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
Use Glide for this purpose , it loads bitmap faster than picasso. Sometimes picasso throws error while loading but in Glide this thing does not happens.
also Dont forget to close and reopen the marker after loading the image. See code below.
if (marker.isInfoWindowShown()) {
marker.hideInfoWindow();
marker.showInfoWindow();
}
let me know if you still have confusion . i will post my full code.
Replace this code
#Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
m.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
poiTargets.remove(this);
Log.d("success"," #+ Set bitmap for "+m.getTitle()+" PT size: #"+poiTargets.size());
}
with
#Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
poiTargets.remove(this);
m.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
Log.d("success"," #+ Set bitmap for "+m.getTitle()+" PT size: #"+poiTargets.size());
}

Set GIF image to Custom ImageView

I have custom ImageView for animated GIF image. i want to show GIF image, I tried but in this case it is contain url in Async instead I want to show GIF image from raw folder without using Glide. Anyone have any idea how to show image? Please guyz help to solve this problem!!!
I tried this for set raw file
new GifStaticData() {
#Override
protected void onPostExecute(Resource drawable) {
super.onPostExecute(drawable);
gifImageView.setImageResource(R.raw.earth_tilt_animation);
// Log.d(TAG, "GIF width is " + gifImageView.getGifWidth());
// Log.d(TAG, "GIF height is " + gifImageView.getGifHeight());
}
}.execute(R.raw.earth_tilt_animation);
GifStaticData.java
public class GifStaticData extends AsyncTask<Resource, Void, Resource> {
private static final String TAG = "GifDataDownloader";
#Override protected Resource doInBackground(final Resource... params) {
final Resource gifUrl = params[0];
if (gifUrl == null)
return null;
try {
// return ByteArrayHttpClient.get(gifUrl);
return gifUrl;
} catch (OutOfMemoryError e) {
Log.e(TAG, "GifDecode OOM: " + gifUrl, e);
return null;
}
}
}
GifImageView.java
public class GifImageView extends ImageView implements Runnable {
private static final String TAG = "GifDecoderView";
private GifDecoder gifDecoder;
private Bitmap tmpBitmap;
private final Handler handler = new Handler(Looper.getMainLooper());
private boolean animating;
private boolean shouldClear;
private Thread animationThread;
private OnFrameAvailable frameCallback = null;
private long framesDisplayDuration = -1L;
private OnAnimationStop animationStopCallback = null;
private final Runnable updateResults = new Runnable() {
#Override
public void run() {
if (tmpBitmap != null && !tmpBitmap.isRecycled()) {
setImageBitmap(tmpBitmap);
}
}
};
private final Runnable cleanupRunnable = new Runnable() {
#Override
public void run() {
tmpBitmap = null;
gifDecoder = null;
animationThread = null;
shouldClear = false;
}
};
public GifImageView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public GifImageView(final Context context) {
super(context);
}
public void setBytes(final byte[] bytes) {
gifDecoder = new GifDecoder();
try {
gifDecoder.read(bytes);
gifDecoder.advance();
} catch (final OutOfMemoryError e) {
gifDecoder = null;
Log.e(TAG, e.getMessage(), e);
return;
}
if (canStart()) {
animationThread = new Thread(this);
animationThread.start();
}
}
public long getFramesDisplayDuration() {
return framesDisplayDuration;
}
/**
* Sets custom display duration in milliseconds for the all frames. Should be called before {#link
* #startAnimation()}
*
* #param framesDisplayDuration Duration in milliseconds. Default value = -1, this property will
* be ignored and default delay from gif file will be used.
*/
public void setFramesDisplayDuration(long framesDisplayDuration) {
this.framesDisplayDuration = framesDisplayDuration;
}
public void startAnimation() {
animating = true;
if (canStart()) {
animationThread = new Thread(this);
animationThread.start();
}
}
public boolean isAnimating() {
return animating;
}
public void stopAnimation() {
animating = false;
if (animationThread != null) {
animationThread.interrupt();
animationThread = null;
}
}
public void clear() {
animating = false;
shouldClear = true;
stopAnimation();
handler.post(cleanupRunnable);
}
private boolean canStart() {
return animating && gifDecoder != null && animationThread == null;
}
public int getGifWidth() {
return gifDecoder.getWidth();
}
public int getGifHeight() {
return gifDecoder.getHeight();
}
#Override public void run() {
if (shouldClear) {
handler.post(cleanupRunnable);
return;
}
final int n = gifDecoder.getFrameCount();
do {
for (int i = 0; i < n; i++) {
if (!animating) {
break;
}
//milliseconds spent on frame decode
long frameDecodeTime = 0;
try {
long before = System.nanoTime();
tmpBitmap = gifDecoder.getNextFrame();
frameDecodeTime = (System.nanoTime() - before) / 1000000;
if (frameCallback != null) {
tmpBitmap = frameCallback.onFrameAvailable(tmpBitmap);
}
if (!animating) {
break;
}
handler.post(updateResults);
} catch (final ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
Log.w(TAG, e);
}
if (!animating) {
break;
}
gifDecoder.advance();
try {
int delay = gifDecoder.getNextDelay();
// Sleep for frame duration minus time already spent on frame decode
// Actually we need next frame decode duration here,
// but I use previous frame time to make code more readable
delay -= frameDecodeTime;
if (delay > 0) {
Thread.sleep(framesDisplayDuration > 0 ? framesDisplayDuration : delay);
}
} catch (final Exception e) {
// suppress any exception
// it can be InterruptedException or IllegalArgumentException
}
}
} while (animating);
if (animationStopCallback != null) {
animationStopCallback.onAnimationStop();
}
}
public OnFrameAvailable getOnFrameAvailable() {
return frameCallback;
}
public void setOnFrameAvailable(OnFrameAvailable frameProcessor) {
this.frameCallback = frameProcessor;
}
public interface OnFrameAvailable {
Bitmap onFrameAvailable(Bitmap bitmap);
}
public OnAnimationStop getOnAnimationStop() {
return animationStopCallback;
}
public void setOnAnimationStop(OnAnimationStop animationStop) {
this.animationStopCallback = animationStop;
}
public interface OnAnimationStop {
void onAnimationStop();
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
clear();
}
}
I had to play and pause the Gif image Glide - Cannot stop gif onClick- Getting TransitionDrawable instead of Animate/GifDrawable
The idea is to get drawable from view,checking if it is an instance of Gifdrawable and playing and pausing it.(Hoping the gif image is already playing)
Add this In OnClick of GifImageView
Drawable drawable = ((ImageView) v).getDrawable();
if (drawable instanceof GifDrawable) {
GifDrawable animatable = (GifDrawable) drawable;
if (animatable.isRunning()) {
animatable.stop();
} else {
animatable.start();
}
}
I found the solution of above problem using GifMovieView!!!
GifMovieViewer.java
public class GifMovieViewer extends Activity {
private Button btnStart;
private GifMovieView gif1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gif_movie_viewer);
gif1 = (GifMovieView) findViewById(R.id.gif1);
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gif1.setMovieResource(R.drawable.earth_tilt_animation);
//for pause
// gif1.setPaused(gif1.isPaused());
}
});
}
public void onGifClick(View v) {
GifMovieView gif = (GifMovieView) v;
gif.setPaused(!gif.isPaused());
}
}

update UI from AsyncTask

I created a custom TextView to show and images on it. I have to download the images and then show them on the textview. So I thought that I can do my job with a AsyncTask class. On the doInBackground I download and save the image on the Internal storage (for offline mode), and on the onPostExecute I call a method which shows the images on the textview. But it doesn't work. I mean instead of showing the images it shows the img tags.
I also tried to get the status from the AsyncTask class on the onPostExecute method and it's RUNNING. Isn't that weird? I thought that it will be FINISHED. Am I missing something about AsyncTask class?
Below is addImages method, where I find the img tags from the text and store the data on a List, and call the DownLoadImage class which extends the AsyncTask.
private boolean add(final Context context, final Spannable spannable) {
path = context.getFilesDir();
Pattern refImgPattern = Pattern.compile("<img .+?\\/>");
hasChanges = false;
refImgMatcher = refImgPattern.matcher(spannable);
while (refImgMatcher.find()) {
set = true;
for (ImageSpan span : spannable.getSpans(refImgMatcher.start(), refImgMatcher.end(), ImageSpan.class)) {
if (spannable.getSpanStart(span) >= refImgMatcher.start()
&& spannable.getSpanEnd(span) <= refImgMatcher.end()
) {
spannable.removeSpan(span);
} else {
set = false;
break;
}
}
String imageUrl = spannable.subSequence(refImgMatcher.start(0), refImgMatcher.end(0)).toString().trim();
width = 0;
Pattern widthPattern = Pattern.compile("width=\"[0-9]+?\"");
Matcher widthMatcher = widthPattern.matcher(imageUrl);
if (widthMatcher.find()) {
String w = widthMatcher.group(0);
w = w.replaceAll("width=", "");
w = w.replaceAll("\"", "");
width = Integer.valueOf(w);
}
height = 0;
Pattern heightPattern = Pattern.compile("height=\"[0-9]+?\"");
Matcher heightMatcher = heightPattern.matcher(imageUrl);
if (heightMatcher.find()) {
String h = heightMatcher.group(0);
h = h.replaceAll("height=", "");
h = h.replaceAll("\"", "");
height = Integer.valueOf(h);
}
Pattern urlPattern = Pattern.compile("(http|ftp|https):\\/\\/([\\w_-]+(?:(?:\\.[\\w_ -]+)+))([\\w.,#?^=%&:\\/~+#-]*[\\w#?^=%&\\/~+#-])?");
Matcher urlMatcher = urlPattern.matcher(imageUrl);
if (urlMatcher.find())
imageUrl = urlMatcher.group(0);
imageName = siteData.getId() + "_" + imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.length());
images.add(new Image(imageUrl, imageName, width, height, refImgMatcher.start(0), refImgMatcher.end(0)));
}
if (images.size() > 0) {
for (final Image img : images) {
image = new File(path, img.name);
if (!image.exists()) {
new DownLoadImage(context, spannable, img).execute();
} else
addImages(spannable, context, img);
}
}
return hasChanges;
}
This is the addImages method where I replace the tags with images
private void addImages(Spannable spannable, Context context, Image im) {
image = new File(path, im.name);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
if (im.width > 0 && im.height > 0)
bitmap = Bitmap.createScaledBitmap(bitmap, im.width * 3, im.height * 3, true);
if (set) {
hasChanges = true;
spannable.setSpan(new ImageSpan(context, bitmap),
im.startIndex,
im.endIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
}
and the DownLoadImage class
private class DownLoadImage extends AsyncTask<Void, Void, Void> {
private Connection connection = Connection.getInstance();
private Context context;
private Spannable spannable;
private Image image;
public DownLoadImage(Context context, Spannable spannable, Image image) {
this.spannable = spannable;
this.context = context;
this.image = image;
}
#Override
protected Void doInBackground(Void... params) {
try {
connection.openConnection(image.path, ConnectionType.GET, false, false, null);
Integer status = connection.getResponseCode();
if (status >= 200 && status < 300) {
InputStream inputStream = new BufferedInputStream(connection.getInputStream());
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Actions.saveImage(context, bitmap, image.name);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
connection.closeConnection();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.i("status", this.getStatus().toString());
addImages(spannable, context, image);
}
}
***** EDIT *****
the getTextWithImages where I call the add method
private Spannable getTextWithImages(Context context, CharSequence text) {
images = new ArrayList<>();
Spannable spannable = spannableFactory.newSpannable(text);
add(context, spannable);
return spannable;
}
and the setText method where I call the getTextWithImages
#Override
public void setText(CharSequence text, BufferType type) {
Spannable s = getTextWithImages(getContext(), text);
super.setText(s, BufferType.SPANNABLE);
}
You could create an interface that invokes a callback to the UI thread, instead of using the context. For example, in your AsyncTask:
private class DownLoadImage extends AsyncTask<Void, Void, Void> {
private Connection connection = Connection.getInstance();
private Context context;
private Spannable spannable;
private Image image;
private OnImageDownloadedListener mOnImageDownloadedListener;
...
#Override
protected Void doInBackground(Void... params) {
...
...
}
// Interface the task will use to communicate with your activity method.
public interface OnImageDownloadedListener {
void onImageDownloaded(Spannable spannable, Image image); // No need for context.
}
#Override
protected void onPostExecute(Void aVoid) {
if (mOnImageDownloadedListener != null) {
// If we set a listener, invoke it.
mOnImageDownloadedListener.onImageDownloaded(spannable, image);
}
}
// Setter.
public setOnImageDownloadedListener(OnImageDownloadedListener listener) {
mOnImageDownloadedListener = listener;
}
}
Then when you create your task try:
if (!image.exists()) {
// Create the task.
DownloadImage downloadTask = new DownLoadImage(context, spannable, img);
// Set your listener.
downloadTask.setOnImageDownloadedListener(new OnImageLoadedListener() {
#Override
public void onImageDownloaded(Spannable spannable, Image image) {
// Add the images.
addImages(spannable, **YourContextHere(Activity/etc)**.this, image)
}
});
// Execute.
downloadTask.execute();
} else
addImages(spannable, context, img);
Hope this helps.

Drawables won't load using AsyncTask

I have the queryAppIcon() method that queries and stores images in the array appIconDrawable. However, I'm only getting blank where images should pop up. Please let me know if I should post any other relevant code
This is the relevant code inside the ViewActivity:
// global vars
final Drawable[] appIconDrawable = null;
int i;
public Drawable[] queryAppIcon() throws ParseException, IOException {
ParseQuery<ParseObject> query = ParseQuery.getQuery("AndroidStoreContent");
query.whereExists("appIcon");
List<ParseObject> ParseResult = query.find();
// Drawable array
appIconDrawable = new Drawable[ParseResult.size()];
for (i = 0; i < ParseResult.size(); i++) {
ParseFile pf = (ParseFile) ParseResult.get(i).get("appIcon");
startDownload(pf);
}
return appIconDrawable;
}
public void startDownload(ParseFile pf) {
new DownloadImageTask(this).execute(pf);
}
public class DownloadImageTask extends AsyncTask<ParseFile, Void, Drawable> {
private AsyncResponse ar;
DownloadImageTask(AsyncResponse ar) {
this.ar = ar;
}
#Override
protected Drawable doInBackground(ParseFile... pf) {
return fetchDrawable(pf[0]);
}
protected void onPostExecute(Drawable result) {
ar.processFinish(result);
}
public Drawable fetchDrawable(ParseFile pf) {
InputStream is;
try {
is = (InputStream) new URL(pf.getUrl()).getContent();
return Drawable.createFromStream(is,null);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public void processFinish(Drawable d) {
appIconDrawable[i] = d; // i also tried testing appIconDrawable[1] = d and the app loaded with all blank images and then crashes
}
This is the interface, AsyncResponse:
public interface AsyncResponse {
void processFinish(Drawable d);
}
It seems like you need a bit of refactor...
You are expecting Drawable[] from queryAppIcon() but you will always get an empty set because you start the download which takes place in a separate thread to then update the return value.
You should be setting the Drawable to the ImageView from within processFinish.
Signs of things done wrong: Async methods such as downloading images should never have a return value.
UPDATE
Here is a very simple download AsyncTask but there are many checks, optimizations, etc. missing, like CACHE! Also, ImageView inside DownloadImageTask should be held by a WeakReference (Google it) otherwise it WILL leak your activity.
public class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
private static final String TAG = DownloadImageTask.class.getSimpleName();
private ImageView mImageView;
DownloadImageTask(ImageView imageView) {
mImageView = imageView;
}
#Override
protected Drawable doInBackground(String... url) {
return fetchDrawable(url[0]);
}
#Override
protected void onPostExecute(Drawable result) {
if (result != null) {
mImageView.setImageDrawable(result);
} else {
Log.w(TAG, "Could download image!");
}
}
public static Drawable fetchDrawable(String url) {
Log.v(TAG, "Downloading: " + url);
InputStream is;
try {
is = (InputStream) new URL(url).getContent();
return Drawable.createFromStream(is, null);
} catch (MalformedURLException e) {
Log.e(TAG, e.getMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
return null;
}
}
Adapter:
public class ImageDownloadAdapter extends ArrayAdapter<String>{
public ImageDownloadAdapter(Context context, String[] objects) {
super(context, R.layout.item_image_download, R.id.txt_url, objects);
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
String url = getItem(position);
ImageView imageView = (ImageView) view.findViewById(R.id.img_download);
DownloadImageTask downloadImageTask = new DownloadImageTask(imageView);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
downloadImageTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
} else {
downloadImageTask.execute(url);
}
return view;
}
}
Activity:
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(new ImageDownloadAdapter(this, new String[]{
"http://www.beautystat.com/site/wp-content/uploads/2011/02/happy-faces-small.jpg",
"http://www.ducthide.com/new_wallet_pics/happy_face.JPG"
}));

Loading picture show loading progress

I use the function to show picture:
Bitmap imageBitmap = loadBitmap(URL);
loadBitmap() as below:
private Bitmap loadBitmap(String url) {
try {
Bitmap bm = BitmapFactory.decodeStream((InputStream)this.fetch(url));
return bm;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
And fetch() below:
public Object fetch(String address) {
try {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
catch(Exception e) {
e.printStackTrace();
}
return this;
}
I want to show the loading progress or a load.png while it loading.
And end with the picture loading finish and show it.
How can I do?
I try to make like ProgressDialog.
But I don't know how to use?
You can use AsyncTask to show a Progress Dialog on the PreExecute() method and hide/dismiss it in the PostExecute() method.
ProgressDialog prog = new ProgressDialog(this); // Create Progress Dialog
private class DownloadBitmap extends AsyncTask<Void, Integer, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Display progressDialog before download starts
prog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prog.hide(); //Hide Progress Dialog else use dismiss() to dismiss the dialog
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
/*
* Perform download and Bitmap conversion here
*
*/
return null;
}
}
And finally call the AsyncTask through,
DownloadBitmap dd = new DownloadBitmap();
dd.execute();
You can use a ProgressBar for this.
Check out these links:
Tutorial 1
Tutorial 2
you can't do that directly, as Android doesn't support GIF files. So to away with that you have to create separate image (loading image into split images) and make animation of it. At the time of loading run the animation and once Bitmap avail stop animation and set Bitmap on ImageView
This example shows progressbar while downloading the image and later it is invisible.
public class ImageDownload extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
ImageView mainImageView = (ImageView) findViewById(R.id.imageView);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
String imageurl = "http://ipadwallpaperportal.com/wp-content/main/2011_09/purple-flower-close-up-1024x1024-wallpaper.jpg";
ImageDownloadMessageHandler imageDownloadMessageHandler1 = new ImageDownloadMessageHandler(
progressBar, mainImageView);
ImageDownlaodThread imageDownlaodThread = new ImageDownlaodThread(
imageDownloadMessageHandler1, imageurl);
imageDownlaodThread.start();
}
class ImageDownlaodThread extends Thread {
ImageDownloadMessageHandler imageDownloadMessageHandler;
String imageUrl;
public ImageDownlaodThread(
ImageDownloadMessageHandler imageDownloadMessageHandler,
String imageUrl) {
this.imageDownloadMessageHandler = imageDownloadMessageHandler;
this.imageUrl = imageUrl;
}
#Override
public void run() {
Drawable drawable = LoadImageFromWebOperations(imageUrl);
Message message = imageDownloadMessageHandler.obtainMessage(1,
drawable);
imageDownloadMessageHandler.sendMessage(message);
System.out.println("Message sent");
}
}
class ImageDownloadMessageHandler extends Handler {
ProgressBar progressBar;
View imageTextView;
public ImageDownloadMessageHandler(ProgressBar progressBar,
View imageTextView) {
this.progressBar = progressBar;
this.imageTextView = imageTextView;
}
#Override
public void handleMessage(Message message) {
progressBar.setVisibility(View.GONE);
imageTextView.setBackgroundDrawable(((Drawable) message.obj));
imageTextView.setVisibility(View.VISIBLE);
}
}
Drawable LoadImageFromWebOperations(String strUrl) {
/**
* This is one method
*/
long x1 = System.currentTimeMillis();
Drawable d = null;
InputStream is = null;
try {
is = (InputStream) new URL(strUrl).getContent();
d = Drawable.createFromStream(is, "src name");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
long x2 = System.currentTimeMillis();
long res = x2 - x1;
Log.v("Image Downloading Time", "" + res);
}

Categories

Resources