I'm new to android, I work on an app. I want to download an image and show it in list item. I used many functions for that. My code runs without error but image doesn't display on screen that's part of my code.
public loader(Context context, String[] img) {
super(context, R.layout.item, img);
this.context = context;
this.img = img;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// ImageView imgshow = (ImageView) findViewById(R.id.image1);
if (null == convertView) {
convertView = inflater.inflate(R.layout.item, parent, false);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.imageview);
//first method
// Glide.with(context)
// .load(img[position])
//.into(imageView);
//second method
DownloadImageTask download=new DownloadImageTask((ImageView) convertView.findViewById(R.id.imageview));
download.execute("http://previews.123rf.com/images/faysalfarhan/faysalfarhan1402/faysalfarhan140200008/25989999-Back-left-arrow-icon-glossy-purple-button-Stock-Photo.jpg");
//new DownloadImageTask((ImageView) convertView.findViewById(R.id.imageview))
//.execute(img[position]);
//third method
//Picasso.with(context).load(img[position]).into(imageView);
//Log.e("image_url","https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Square_200x200.svg/1024px-Square_200x200.svg.png");
return convertView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
TextView t;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = "http://previews.123rf.com/images/faysalfarhan/faysalfarhan1402/faysalfarhan140200008/25989999-Back-left-arrow-icon-glossy-purple-button-Stock-Photo.jpg";
Bitmap mIcon11 = null;
// Toast.makeText(mainpage.this ,urldisplay ,Toast.LENGTH_SHORT).show();
TextView t=(TextView)findViewById(R.id.texttt);
// t.setText(urldisplay);
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);
}
}
}
I put that in my list using (img is array of strings I save urls in it and display them but for testing I replace it by one image url inside loader class)
String[] img = new String[1000];
loader im=new loader(mainpage.this,img);
lv.setAdapter(im);
you can't set image in ImageView directly. you have to convert that image in Bitmap and then set
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
and then set to imageview :
imageView.setImageBitmap(getBitmapFromURL(url));
try this hope it helps you
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Use piccasso.
To use piccasso to add it add
compile 'com.squareup.picasso:picasso:2.5.2'
To your app level gradle. And
use this
Picasso.with(context).load("http://previews.123rf.com/images/faysalfarhan/faysalfarhan1402/faysalfarhan140200008/25989999-Back-left-arrow-icon-glossy-purple-button-Stock-Photo.jpg").into(imageview);
or maybe your getCount() method is returning 0. (or add it) change it to
#Override
public int getCount() {
return img.length;
}
Use Glide
dependency for glide: compile 'com.github.bumptech.glide:glide:3.7.0'
and add the code
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load("https://s3-us-west-1.amazonaws.com/powr/defaults/image-slider2.jpg").into(imageView);
Related
I have created a listview with a custom adapter. One of the fields is an image to show the avatar of each user. I must obtain those images from an url.
I have created a class that converts an image from URL into a Bitmap.
I think this should be done from an asyntask. The problem is that I do not know how to call this method from a custom adapter.
This is my class:
private class obtAvatar2 extends AsyncTask<Void , Void, Bitmap>{
Bitmap bm;
#Override
protected Bitmap doInBackground(Void... voids) {
try {
URL url = new URL("https://www.bellatores.cl/wp-content/uploads/2018/01/Avatar-Mujer.png");
URLConnection con = url.openConnection();
con.connect();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
}catch (IOException e){
}
return bm;
}
}
This return a Bitmap.
Then from my custom adapter, i need to put that Bitmap in a ImageView
for example, i'm trying:
ImageView avatarView = (ImageView)view.findViewById(R.id.imageViewAvatarMensa);
avatarView.setImageBitmap(new obtAvatar2().execute());
But, it's wrong :(
any advice?
I suggest to you to either work with Glide or Picasso libaries, they are the most used image library on android application :
To import to you project with gradle :
PICASSO :
dependencies {
compile 'com.squareup.picasso:picasso:2.5.1'
}
GLIDE :
dependencies {
compile 'com.github.bumptech.glide:glide:3.5.2'
}
Usage :
PICASSO :
Picasso.with(myFragment)
.load(url)
.into(myImageView);
GLIDE :
Glide.with(myFragment)
.load(url)
.into(myImageView);
Hope this helps
You can use Glide or Picasso. As those are very helpful libraries for setting image in adapter (here views are reusable).
If you still want to use asynctask then check below:
In adapter each time scroll will lead to new network call, that can be avoided using saving bitmap object.
You are trying to get image by using below code:
ImageView avatarView = (ImageView)view.findViewById(R.id.imageViewAvatarMensa);
avatarView.setImageBitmap(new obtAvatar2().execute());
This will not work as:
new obtAvatar2().execute()
It will execute in background and return response in onPostExucute(). And result is:
avatarView.setImageBitmap(null)
If you want to use asytask then probably you need make your code like:
private class obtAvatar2 extends AsyncTask<Void, Void, Bitmap> {
Bitmap bm;
#Override
protected Bitmap doInBackground(Void... voids) {
try {
URL url = new URL("https://www.bellatores.cl/wp-content/uploads/2018/01/Avatar-Mujer.png");
URLConnection con = url.openConnection();
con.connect();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
}
return bm;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
ImageView avatarView = (ImageView)view.findViewById(R.id.imageViewAvatarMensa);
avatarView.setImageBitmap(bitmap);
//set bitmap to imageview and save in local list, so in future no need to download
}
}
You can pass reference of ImageView in constructor.
First of all you should add obtAvatar2 async task in your custom adapter.
I hope you are using ViewHolder in your customadapter, then in you getView(), before assigning value to your Imageview, call the async task. For example:
public static class ViewHolder {
public ImageView display_adImage;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.test_layout, null);
holder = new ViewHolder();
holder.display_adImage = vi.findViewById(R.id.IvAdImage);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
...
Bitmap b = new GetImageTask().execute().get();
holder.display_adImage.setImageBitmap(b);
}
}
private class obtAvatar2 extends AsyncTask<Void , Void, Bitmap>{
Bitmap bm;
#Override
protected Bitmap doInBackground(Void... voids) {
try {
URL url = new URL("https://www.bellatores.cl/wp-content/uploads/2018/01/Avatar-Mujer.png");
URLConnection con = url.openConnection();
con.connect();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
}catch (IOException e){
}
return bm;
}
}
I want to take the image from a URL and set is as the background of my RelativeLayout. I use the AsyncTask and try to create a Drawable from BitmapDrawable. But I get a NullPointerException and can't seem to figure out why?
class DownloadBackgroundTask extends AsyncTask<String, Void, Bitmap> {
RelativeLayout bmImage;
View vi;
public DownloadBackgroundTask(RelativeLayout bmImage, View vi) {
this.bmImage = bmImage;
this.vi = vi;
}
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) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null)
{
// null pointer exception here
Drawable d = new BitmapDrawable(vi.getContext().getResources(), result);
bmImage.setBackground(d);
}
else
{
bmImage.setBackgroundResource(R.drawable.logo);
}
}
}
onCreateView():
RelativeLayout rl = (RelativeLayout) rootView.findViewById(R.id.RelativeLayout1);
new DownloadBackgroundTask(rl, rootView).execute("http://pctechmag.com/wp-content/uploads/2012/10/fifa13_messi.jpg");
I'm trying to display an image from a url in a "InfoWindowAdapter"
,I have the following code, but does not show me the image
....
mMap = getMap();
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
...
#Override
public View getInfoContents(Marker marker) {
View v = getActivity().getLayoutInflater().inflate(
R.layout.info_window_layout, null);
String image_url = "http://api.androidhive.info/images/sample.jpg";
new DownloadImageTask(imgEquipo).execute(image_url);
return v;
}
});
call to AsyncTask to get image
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);
} }
}
tranks for your help.
It won't work because the view is returned before you get the image, and they are not synchronized.
Take a look at this approach:
I my using google mapV2 and i m downloading image from google place api and want to display in the popup
The trick is to update the InfoWindow after you get the image.
I have been reading through a lot of answers of questions that are similar to mine, but still having problem fixing my issue. I have a project that is an RSS Reader that loads in images in the background with an AsyncTask class. The program works, except if the user scrolls quickly then the images sometimes do not load in my rows. They never load in the incorrect spot, it just seems like they are skipped if the user scrolls quickly. Also, on start-up, only 2 or 1 of the images in my listview load out of the 4 rows that the user can see.
I know the problem has something to do with the WeakReference object that I use, but I am not sure how to implement it in a better way...
This is my RssListAdapter, which contains my Async class as well.
public class RssListAdapter extends ArrayAdapter<JSONObject>
{
TextView textView;
ImageView imageView;
JSONObject jsonImageText;
ProgressDialog progressDialog;
Activity activity2;
View rowView;
public RssListAdapter(Activity activity, List<JSONObject> imageAndTexts)
{
super(activity, 0, imageAndTexts);
activity2 = activity;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
// Inflate the views from XML
View rowView = (View) inflater
.inflate(R.layout.image_text_layout, null);
jsonImageText = getItem(position);
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// The next section we update at runtime the text - as provided by the
// JSON from our REST call
// //////////////////////////////////////////////////////////////////////////////////////////////////
textView = (TextView) rowView.findViewById(R.id.job_text);
imageView = (ImageView) rowView.findViewById(R.id.feed_image);
BitmapDownloaderTask task = new BitmapDownloaderTask();
Spanned text;
try
{
text = (Spanned) jsonImageText.get("text");
textView.setText(text);
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
task.execute();
return rowView;
}
public class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap>
{
private String url;
private RssListAdapter adapter;
private WeakReference<ImageView> imageViewReference = null;
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params)
{
imageViewReference = new WeakReference<ImageView>(imageView);
Bitmap img = null;
try
{
if (jsonImageText.get("imageLink") != null)
{
System.out.println("XXXX Link found!");
String url = (String) jsonImageText.get("imageLink");
URL feedImage = new URL(url);
HttpURLConnection conn = (HttpURLConnection) feedImage
.openConnection();
InputStream is = conn.getInputStream();
img = BitmapFactory.decodeStream(is);
}
}
catch (MalformedURLException e)
{
// handle exception here - in case of invalid URL being parsed
// from the RSS feed item
}
catch (IOException e)
{
// handle exception here - maybe no access to web
}
catch (JSONException e)
{
// textView.setText("JSON Exception");
}
return img;
}
#Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap)
{
if (isCancelled())
{
bitmap = null;
}
if (imageViewReference != null)
{
ImageView imageView = imageViewReference.get();
if (imageView != null)
{
imageView.setImageBitmap(bitmap);
}
}
}
#Override
// Before images are loaded
protected void onPreExecute()
{
if (imageViewReference == null)
{
imageView.setImageResource(R.drawable.stub);
}
}
}
}
You should check the official Android "Displaying Bitmaps Efficiently" tutorial on how to load and display bitmaps efficiently. It comes with a ready to use piece of code.
i want to display images from mysql server(testing in localhost) using imageurl,i have images in a filder on my server,in an android client app as gridview along with text.how do i use imageurl in my code?
mymainmenu.java
public class MainMenu extends Activity {
GridView gridView;
static final String[] MOBILE_OS = new String[] {
"Android", "iOS","Windows", "Blackberry" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu_list);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(
getApplicationContext(),
((TextView) v.findViewById(R.id.grid_item_label))
.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
my imageadapter.java:
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
public ImageAdapter(Context context, String[] mobileValues) {
this.context = context;
this.mobileValues = mobileValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from list.xml
gridView = inflater.inflate(R.layout.list, null);
// set value into textview
TextView textView = (TextView) gridView
.findViewById(R.id.grid_item_label);
textView.setText(mobileValues[position]);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.grid_item_image);
String mobile = mobileValues[position];
if (mobile.equals("Windows")) {
imageView.setImageResource(R.drawable.imggrid);
} else if (mobile.equals("iOS")) {
imageView.setImageResource(R.drawable.imggrid);
} else if (mobile.equals("Blackberry")) {
imageView.setImageResource(R.drawable.imggrid);
} else {
imageView.setImageResource(R.drawable.imggrid);
}
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return mobileValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
I dnt know how to use the following in my code:
try {
URL url = new URL(imageFileURL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
img.setImageBitmap(bitmap);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Put the image downloading code in a AsyncTask. Here is the explanation.
Execute one instance of asynctask in your getView method, i.e to fetch one image everytime.
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView mImageView;
public void setImageView(ImageView img) {
mImageView = img;
}
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
Call task.setImageView(yourImageViewinGrid) before executing your AsyncTask to let it know where to set the image after downloading.
To get the image, you have to do something like :
URL new_url = new URL("your url");
Bitmap image_bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); ImageView image_view = new ImageView(this);
image_view.setImageBitmap(image_bitmap);
Anyway, it's better to download the image as background task. What I actually do is to create a custom view with one private inner class that extend AsyncTask to download the image for you.
I dnt know how to use the following in my code:
that code will download the image for you, you can place in separate thread either AsyncTask or Thread and set the downloaded image in the imageview... simple as that. There are so many example on the web you can google it out
EIDTED
code to download the image
public class AsyncFetchImage extends AsyncTask<String, Void, Bitmap>{
private WeakReference<ImageView> imageReference;
// private WeakReference<Dialog> dialogReferance;
public AsyncFetchImage(ImageView imageview) {
imageReference = new WeakReference<ImageView>(imageview);
// dialogReferance = new WeakReference<Dialog>(dialog);
}
#Override
protected Bitmap doInBackground(String... s) {
return downloadImage(s[0]);
}
private Bitmap downloadImage(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Nixit");
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 is = null;
try{
is = entity.getContent();
final Bitmap bit = BitmapFactory.decodeStream(is);
return bit;
}finally{
if(is != null)
is.close();
entity.consumeContent();
}
}
} catch (IOException e) {
e.printStackTrace();
return null;
} finally{
if(client != null){
client.close();
}
}
Log.i("Image Fetch","Image Fetch Complete");
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
if(isCancelled()){
result = null;
}
if(imageReference != null){
ImageView imageView = imageReference.get();
// Dialog di = dialogReferance.get();
if (imageView != null) {
imageView.setImageBitmap(result);
// di.show();
}
}
}
}
How to use:-
imageView = (ImageView)dialog.findViewById(R.id.imageView1);
AsyncFetchImage fetchImage = new AsyncFetchImage(imageView);
fetchImage.execute(url);
You can use this in getview method of adapter
Hope that help