How do i download multiple images on android from localhost server? - java

I created an android application to download images from my local server, but i failed to do it. I tried few times but i did not work out. Here is my source code at the exact class i created to do the function i want:
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>(4);
public static final String URL = "http://localhost/img/";
Button load_img;
ImageView imageview;
Bitmap bitmap;
ProgressDialog pDialog;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitor);
load_img = (Button)findViewById(R.id.load);
imageview = (ImageView)findViewById(R.id.img);
load_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadImage().execute(new String[]{URL});
//img.setImageBitmap(bitmapArray.ge);
}
});
}
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Monitor.this);
pDialog.setMessage("Fetching Images ....");
pDialog.show();
}
protected Bitmap doInBackground(String... urls) {
bitmap = null;
for(String url : urls){
bitmap = downloadImage(url);
}
//List<Bitmap> bitmap = new ArrayList<Bitmap>;
// bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
return bitmap;
}
private Bitmap downloadImage(String arg0){
bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try{
stream = getHttpConnection(arg0);
bitmap = BitmapFactory.decodeStream(stream, null,bmOptions);
stream.close();
}catch(Exception e){
e.printStackTrace();
}
bitmapArray.add(bitmap);
return bitmap;
}
protected void onPostExecute(Bitmap result) {
if(result != null){
imageview.setImageBitmap(bitmap);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(Monitor.this,"Failed in downloading the image", Toast.LENGTH_SHORT).show();
}
}
//creating open connection
private InputStream getHttpConnection(String urlString) throws IOException{
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
stream = httpConnection.getInputStream();
}
}catch(Exception e){
e.printStackTrace();
}
return stream;
}
}
}

Related

How to get data from sqlite, and show it using stackwidget?

