How to use Online Images URLs in place of Drawable Images - android

In my program i am using local images, but now i want to use online images instead of Drawable
But i don't know what are the changes i have to implement in my code, to get my target done for me.
here is my code, which i am using for drawable images, see:
public int[] IMAGE_IDS = {
R.drawable.flower_01, R.drawable.flower_02,
R.drawable.flower_01, R.drawable.flower_02,
R.drawable.flower_01, R.drawable.flower_02,
R.drawable.flower_01, R.drawable.flower_02
};
And Adapter class, complete code looks like this:
public class AddImageAdapter extends BaseAdapter
{
Context mycontext = null;
int galitembg = 0;
public int[] IMAGE_IDS = {
R.drawable.flower_01, R.drawable.flower_02,
R.drawable.flower_01, R.drawable.flower_02,
R.drawable.flower_01, R.drawable.flower_02,
R.drawable.flower_01, R.drawable.flower_02
};
public AddImageAdapter(Context c)
{
mycontext = c;
TypedArray typArray = mycontext.obtainStyledAttributes(R.styleable.GalleryTheme);
galitembg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
#Override
public int getCount()
{
return IMAGE_IDS.length;
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageview = new ImageView(mycontext);
imageview.setImageResource(IMAGE_IDS[position]);
imageview.setScaleType(ImageView.ScaleType.FIT_XY);
return imageview;
}
}
I wanna use these two live images URLs in place of drawable
URL-1: http://files.vividscreen.com/soft/4f9891a78a355e9c4d15fc469eb98625/Sunflowers-480x800.jpg
URL-2: http://www.hdiphonewallpapers.us/phone-wallpapers/freewallpaper/12960425OV940-3Q61.jpg

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);
}
}
You can download images from url using this method and set it in imageview. you just need the internet permission to download the images

You can use this library Picasso. This library download images from a url and disk cached also many more options.
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
How to use:
How to use Picasso

Related

Load GridView Bitmaps in Asynctask

is it possible to load the Thumbnails of a GridView in an Asynctask, to prevent lags on scrolling the GridView?
That's the code of my Asynctask:
#SuppressLint("StaticFieldLeak")
public class AsyncTaskLoadFiles2 extends AsyncTask<Void, String, Void> {
File targetDirector;
public AsyncTaskLoadFiles2(ImageAdapter2 adapter) {
myTaskAdapter2 = adapter;
}
#Override
protected void onPreExecute() {
String targetPath = "/sdcard/Android/data/de.myapps.gridtest/files/Download/.Videos";
targetDirector = new File(targetPath);
myTaskAdapter2.clear2();
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading Videos, please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
File[] files = targetDirector.listFiles();
for (File file : files) {
publishProgress(file.getAbsolutePath());
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (isCancelled()) break;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
myTaskAdapter2.add2(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
myTaskAdapter2.notifyDataSetChanged();
progressDialog.dismiss();
super.onPostExecute(result);
}
}
And here's the code of my ImageAdapter:
public class ImageAdapter2 extends BaseAdapter {
private Context mContext;
ArrayList<String> itemList = new ArrayList<String>();
public ImageAdapter2(Context c) {
mContext = c;
}
void add2(String path) {
itemList.add(path);
}
void clear2() {
itemList.clear();
}
void remove2(int index) {
itemList.remove(index);
}
public String getPath(int position) {
return itemList.get(position);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#SuppressLint("ResourceType")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 420));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
imageView = (ImageView) convertView;
}
thumbnail = ThumbnailUtils.createVideoThumbnail(getPath(position),
MediaStore.Images.Thumbnails.MICRO_KIND);
// Set the decoded bitmap into ImageView
imageView.setImageBitmap(thumbnail);
return imageView;
}
}
So what I would like to know is if it is possible to load the thumbnail Bitmap in the Asynctask, because with this code the app lags. (I'm using a TabbedActivity so all this code is part of a Fragment)
Have a look at
https://developer.android.com/topic/performance/graphics/cache-bitmap
BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
task.execute(resId);
You can create an AsyncTask that loads the image into the ImageView
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
...
// Decode image in background.
#Override
protected Bitmap doInBackground(Integer... params) {
final Bitmap bitmap = decodeSampledBitmapFromResource(getResources(), params[0], 100, 100));
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if(result != null) {
myImgView.setImageBitmap(result);
}
}
}
You just call BitmapWorkerTask.Execute with parameters in the constructor from the getView() method in your adapter.
BitmapWorkerTask task = new BitmapWorkerTask(imageView, filePath);
Make the constructor
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private ImageView imageView;
private String filePath;
public BitmapWorkerTask(ImageView imageView, String filePath) {
this.imageView = imageView;
this.filePath = filePath;
}
....
//Get your bitmap
//Set Bitmap onPostExecute

