how to load 4 images from url in android? - android

I want to load four images in four imageview in android
I try this code and it is run vary good
but it is load one image>>>>>>>>
How can I do to load 4 images>> I think I need to use array but how??
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadImage().execute("https://pbs.twimg.com/profile_images/630285593268752384/iD1MkFQ0.png");
}
});
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
b1.setImageBitmap(image);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}

Use one of the ready made libraries... they have async loading, resizing, loading into target to get bitmap... no need to reinvent the wheel (unless it's for study purposes). You can use Picasso, Glide, Fresco... you choose. There is plenty documentation available. Loading is done asynchronously. So you can send multiple requests with multiple urls.

Related

Saving image from URL using Picasso without change in size (using bitmap.compress() changes size)

I am using Picasso for my image handling and use it to download images from a backend server and save to the local device. I use Target to save the image
Picasso.with(context)
.load(url)
.into(target);
Since the target code gets a bitmap, I have to use bitmap.compress() to write the image to local disk and I use JPEF format with quality of 100 assuming this will preserve the original quality.
Reading this it seems like this might not be what I want. In one case, the image on the backend was 90kb and the image that was written was 370kb. The original image can be generated using an arbitrary quality value. What is the easiest way to save the image using Picasso without the size/quality changing?
Target target = new Target() {
#Override
public void onPrepareLoad(Drawable arg0) {
}
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom arg1) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
FileOutputStream out = null;
try {
out = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void info) {
}
}.execute();
}
#Override
public void onBitmapFailed(Drawable arg0) {
}
};
UPDATE: more elegant solution here: https://github.com/square/picasso/issues/1025#issuecomment-102661647
Solved the problem using this solution.
In my PagerAdapter's instantiateItem() method, I run an AsyncTask that will download the image, save it to a file and then call Picasso with that image file.
PagerAdapter instantiateItem():
RemoteImageToImageViewAsyncTask remoteImageToImageViewAsyncTask =
new RemoteImageToImageViewAsyncTask(imageView, url, imagePath);
remoteImageToImageViewAsyncTask.execute();
RemoteImageToImageViewAsyncTask
public class RemoteImageToImageViewAsyncTask extends AsyncTask<Void, Void, Void> {
ImageView imageView;
String url;
File output;
public RemoteImageToImageViewAsyncTask(ImageView imageView, String url, File output) {
this.imageView = imageView;
this.url = url;
this.output = output;
}
#Override
protected Void doInBackground(Void... params) {
// Downloads the image from url to output
ImageDownloader.download(url, output);
return null;
}
#Override
protected void onPostExecute(Void params) {
Picasso.with(context)
.load(output)
.into(imageView);
}
}

Android Error loading image view

I am trying to load an image in my imageview but it does not load any image for the link.
The link has the image but I still get empty blank space.
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
String url = "http://www.learn2crack.com/wp-content/uploads/2014/04/node-cover-720x340.png";
URL urlurl = new URL(url);
bitmap = BitmapFactory.decodeStream(urlurl.openConnection().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}else{
Toast.makeText(activity.getApplicationContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
XML
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip"
/>
As you can see in the logcat stacktrace you have a network on mainthread exception becasue you are doing a network task on the 'main' thread which is also called the gui thread. You need to use an AsyncTask for this.
private class DownloadImageTask extends AsyncTask<Object, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Object... args) {
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
}
#Override
protected void onPostExecute(Bitmap result) {
//here do stuff with your bitmap data, also here you can interact with the gui
}
}
Also I recommend using an Image downloading library to download images off the web. They make it really easy to download images and you dont have to worry a lot about the tiny details.

How can i send mulltiple images at once to server?

i need to send three images at once to server, currently i can send one image by following code(PictureId). If i need to send three images say Picture1Id, Picture2Id, Picture3Id how can set in (protected Void doInBackground(Void... params) {})
// IMAGE UPLOAD ///////////
final ProgressDialog progress = new ProgressDialog(NBCompetitorTracking_Activity.this);
progress.setMessage("Uploading image, please wait...");
// If auto upload true upload picture:
if (new SessionManager(NBCompetitorTracking_Activity.this).isAutoUpload()) {
// upload image
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
UploadImage.uploadImage(NB_CompetitorTracking.**PictureId**);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
}
};
}
// END: IMAGE UPLOAD ///////////
Start multiple Thread instances of the 'upload thread' with separate files to be uploaded.Purely upon java concept, You can write a Thread class that uploads a file. And initiate many instances(as much as the files) and start them all together.