I want to retrieve url image from sqlite, then convert it to bitmap and show it into stackwidget. When insert url image manually, one by one, it works well. But when i use url image from sqlite, application is force close and my stackwidget doesn't show image.
public class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
...
StackRemoteViewsFactory(Context context) {
mContext = context;
}
#Override
public void onCreate() {
FilmHelper filmHelper = FilmHelper.getInstance(mContext);
filmHelper.open();
}
#Override
public void onDataSetChanged() {
DatabaseHelper databaseHelper;
databaseHelper = new DatabaseHelper(mContext);
SQLiteDatabase databases = databaseHelper.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(databases, "note");
ArrayList<Film> ini = new ArrayList<>();
Cursor c =FilmHelper.database.rawQuery("SELECT * FROM note" , null );
c.moveToFirst();
Film note;
int i;
if (c.getCount() > 0) {
for (i=0; i < count; i++ ) {
do {
note = new Film();
note.setId(c.getInt(c.getColumnIndexOrThrow(_ID)));
note.setPosterPath(c.getString(c.getColumnIndexOrThrow(IMAGE)));
ini.add(note);
try {
URL url = new URL("https://image.tmdb.org/t/p/w600_and_h900_bestv2/" +
ini.get(i).getPosterPath());
Bitmap image = BitmapFactory.decodeStream(url.openStream());
mWidgetItems.add(image);
} catch (IOException e) {
System.out.println(e);
}
c.moveToNext();
} while (!c.isAfterLast());
}
}
c.close();
databases.close();
...
}
you are doing network consuming task like converting url to bitmap inside forloop in main thread.
you can use Asynctask that will download bitmap from url to you in onPostExecute and from that you can add bitmap to mWidgetItems.
class ConvertUrltoBitmap extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public Bitmap doInBackground(String... urls) {
Bitmap map = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection connection =(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
map= BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
protected void onPostExecute(Bitmap bitmap){
try {
mWidgetItems.add(bitmap);
}catch (Exception exception){
exception.printStackTrace();
}
}}

how to fetch data without button click

how to fetch first image without click fetch image button
click to view image
this code work fine but on click fetch image button but i want fetch image with out click fetch images button i want to remove this button
Public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
You can trigger it in onCreate(),but you must not run it on UI thread,for it might be a time-consuming operation.Read Specifying the Code to Run on a Thread to help,
you might add the following block in your onCreate() method:
new Runnable() {
#Override
public void run() {
getAllImages();
}
}.run();

How to get Image from url and store it in Bitmap variable

I am new for android. I Want to get image from url and set into Bitmap variable.I tried so many code but i didn't get.
Here my code:
String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;
ImageDownloaderTask.java
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
Bitmap bImage;
#Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
private Bitmap downloadBitmap(String src) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + src);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
bImage = result;
}
}
Thanks in advance...
Here is code you can use
new DownloadImage().execute("https://www.google.com/intl/en_ALL/images/logo.gif");
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// Do whatever you want to do with the bitmap
}
}
public static Bitmap getBitmapFromURL(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);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
From your code,
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;
you get an empty image because your ImageDownloaderTask not yet finished downloadin the image.
Try updating image on your onPosExecute:
protected void onPostExecute(Bitmap result) {
bImage = result;
// Update image here.
}
Bitmap bmp;
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
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) {
bmp=result
}}
try this,
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
In my opinion its best to create an interface for this:
public interface ImageDownloaderResponse {
void downloadFinished(Bitmap bm);
}
In your ImageDownloaderTask:
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
Bitmap bImage;
public ImageDownloaderResponse delegate = null;
#Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
private Bitmap downloadBitmap(String src) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + src);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
delegate.downloadFinished(result);
}
}
Then let your activity/fragment implement the interface like this:
public class MainActivity extends AppCompatActivity implements ImageDownloaderResponse {
And use your Downloadtask like this:
String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(url);
And add this to your activity/fragment:
#Override
public void downloadFinished(Bitmap bm) {
Bitmap bitmap = bm;
}
Try below code:
URL url = new URL("https://www.google.com/intl/en_ALL/images/logo.gif");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
And add this permission in manifest:
<uses-permission android:name="android.permission.INTERNET" />

Imageloader for displaying the Image in an activity

Check this URL I am USING :: http://54.218.73.244:7006/DescriptionSortedRating/
Images will append with relative path from JSON out put using restaurantIMAGE
EX::
http://54.218.73.244:7006/CopperChimney1.jpg
I am using restaurantIMAGE from JSON
{
"restaurants": [
{
"restaurantID": 4,
"restaurantNAME": "CopperChimney1",
"restaurantIMAGE": "MarkBoulevard1.jpg",
"restaurantDISTANCE": 15,
"restaurantTYPE": "Indian",
"restaurantRATING": 1,
"restaurantPrice": 11,
"restaurantTime": "9am t0 8pm"
},
{
"restaurantID": 1,
"restaurantNAME": "CopperChimney",
"restaurantIMAGE": "CopperChimney.png",
"restaurantDISTANCE": 5,
"restaurantTYPE": "Indian",
"restaurantRATING": 3,
"restaurantPrice": 20,
"restaurantTime": "8pm to 11pm"
},
I am USING IMAGE LOADER
ImageLoader.java
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.temp_img;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
Utils,FileCache,MemoryCache java files are also there
RestaurantDescPhotos.java
public class RestaurantDescPhotos extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7006/DescriptionSortedRating/";
String restaurant_name, cc_res;
ProgressDialog progressDialog;
JSONObject jsonObject;
JSONArray first_array;
ImageLoader imageLoader;
TextView textView;
TextView text;
private SparseArray<String> imagesMap = new SparseArray<String>();
ArrayList<HashMap<String, String>> list_of_images = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurant_desc_photos);
imageLoader=new ImageLoader(RestaurantDescPhotos.this);
progressDialog = new ProgressDialog(RestaurantDescPhotos.this);
new ParsingAsync().execute();
}
private class ParsingAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(RestaurantDescPhotos.this, "",
"Please Wait", true, false);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String _response = null;
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet(url);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
jsonObject = new JSONObject(_response);
first_array = jsonObject.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
// TextView timedisplay=(TextView)
// findViewById(R.id.RestaurantTimeID);
for (int i = 0; i < first_array.length(); i++) {
try {
JSONObject detail_obj = first_array.getJSONObject(i);
HashMap<String, String> map_for_images = new HashMap<String, String>();
int id = detail_obj.getInt("_id");
String IMAGES = "http://54.218.73.244:7006/"+detail_obj.getString("restaurantIMAGE");
map_for_images.put("Starters", IMAGES);
list_of_images.add(map_for_images);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageView imageView = (ImageView) findViewById(R.id.DISP_IMG);
imageLoader.DisplayImage(url, imageView);
}
}
}
I am facing the problems in setting the images onto image view using image loader
There is some problem in RestaurantDescPhotos.java ... I am not able to figure it out
Any Ideas
The url content is not a valid image url:
imageLoader.DisplayImage(url, imageView);
I tried a fixed image url, and image is loaded successfully:
String path = "http://54.218.73.244:7006/CopperChimney1.jpg";
imageLoader.DisplayImage(path, imageView);

Downloading and displaying images from an array of URLs to multiple different ImageViews on Android

I have this code to download a photo from a URL and display it in an ImageView on Android.
I am not sure how to loop this if I had a ArrayList or Array of multiple Urls to download and display on different ImageViews. I would appreciate any help or insight on how to proceed! Thank you!
public class DisplayPhotoTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
//sets bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
ImageView imageView1 = (ImageView) findViewById(R.id.imageView);
imageView1.setImageBitmap(result);
}
//creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
//makes httpurlconnection and returns inputstream
private InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
You can for example make a result of AsyncTask as List ant write something like this
protected Bitmap doInBackground(String... urls) {
List<Bitmap> bitmaps = new ArrayList<Bitmap>;
for (String url : urls) {
bitmaps.add(downloadImage(url));
}
return bitmaps;
}
protected void onPostExecute(List<Bitmap> result) {
//...
}
But what I really would recommend you is to use Volley library written by Google, it has really easy and powerful API (here is Google I/O session about it https://developers.google.com/live/shows/474338138 and repository https://android.googlesource.com/platform/frameworks/volley/)

Categories