Images are reloading when scrolling listView in Android

I have a listView where I put a Title and a description with a picture and the pictures reloads when I scroll up, how could I resolve this problem? I tried some solutions but they failed...
Here is my code:
GETVIEW
public class ViewHolder extends ArrayAdapter<ListViewModel> {
public ViewHolder(Context context, List<ListViewModel> model) {
super(context, 0, model);
}
#Override
public View getView(int position, View cView, ViewGroup parent) {
if(cView == null){
cView = LayoutInflater.from(getContext()).inflate(R.layout.view_list_holder,parent, false);
}
ListViewHolder viewHold = (ListViewHolder) cView.getTag();
if(viewHold == null){
viewHold = new ListViewHolder();
viewHold.title = (TextView) cView.findViewById(R.id.title);
viewHold.content = (TextView) cView.findViewById(R.id.content);
viewHold.picture = (ImageView) cView.findViewById(R.id.picture);
cView.setTag(viewHold);
}
ListViewModel model = getItem(position);
viewHold.title.setText(model.getTitle());
viewHold.content.setText(model.getContent());
if (viewHold.picture != null)
new DownloadImageTask(viewHold.picture).execute(model.getPicture());
return cView;
}
private class ListViewHolder{
public TextView title;
public TextView content;
public ImageView picture;
}
}
ImageDownloader
public 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 myImage = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
myImage = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return myImage;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Try using Volley instead of AsyncTask:
http://developer.android.com/training/volley/request.html
It has built in support for image caching as well as cancelling requests if a particular set of images are no longer needed if the user has scrolled away.
Could you not just save the images in a bitmap array in the activity? Then just display those. Therefore they never reload, they are just in activity to be used in the view?

Android load images into viewpager from web