View Images From Url and Place in ImageView when User selects

Am develop the Frame application. For that i want to display images(frames) from url. the url has more than 50 images. For that i use gridview but it lacks some points such as,
1.It speeds very slow to load images.
2.We declare the name and size of the images at code time so that we dont add images to the url after publishing the applicaton.
I need solution for these asap. Please anyone give me suggestion.
Use below link of lazy loading listview, this will help you.
Lazy Loading ListView
Use Above link Code and Add another activity and another layout for display selected image, if u have any issue than tell me, i will put full code here.
1.It speeds very slow to load images.
It will depend on You bandwidth and device Cache.
2. We declare the name and size of the images at code time so that we dont add images to the url after publishing the application.
You can have predefine URL so at code time you can append the image name to url.and once you have URL ready using AsyncTask download images one by one \
The below snippets will help you.
DownloadHelper.java
public interface DownloadHelper
{
public void OnSucess(Bitmap bitmap);
public void OnFailure(String response);
}
MainActivity.java
public class GalleryExample extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
DownloadHelper downloadHelper = new DownloadHelper()
{
#Override
public void OnSucess(Bitmap bitmap)
{
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
}
#Override
public void OnFailure(String response)
{
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
};
new MyTask(this,downloadHelper).execute("image url");
}
MyTask.java
public class DownloadTask extends AsyncTask<String, Integer, Object>
{
private Context context;
private DownloadHelper downloadHelper;
private ProgressDialog dialog;
public DownloadTask(Context context,DownloadHelper downloadHelper)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(context);
dialog.setTitle("Please Wait");
dialog.setMessage("Fetching Data!!");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected Object doInBackground(String... params)
{
URL aURL = new URL(myRemoteImages[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
}
#Override
protected void onPostExecute(Object result)
{
dialog.dismiss();
if (result != null)
{
downloadHelper.OnSucess((Bitmap)result);
}
else
{
downloadHelper.OnFailure("Error in Downloading Data!!");
}
super.onPostExecute(result);
}
}

AsyncTask not stopping while loading images.

This is my AsyncTask, called from getView of an adapter:
class LoadImage extends AsyncTask<Object,Void,String>{
private ImageView imv;
private String path;
public LoadImage(ImageView imv) {
this.imv = imv;
}
Bitmap userAvatarStream = null ;
Bitmap IconStream = null;
URL IconURL;
ProgressDialog dialog;
#Override
protected void onPreExecute(){
//Setting all the variables by getting the ids from the layout
return;
}
#Override
protected String doInBackground(Object... params) {
try {
IconURL = new URL(cr.ImageUrl);
IconStream = BitmapFactory.decodeStream(IconURL.openConnection().getInputStream());
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
// ImageView user_avatar = (ImageView)v.findViewById(R.id.follower_user_avatar);
imv.setImageBitmap(IconStream);
return;
}
The problem that I get here is that the images keep loading. Lets say I scroll down and the images go away to be refreshed again if I scroll up the list. It keeps making calls to get the images. This behaviour is obviously undesirable except at one place that if the internet on your cell-phone goes down and comes up again, this would help to auto-load the images. But, in the current state even that is crashing as it keeps making calls. How to stop AsyncTask from doing that?
Just cache you images to filesystem or memory.
Each time you scroll the list getView is called. If you put the image loading method on getView and didn't use Image Caching then it'll download the images again and again. There are some opensource image loader for list with caching support.
One of them is droidFu. It supports two level of caching. Filesystem and memory. Get droidFu from following link.
https://github.com/kaeppler/droid-fu
Try a boolean flag to keep the check whether the image was loaded successfully or not.
If it was not then only make a call to Load Image Asynctask.
You may need to use a boolean array to keep the track if there are more than one row in adapter.
Try this code:
class performBackgroundTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Please wait ...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... arg0) {
callxmlparser();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (ringtoneNamelist != null && ringtoneNamelist.size() > 0) {
songslist.setAdapter(new Songslist());
} else {
Toast.makeText(SongsList.this,"Network signal speed is too slow\ncannot parse the data from the server\n Please try again", Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
}

Categories

Resources