ImageView not updating with bitmap? - android

why my imageview is not updating in the for loop,only the image from last url is showing in the imageview not all the images,what i am doing wrong?
public class LoadImageActivity extends Activity {
ImageView image_view;
Bitmap bitmap;
String[] imageLocation={
"http://wallbase1.org/thumbs/rozne/thumb-499842.jpg",
"http://ns3002439.ovh.net/thumbs/rozne/thumb-2493796.jpg",
"http://ns3002439.ovh.net/thumbs/rozne/thumb-2486664.jpg" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image_view = (ImageView)findViewById(R.id.imageview);
for (int i = 0; i < 2; i++) {
bitmap = loadImage(imageLocation[i]);
image_view.setImageBitmap(bitmap);
Animation rotate = AnimationUtils.loadAnimation(LoadImageActivity.this, R.anim.rotate);
findViewById(R.id.imageview).startAnimation(rotate);
}
}
public Bitmap loadImage(String image_location){
URL imageURL = null;
try {
imageURL = new URL(image_location);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = HttpURLConnection)imageURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}

Well, at first, how slow is you device that you would switch between images in two successing lines of code (effectively)?
Secondly, the system has to be layouted first which happens after onCreate() returns. What you did is:
-set reference to bitmap that will be shown when layouted
-changed that reference
-let the system do the layout (Question: Which reference will be read?)
It looks like you want to set the first bitmap, rotate it and then set the other bitmap.
What you need to do is:
-set bitmap
-start animation with an Animation.AnimationListener, which sets the second bitmap in onAnimationEnd().
#Thanks to Adam!

You can put an Animation.AnimationListener on your first animation, and you can load the next image and start the new transition in the onAnimationEnd(...) method of the listener.

Try setting the underlying object (Bitmap) and then updating the ImageView.

The method loadImage() is not in UI main Thread, use a Handler to update the ImageView with your new image.

Related

Android imageview flickering

In my app I have list view and each item in the list contains an Image view. The image is loaded from bitmap using
imageView.setImageBitmap(bitmap);
For handling concurrency i am using the method described in the following official documentation.
Processing Bitmaps Off the UI Thread
On high density devices the image view flickers. Any possible solution for this problem?
when i use handle concurrency then only the flickering happens and when i am using asynctask only then there is no flickering
Use Picasso , Picasso saves you all the problems with downloading, setting and caching images. The whole code needed for a simple example is:
Just use like this (from UI Thread) :
In listview , use this in getView() , it handles caching and else..
Picasso.with(context)
.load(url)
.into(imageView);
http://square.github.io/picasso/
or
ImageView tre = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...sdsdsd ...";
mChart.setTag(URL);
new DownloadImage.execute(tre);
public class DownloadImage extends AsyncTask<ImageView, Void,Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}

Running code from another class

hi I'm new to android programming and I'm creating an app that part of it generate Qrcode by using The Zxing library
I created a class with a method Encode contains block of code that generate the qrcode
public void Encode(String Text_To_Encode )
{
final ImageView imageView = (ImageView) findViewById(R.id.QrImageView);
String qrData = "Ahmed";
int qrCodeDimention = 500;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimention);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
Whenever I call this method in Oncreate() method in MainActivity the app Unfortunately has stopped
but when I take this block of code and run it directly in the MainActivity it runs perfectly
I need to know what I do wrong ....
From normal class use Activity context to access views :
public void Encode(String Text_To_Encode,Activity activity )
{
final ImageView imageView =
(ImageView)activity.findViewById(R.id.QrImageView);
.....
}
From Activity call Encode method by passing Activity context:
Encode(Text_To_Encode,ActivityName.this)
Your problem is in this line of code: final ImageView imageView = (ImageView) findViewById(R.id.QrImageView);
You see, you're trying to modify ONE SPECIFIC ImageView. That ImageView belongs to an Activity or Fragment, not to the Application. When you call that method in any Activity or Fragment that R.id.QrImageView does not exist, it will crash because it can't find the ImageView (which is because that ImageView is out-of-scope).
To solve this problem, I would improve your code by RETURNING THE BITMAP in the method.
To be clear, your method should look like this:
public Bitmap Encode(String Text_To_Encode )
{
String qrData = "Ahmed";
int qrCodeDimention = 500;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimention);
try {
return qrCodeEncoder.encodeAsBitmap();
} catch (WriterException e) {
e.printStackTrace();
}
}
Now, in your Activity or Fragment, simply use imageView.setImageBitmap(qrClass.encode(String textToEncode));

Android - Load image from URL not working

please help me with these code, It doesn't show image from URL.
And another question, how to debug each functions such as "url.openConnection", "getInputStream".... to confirm they work well or not?
Thank you
public class MainActivity extends Activity {
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainlayout);
// ImageView
ImageView imgView = new ImageView(this);
mainLayout.addView(imgView);
bitmap = loadImage("https://www.google.com.vn/logos/doodles/2014/dian-fosseys-82nd-birthday-5702250374627328-hp.jpg");
imgView.setImageBitmap(bitmap);
}
public Bitmap loadImage(String src)
{
try
{
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
input.close();
return myBitmap;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
The problem is that you are doing network communications on the main thread, and assuredly getting a NetworkOnMainThreadException because of it.
While you could implement an AsyncTask to manage your network calls, I would strongly suggest using a networking-capable image library to do all the grunt work for you.
https://github.com/nostra13/Android-Universal-Image-Loader
Probably a good idea to choose ImageLoader library rather than doing all this nitty gritty stuff yourself. It is not optimised and error prone too.

why my animations are not proper and image loading is taking more time in some of the images?

public class LoadImageActivity extends Activity {
ImageView image_view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image_view = (ImageView)findViewById(R.id.imageview);
me m1=new me();
m1.execute("http://wallbase1.org/thumbs/rozne/thumb-499842.jpg");
me m2=new me();
m2.execute( "http://wallbase1.org/thumbs/rozne/thumb-637449.jpg");
me m3=new me();
m3.execute( "http://wallbase1.org/thumbs/rozne/thumb-2509834.jpg");
me m4=new me();
m4.execute( "http://wallbase1.org/thumbs/rozne/thumb-2501884.jpg");
me m5=new me();
m5.execute( "http://wallbase1.org/thumbs/rozne/thumb-2514440.jpg");
};
class me extends AsyncTask<String, Integer, Bitmap> {
Bitmap b1;
// private MainActivity m1;
protected Bitmap doInBackground(String...params) {
// TODO Auto-generated method stub
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(params[0]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
b1=bm;
bis.close();
is.close();
} catch (IOException e)
{
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
image_view.setImageBitmap(b1);
Animation rotation = AnimationUtils.loadAnimation(LoadImageActivity.this, R.anim.rotate);
image_view.startAnimation(rotation);
}
}}
I am trying to show an image from internet by decoding it into bitmap,i want to show multiple images from multiple urls.Is there any better way of implementing it?
The duration of a download depends on a lot of different stuff. You currently spawn 5 AsyncTasks and there is no guarantee that the order of delivery/execution will be the same order you spawned them. It is easily possible that the fifth image might be the first you received and this would result in a totally wrong order. So you should download all images first, possibly with just one AsyncTask. After that and if that succeeded, you should start the animation and switch between the images.
There're several better ways of doing it and all of them are far more complex than your code. But you do have a good start.
This video form Google I/O have some good techniques for image, check around 4:40 https://www.youtube.com/watch?v=gbQb1PVjfqM
It takes different times because they are different images with probably different sizes.
Please post your XML R.anim.rotate code so someone can try to check why the animation is not working.

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

Categories

Resources