I am loading images from drawable but it is not effective now i want to load images from web but i am stucked. I realy search for solutions but i cant success.
There is my Custom Adapter class:
int[] imageId = {R.drawable.first, R.drawable.second, R.drawable.third, R.drawable.fourth, R.drawable.fifth};
public Object instantiateItem(ViewGroup container, int position) {
global_position=position;
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
View viewItem = inflater.inflate(R.layout.image_item, container, false);
imageView = (ImageView) viewItem.findViewById(R.id.imageView);
imageView.setImageResource(imageId[position]);
((ViewPager)container).addView(viewItem);
return viewItem;
}
How can a turn this it can download images from web and load view pager.
You can use an AsyncTask to do that job without crashing your app.
class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView myImage //your image url;
public DownloadImageTask(ImageView myImage) {
this.myImage = myImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
To use this class just instanciate it like the others.
new DownloadImageTask((ImageView) findViewById(R.id.your_image_viewer))
.execute(imageURL);

fetching multiple image from urls

I have an application which allow to download 3 images and show them into a gallery
In order to do this , i use a thread in order to download the images and a handler in order to put the images into the gallery
The problem is that the images are not displayed(imageviews are empty) into the gallery (even if i see 3 imageview for my 3 images)
I do not know if this is because the connection is very slow (I develop on a mobile) or if it's because the ui is displayed before images are downloaded
Thank you very much for your help
public class ChoiceLanguage extends Activity {
private TextView nomLangue;
private ArrayList<Language> listeLangues;
private ArrayList<String> listImages;
private Gallery gallery;
private String URL="******************";
private Drawable mNoImage;
Bitmap bitmap;
ImageView imgView = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choice_language);
listeLangues= getIntent().getParcelableArrayListExtra("listeLangues");
listImages=buildListImages();
gallery = (Gallery) findViewById(R.id.galleryImg);
gallery.setAdapter(new AddImgAdp(this));
gallery.setSpacing(10);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
System.out.println("URL "+ listImages.get(position) );
}
});
}
private InputStream openHttpConnection(String urlString) throws IOException {
InputStream in = null;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
in=conn.getInputStream();
return in;
}
private Bitmap downloadImage( ImageView iView, String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedInputStream bis ;
try {
in = openHttpConnection(url);
bis= new BufferedInputStream(in, 8192);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
private ArrayList<String> buildListImages() {
ArrayList<String> listImg = new ArrayList<String>();
for(Language l : listeLangues) {
listImg.add(URL+l.getImagePath());
}
return listImg;
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return listImages.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imgView = new ImageView(cont);
} else {
imgView = (ImageView)convertView;
}
ThreadDownload progressDl= new ThreadDownload(position);
progressDl.start();
imgView.setLayoutParams(new Gallery.LayoutParams(150, 150));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
private class SetImg extends Handler {
public void handleMessage(Message msg) {
imgView.setImageBitmap(bitmap);
}
}
private class ThreadDownload extends Thread {
SetImg img= new SetImg();
int position ;
public ThreadDownload(int position)
{
super();
this.position=position;
}
public void run() {
bitmap = downloadImage(imgView,listImages.get(position));
img.sendEmptyMessage(0);
}
}
}
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

Gridview get image from JSON using AsyncTask

This project I've done with image in my drawable but now I want to get image url from JSON by using Asynctask and display it. and I make php that provide a json string like below.
I want to get path of image(url) by using AsyncTask from JSON.
I want to use data from json instead of public mThumbId = {...};
{"count":"28","data":
[{"id":"1",
"first_name":"man",
"last_name":"woman",
"username":"man",
"password":"4f70432e636970de9929bcc6f1b72412",
"email":"man#gmail.com",
"url":"http://vulcan.wr.usgs.gov/Imgs/Jpg/MSH/Images/MSH64_aerial_view_st_helens_from_NE_09-64_med.jpg"},
{"id":"2",
"first_name":"first",
"last_name":"Last Name",
"username":"user",
"password":"1a1dc91c907325c69271ddf0c944bc72",
"email":"first#gmail.com",
"url":"http://www.danheller.com/images/California/Marin/Scenics/bird-view-big.jpg"},
{"id":"3",
"first_name":"first",
"last_name":"Last Name",
"username":"user",
"password":"1a1dc91c907325c69271ddf0c944bc72",
"email":"0",
"url":"http://www.hermes.net.au/bodhi/images/view/large/view_03.jpg"}]}
AndroidGridLayoutActivity
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.pic_1, R.drawable.pic_2,
R.drawable.pic_3, R.drawable.pic_4,
R.drawable.pic_5, R.drawable.pic_6,
R.drawable.pic_7, R.drawable.pic_8,
R.drawable.pic_9, R.drawable.pic_10,
R.drawable.pic_11, R.drawable.pic_12,
R.drawable.pic_13, R.drawable.pic_14,
R.drawable.pic_15
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
FullImageActivity
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
I think that this simple link will totally answer your question:
https://github.com/novoda/ImageLoader
And my own implementation:
https://github.com/iRail/BeTrains-for-Android/blob/master/src/tof/cv/mpp/adapter/TweetItemAdapter.java
EDIT
What you really need to do:
1) Parse JSON: there are thousands of tutorials on the web, or use the awesome GSON library.
2) Once JSON is parsed, you will get an array of objects.
3) In your Adapter, you will maybe need to extend ArrayAdapter.
4) in the getView() method, analyse my 2 above links and use something like:
imageLoader.DisplayImage(tweet.profile_image_url, activity, holder.image);
You have to first extract the urls from json in a array and then use below code to load image as bitmap dynamically using Async Task.
Bitmap bm[]=new Bitmap[3];
ImageAdapter img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bm[0]=null;
bm[1]=null;
bm[2]=null;
InputStream is= getDataFromServer();
String asd=getResponseFromStream(is);
try {
JSONObject jsn=new JSONObject(asd);
JSONArray jd=jsn.getJSONArray("data");
for(int i=0;i<jd.length();i++)
{
JSONObject j_object=jd.getJSONObject(i);
String url=j_object.getString("url");
urls.add(url);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
img=new ImageAdapter(this);
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(img);
new ImageDownloader().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
ProgressDialog prg;
private class ImageDownloader extends AsyncTask<Integer, Integer, String>
{
#Override
public void onPreExecute()
{
prg=ProgressDialog.show(LazyLoadActivity.this, null,
"Loading...");
}
protected void onPostExecute(String result)
{
prg.hide();
}
protected void onProgressUpdate(Integer... progress) {
img.notifyDataSetChanged();
}
protected String doInBackground(Integer... a)
{
for(int i=0;i<3;i++)
{
bm[i]=downloadBitmap(urls[i]);
this.publishProgress(i);
}
return "";
}
}
public Integer[] mThumbIds = {
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher
};
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
if(bm[position]==null)
imageView.setImageResource(mThumbIds[position]);
else
imageView.setImageBitmap(bm[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
Bitmap downloadBitmap(String url) {
final HttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.e("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
//client.
}
}
return null;
}

Categories

Resources