Android: Issues with images downloading - android

I have an app in which i am downloading and displaying images in a thread. Everything is working fine. But when the images are getting loaded same image is getting loaded in two to three places and when we scroll the screen images are loaded correctly. Please can any one of you can give any suggestions to this?
code:
try{
holder.progress.setVisibility(View.VISIBLE);
DownLoadImageInAThreadHandler(Item, holder);
}
catch(Exception e)
{
System.out.println("Exception in Downloading image : " + e.getMessage());
}
return convertView;
}
//This code is outside the getview method
public void DownLoadImageInAThreadHandler(final CategoryData Item, final ViewHolder holder)
{
nImageDownLoads++;
System.out.println("The images being downloaded :" + nImageDownLoads);
final Handler handler = new Handler()
{
#Override public void handleMessage(Message message)
{
holder.imgitem.setImageDrawable((Drawable) message.obj);
holder.imgitem.setVisibility(View.VISIBLE);
holder.progress.setVisibility(View.GONE);
}
};
//Thread for downloading the images
Thread t = new Thread()
{
public void run()
{
try
{
Item.bImageDownLoaded = 2;
System.out.println("Downloading image :"+Item.ImageUrl);
drawable=getDrawableFromUrl(Item.ImageUrl);
nImageDownLoads--;
System.out.println("Downloaded image :" + Item.ImageUrl);
System.out.println("Remaining images for downloading: " + nImageDownLoads);
if(drawable != null)
{
Item.bImageDownLoaded = 1;
//Send the message to the handler
Message message = handler.obtainMessage(1, drawable);
handler.sendMessage(message);
}
else{
int idNoImage = R.drawable.giftsuggestionsnoimage;
Drawable dwgNoImg = getParent().getResources().getDrawable(idNoImage);
//Send the message to the handler
Message message = handler.obtainMessage(1, dwgNoImg);
handler.sendMessage(message);
}
}
catch(Exception exp)
{
System.out.println("Exception in DownLoadImageInAThread : " + exp.getMessage());
}
}
private Drawable getDrawableFromUrl(String imageUrl) throws IOException
{
try
{
image = DownloadDrawable(imageUrl, "src");
//bmp = readBitmapFromNetwork(new URL(imageUrl));
}
catch (IOException e)
{
e.printStackTrace();
}
return image;
//return bmp;
}
};
t.start();
}
Drawable DownloadDrawable(String url, String src_name) throws java.io.IOException
{
return Drawable.createFromStream(((java.io.InputStream) new java.net.URL(url).getContent()), src_name);
}

Are you using a ListView? if so, is it possible that the view is already recycled by ListView (reused to display another list item) by the time that you write the image in it?

Problem happens because you have written the code to load the images in getView() method.
And that method get called every time you scroll the list.
So that's a poor and not good idea at all.
Remove that code from there..
Load images and in other thread or AsyncTask
And then call notifyDataSetChanged() of you Adapter class object.
Just steps for what I indicated to do, Please read carefully and try to implement, if cant understand anything feel free to ask..sorry couldnt paste any code snippet..
ListView adapter's getView() method
show default icon if array doesn't contain bitmap at that position
if bitmap is there show bitmap else show default icon
AsyncTask to Load Data
do in background
load data and show in listview
AsyncTask to Load Images
do in background
download images one bye one from the urls got in first AsyncTask
in onPostExecute call adapter's notifyDataSetChanged() to show the bitmaps too
you can also call onProgressUpdate periodically means..after 2-3 image download
call publishProgress in doInBackground which will call onProgressUpdate and
in that method also write adpater.notifyDataSetChanged() to
reflect currently downloaded/available bitmaps in array

Related

Android: Load image on launch from URL

I am a learner and have been working on a home visitor app to get image from a URL of the visitor. Using the following code, which I found online, I was able to load image by adding an intent before the screen and adding a button on the screen saying "See Visitor Image" but now I want that my image should load as soon as the app launches. What changes could I make to do that? Thanks for your help.
OnClickListener getImageBtnOnClick = new OnClickListener() {
public void onClick(View view) {
Context context = view.getContext();
Editable ed = inputUrl.getText();
Drawable image = ImageOperations(context,ed.toString(),"image.jpg");
ImageView imgView = new ImageView(context);
imgView = (ImageView)findViewById(R.id.image1);
imgView.setImageDrawable(image);
}
};
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
inputUrl = ((EditText)findViewById(R.id.imageUrl));
inputUrl.setSingleLine();
inputUrl.setTextSize(11);
Button getImageButton = (Button)findViewById(R.id.getImageButton);
getImageButton.setOnClickListener(getImageBtnOnClick);
}
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
You can make use of SmartImageView, it is a drop-in replacement for Android’s standard ImageView which additionally allows images to be loaded from URLs or the user’s contact address book. Images are cached to memory and to disk for super fast loading.
https://github.com/loopj/android-smart-image-view
Or on OnResume of ur activity start downloading the image form the url as u r doing now in the click listener of button in a separate thread to avoid blocking main UI thread. Once you completed the download you can update the image view using handler from the worker thread.
You can make use of async task also instead of creating your own thread and handler to update UI. for more infor about async task refer following link http://www.vogella.com/articles/AndroidPerformance/article.html

Download images with AsyncTask

I'm not really sure what goes wrong with my code or structure. I wanted to use AsyncTask to download images and display out the progress bar at the mean time. But I tried out a few different way of doing it. It still failed and no idea what's wrong with it. My structure flow is
ContentID is a string array that stores the content ID of the Images.
Primary Issue: It managed to download images from the url and store into the phone, but the downloaded images are all the same image. It should be different images, it's not what I expected.
Secondary Issue: The progress bar pop up while the application downloading images, but the progress bar did not update it's progress. It just remains 0% and dismissed after the download completed.
I wanted to know what causes primary and secodary issue as i mentioned. Please leave a comment or answer if you might know what's wrong with my code. Any help will be appreciated.
if(isSyncSuccess){
SetConstant.IMAGE_EXIST = 1;
pDialog = new ProgressDialog(GalleryScreen.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setProgress(0);
pDialog.setMax(contentId.length);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
if (contentId.length>0){
Log.i(TAG, "contentid.length:" +contentId.length);
for (int i=0;i<contentId.length;i++){
if(helper.databaseChecking(useremail, contentId[i])){
contentdownload = i;
SetConstant.CONTENT_ID = contentId[i];
String URL = SetConstant.URL_DOWNLOAD_CONTENT+contentId[i];
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute(URL);
}
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... sUrl){
Bitmap bm;
InputStream in;
try{
in = new java.net.URL(sUrl[0]).openStream();
bm = BitmapFactory.decodeStream(new PatchInputStream(in));
File storage = new File(Environment.getExternalStorageDirectory() + File.separator + "/Image/");
Log.i(TAG,"storage:" +storage);
Log.i(TAG,"storage:" +storage.getAbsolutePath());
if(!storage.exists()){
storage.mkdirs();
}
String FileName = "/"+SetConstant.CONTENT_ID+".jpg";
FileOutputStream fos = new FileOutputStream(storage + FileName);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);
String filepath = storage + FileName;
File filecheck = new File (filepath);
long fileSize = filecheck.length();
fos.flush();
fos.close();
Log.i(TAG, "bm:" +bm);
Log.i(TAG, "fos:" +fos);
Log.i(TAG, "filesize:" +fileSize);
Log.i(TAG, "filepath:" +filepath);
}
catch(IOException e1){
e1.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress){
super.onProgressUpdate(progress);
pDialog.setProgress(progress[0]);
}
protected void onPostExecute(String result){
super.onPostExecute(result);
pDialog.dismiss();
}
}
Edit
Now the application able to download images according and the progress bar is working as well! But I got another issue is how to return error message when the application failed to complete the download. Currently when the application failed to download it will crash. I believed that I should not run it inside the doInBackground side. But where else can I do the checking? Any idea how to return as an error message and request for the user to retry instead of crashing the application?
You never called onProgressUpdate during your doInBackGround(...). Please note that running multiple instances of AsyncTask is a bad idea. Here is what I suggest:
if(isSyncSuccess){
SetConstant.IMAGE_EXIST=1;
pDialog=new ProgressDialog(GalleryScreen.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setProgress(0);
pDialog.setMax(contentId.length);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
new DownloadFile().execute();
}
private class DownloadFiles extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
Bitmap bm;
InputStream in;
if (contentId.length > 0) {
for (int i = 0; i < contentId.length; i++) {
if (helper.databaseChecking(useremail, contentId[i])) {
contentdownload = i;
SetConstant.CONTENT_ID = contentId[i];
String URL = SetConstant.URL_DOWNLOAD_CONTENT + contentId[i];
//YOUR INTRESTING LOOP HERE.
publishProgress(30);
//SOME INTRESTING NUMBER FOR PROGRESS UPDATE
}
}
try {
in = new java.net.URL(sUrl[0]).openStream();
bm = BitmapFactory.decodeStream(new PatchInputStream(in));
File storage = new File(Environment.getExternalStorageDirectory() + File.separator + "/Image/");
Log.i(TAG, "storage:" + storage);
Log.i(TAG, "storage:" + storage.getAbsolutePath());
if (!storage.exists()) {
storage.mkdirs();
}
String FileName = "/" + SetConstant.CONTENT_ID + ".jpg";
FileOutputStream fos = new FileOutputStream(storage + FileName);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);
String filepath = storage + FileName;
File filecheck = new File(filepath);
long fileSize = filecheck.length();
fos.flush();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute () {
super.onPreExecute();
pDialog.show();
}
#Override
protected void onProgressUpdate (Integer...progress){
super.onProgressUpdate(progress);
pDialog.setProgress(progress[0]);
}
protected void onPostExecute (String result){
super.onPostExecute(result);
pDialog.dismiss();
}
}
}
Of course this code don't run and you need to fix the scopes. But what I am trying to suggest is that your loop should be in doInBackGround(...), you should only have 1 instance of AsyncTask at given time for this case, and call the onProgressUpdate().
Primary issue :
SetConstant.CONTENT_ID = contentId[i];
String URL = SetConstant.URL_DOWNLOAD_CONTENT+contentId[i];
Here, you are facing trouble. As #Sofi Software LLC's answer, you are using a global variable, whose value is being changed by the main thread, in another thread.
Secondary Issue :
If you want a progress bar to update, you have to update its value;
it doesn't update itself.
You do need to download the image in AsyncTask (Downloading from URL). Effectively to achieve your functionality, you need to do
Create AsyncTask to download your image (implement download in
doInBackground()), also have a boolean (say isImageDownloaded) to
track if the image is successfully downloaded in postExecute().
Don't forget to also show your progress bar before initiating the
download
Execute your AsyncTask to initiate download
Create extension of android.os.CountDownTimer to countdown a minimum
time
On the method onFinish() check the boolean that you track, if it is
false then you cancel the AsyncTask and throw the toast/dialog that
you intended
Running multipule instance of AsyncTask is not a good idea, so do one after another. You can execute your AsyncTask's on an Executor using executeOnExecutor().To make sure that the threads are running in a serial fashion please use: SERIAL_EXECUTOR.
Following resources may help you #
If you need to download an image, show progress bar and load in a imageview
https://github.com/koush/UrlImageViewHelper
http://developer.aiwgame.com/imageview-show-image-from-url-on-android-4-0.html
http://blog.blundell-apps.com/imageview-with-loading-spinner/
If you need to download multiple files (here, for images) using AsyncTask
Problem with downloading multiple files using AsyncTask
How to get back the task completion status in AsyncTask
Implement Progress Bar for File Download in Android
EDIT:
From http://developer.aiwgame.com/imageview-show-image-from-url-on-android-4-0.html
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png"); }
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
} }
From Image download in an Android ImageView and Progressbar implementation
// note that you could also use other timer related class in Android aside from this CountDownTimer, I prefer this class because I could do something on every interval basis
// tick every 10 secs (or what you think is necessary)
CountDownTimer timer = new CountDownTimer(30000, 10000) {
#Override
public void onFinish() {
// check the boolean, if it is false, throw toast/dialog
}
#Override
public void onTick(long millisUntilFinished) {
// you could alternatively update anything you want every tick of the interval that you specified
}
};
timer.start()
In the following line:
SetConstant.CONTENT_ID = contentId[i];
You're setting a global variable to a value, then you create a string url based on that same value and pass it to the AsyncTask. That executes, and then when it is done downloading, it create a file whose name is based on the global variable SetConstant.CONTENT_ID.
In other words, you are using a global variable, whose value is being changed by the main thread, in another thread. Don't do this, as you will get all kinds of weird problems due to the different threads updating at different times.. Pass in the value or the name of the output file to the AsyncTask. You can do that in a constructor for DownloadFile, and stash the value in a field.
If you want a progress bar to update, you have to update its value; it doesn't update itself. Call AsyncTask.publishProgress during the task (in doInBackground) and implement onProgressUpdate to update the progress dialog.
[EDIT: onProgressUpdate is indeed called in the UI thread.]
First create a separated class which allows you to reach to image address
like following:
public class ImageDownloader extends AsyncTask {
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Then get access to that class (through a method called by a button) by creating an object and execute the Bitmap task like following :
public class MainActivity extends Activity {
ImageView downloadedImg;
public void downloadImage(View view) {
ImageDownloader task = new ImageDownloader();
Bitmap myImage;
try {
myImage = task.execute("YOUR IMAGE ADDRESS ........").get();
downloadedImg.setImageBitmap(myImage);
} catch (Exception e) {
e.printStackTrace();
}
}
Do NOT forget to:
1 - define the imageView in onCreat method ==> downloadedImg = (ImageView) findViewById(R.id.imageView);
2 - to link the method you've created by a button in user interface ==> (public void downloadImage(View view){})
3 - ask for permission in manifest file

Fetching images from the Server and Display them as Banner in Android

The server is sending a list of urls of images when the application loads.
After parsing the url,The Application is Supposed to fetch that images from the server and display those images as MARQUEE on it's header as a BANNER.
On Clicking on that banner...a link is to be open(Say for example link of any WebSite).
Can Anybody tell me how to fetch this image from the url and Save it temporarily and Display them as Banner.
Regards.
I used this code for loding img form url
ImageView v_thumburl = (ImageView) rowView
.findViewById(R.id.v_thumb_url);
thumburl = temp.getString(temp.getColumnIndex("thumburl"));
Drawable drawable = LoadImageFromWebOperations(thumburl);
v_thumburl.setImageDrawable(drawable);
private Drawable LoadImageFromWebOperations(String url) {
try {
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;
}
}
try this i hope it may help u
Use AsyncTask for downloading images from server (Store them in external storage).
After complete the download display those images in Gallery view as a
Banner. (Put Gallery view in banner).
As Android Gallery doesn't support Marquee, use animation for Gallery
view (Like Marquee).
For Loading Image from The Server you can use LasyList which will fetch the image from server and store it into SD Card.
SlideShow will be better than Marquee, so if you want SlideShow see this
And If you want marquee then what you can so is have and HorizontalListView
Add a public Method in HorizontalListView Class as shown below
public void getScrollWidth() {
return mMaxX;
}
public void getCurrentScrollX() {
return mNextX;
}
and For Marquee have a Thread and a Handler in your class like this.
new Thread(new Runnable() {
#Override
public void run() {
try {
handler.post(new Runnable() {
#Override
public void run() {
if((horizontalListView.getCurrentScrollX() + 50) < horizontalListView.getScrollWidth())
{
horizontalListView.scrollTo(horizontalListView.getCurrentScrollX() + 50);
}
else
{
horizontalListView.scrollTo(0);
}
}
});
Thread.sleep(1000);
} catch (Exception e) {
}
}
}).start();

Loading images from server to Android custom listview when scrolling down the listview

I have a custom listview that contains images and text from the server. If server returns 500+ sets of data I can render all the data to my listview but it will take lots of time to load
Instead I should render the data when list is scrolled down. For this I was return the some code to load the images but still I was not satisfied with this code. I am loading the images from the getView() method by calling manager.fetchBitMapThread(data.getImgUrl(),iv) (ImageLoaderThread). Because of so many threads will create while running. can one suggest the good idea to load the data custom listview.
I have seen OnScrollListener but I am not understanding how to implement this for a custom listview.
manager.fetchBitMapThread(data.getImgUrl(),iv);
public class Manager {
ImageView imageView;
final int stub_id=R.drawable.stub;
private final Map<String, Bitmap> bitMap;
public Manager() {
bitMap = new HashMap<String, Bitmap>();
}
public void fetchBitMapThread(final String urlString, final ImageView imageView) {
this.imageView = imageView;
if (bitMap.containsKey(urlString)) {
imageView.setImageBitmap(bitMap.get(urlString));
}
imageView.setImageResource(stub_id);
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
if(!message.equals(null))
imageView.setImageBitmap((Bitmap) message.obj);
else
imageView.setImageResource(stub_id);
}
};
Thread thread = new Thread() {
#Override
public void run() {
// set imageView to a "pending" image
Bitmap bitM = fetchBitmap(urlString);
Message message = handler.obtainMessage(1, bitM);
handler.sendMessage(message);
}
};
thread.start();
}
public Bitmap fetchBitmap(String urlString) {
if (bitMap.containsKey(urlString)) {
return bitMap.get(urlString);
}
Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
try {
InputStream is = fetch(urlString);
Bitmap drawable = BitmapFactory.decodeStream(is);
if (drawable != null) {
bitMap.put(urlString, drawable);
//Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", " + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", " + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
} else {
//wrong.setImageResource(stub_id);
Log.w(this.getClass().getSimpleName(), "could not get thumbnail");
}
return drawable;
} catch (MalformedURLException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
//imageView.setImageResource(stub_id);
return null;
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
// imageView.setImageResource(stub_id);
return null;
}
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
follow this link to Load images from server in Custom List View.
http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_Example/index.php?view=article_discription&aid=112&aaid=134
Download this and try to implement it in your application.
OnScrollListener provides four arguments which are as below:
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount)
As the name suggests , first one is first item which is visible to you on screen ,second one is total no of items which are visible to you and last one tells you total no of itema list has which is in your case is 500+ . So send request to download the images for those itema/rows which are visible to user . BY ding this first less threads will be created second plus point is images will be downloaded much faster .Use placeholder or progreess bar for image view .
Prepare one map for bitmap images and in key as url value . In get view method check bitmap for particular image view position is downloaded or not using hashmap and set progress bar visibility according to that .
For doing above you cant do simply creating a thread (in anonymous inner class) , Do it efficiently by creating a class extending thread and implement one listener which notifies both ui thread and background for image downloaded or not . It will be something like creating a pipeline of thread asynchronus .
I hope above approach could help you in loading 500+ rows without taking time else doing all images download in asynchronous can lead to Bitmap out of memory exception and its very much time taking too.
Follow this link
http://android-er.blogspot.in/2010/07/load-listview-in-background-asynctask.html
Complete example to load images from server using Async Task and display them in a ListView

problem is in ASyncTask class in Android

basically i am reading image bytes from file i have a loop which has to read almost 20 images from file and in this loop i have making the object of my class which extends ASyncTask class and i am reading bytes and drawing on canvas in doItBackground() method and setting my image on onPostExecute() method. so basically Asynchronously 20 threads starts execution in background. now problem is it is not showing any image.
anybody have any idea how to handle multiple AsyncTask class? here is my code.
#Override
protected Void doInBackground(Void... params)
{
// Log.i("start background thread", "start background thread");
Set<Integer> keys;
keys = iTileListOffsets.keySet();
boolean found = false;
Object key[] = keys.toArray();
int k = 0;
for (int i=0; i < key.length && found==false ; i++)
{
k = (Integer) key[i];
MapTileHeader tileHeader = iTileListOffsets.get(k);
if (tileHeader.equalsWith(mapTile.getiMapTileHeader()) )
{
found = true;
}
}
if(found)
{
try
{
synchronized (MapMaker.getSingletonObject())
{
fc.position(0);
input.skipBytes(k);
int tSizeOfTile = input.readInt();
mapTile.loadTileWithFileHeader(input, tSizeOfTile, headerBytesArray);
}
mapMaker.getBufferedTilesDataList().add(mapTile);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
byte imageTile[] = mapTile.getImageTilesBytes(); //bufferedTile.getImageTilesBytes();
if(mapTile.getImageTilesBytes() != null)
{
try
{
Bitmap tileBitmap = BitmapFactory.decodeByteArray(imageTile, 0, imageTile.length);
canvas.drawBitmap(tileBitmap, rect.left, rect.top, null);
tileBitmap = null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
// Log.i("ENDDDD background thread", "ENDDD background thread");
return null;
}
#Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("start POSTECEXCUTE thread", "start POSTECEXCUTE thread");
MyRect mapRect = aBufferArea.GetScreenRectangle(buffer, aScrnArea);
Bitmap smallBitmap = Bitmap.createBitmap(bitmap, mapRect.left, mapRect.top, mapRect.width, mapRect.height);
image.setImageBitmap(smallBitmap);
Log.i("ENDDDDD POSTECEXCUTE thread", "ENDDDD POSTECEXCUTE thread");
}
thanks
I dont think you can update the UI directly from doInBackground, as the code in this method is run in a backgound thread and does not have direct access to the IU thread. You can update the UI either from onPostExecute or from onProgressUpdate. You can call the latter of these from doInBackground by calling publishProgress.
There is a simple example in the documentation for AsyncTask, and this one is a little more complex.
I'd like to suggest a slightly different way of thinking about the problem. Instead of having a thing in the background which both downloads and draws the bitmaps, you might try making the doInBackground method decode and return the Bitmap, then draw it onto the canvas in onPostExecute. This arrangement should prevent you from having contention on the canvas.
Looking at the code you've posted, the loaded bitmaps get drawn onto canvas. Then bitmap gets displayed in image. I can't see, in the code you posted, anywhere that the loaded bitmaps canvas gets sent to the screen.
It might be worth double-checking that the image you're drawing to has a large enough height and width.

Categories

Resources