image display as gridview - android

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

Related

android Lazy image load of ListView not working properly

I am tying to lazy load images into my ListView, the images are loading fine, but I've a problem. While loading the images get interchanged.
Let's say that the ListView has 10 rows. It loads the images for 1st row, it displays it in the 1st row, then it loads the image for the 2nd row. It displays in the 2nd row for a moment and then it displays the image for the 2nd row in the 1st row. Then the ImageView in row1 switches between images of 1st row and 2nd. Similarly while loading images of next rows. the previous row's images get switched between. And then after loading all the images, everything gets displayed correctly.
Here's my code
Adapater class:
public class FamilyMemberListAdapter extends ArrayAdapter<Map<String, String>> {
List<Map<String, String>> familyMemberList = new ArrayList<Map<String, String>>();
private Activity activity;
public FamilyMemberListAdapter(Activity activity,
List<Map<String, String>> familyMemberList) {
super(activity, R.layout.activity_gch_family_members, familyMemberList);
this.activity = activity;
this.familyMemberList = familyMemberList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext()).inflate(
R.layout.activity_gch_family_member_item, parent, false);
holder = new ViewHolder();
holder.lblFamilyMemberName = (TextView) convertView
.findViewById(R.id.lblFamilyMemberItem);
holder.lblFamilyMemberRelation = (TextView) convertView
.findViewById(R.id.lblFamilyMemberRelationItem);
holder.imgProfilePic = (ImageView) convertView
.findViewById(R.id.imgvProfilePic);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
int accountId = Integer.valueOf(familyMemberList.get(position).get(
"accountId"));
holder.lblFamilyMemberName.setText("Name: "
+ familyMemberList.get(position).get("name"));
holder.lblFamilyMemberRelation.setText("Relation: "
+ familyMemberList.get(position).get("relation"));
if (holder.imgProfilePic != null) {
new ImageDownloaderTask(holder.imgProfilePic).execute(String
.valueOf(accountId));
}
return convertView;
}
#Override
public int getCount() {
return familyMemberList.size();
}
static class ViewHolder {
TextView lblFamilyMemberName;
TextView lblFamilyMemberRelation;
ImageView imgProfilePic;
}
}
Imageloader AsyncTask:
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
String responseText = null;
HttpClient httpClient = ServiceHelper.getHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(RestApiPaths.GET_PROFILE_PIC + accountId);
try {
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
Log.d(TAG, responseText);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.holder_pic_side);
imageView.setImageDrawable(placeholder);
}
}
}
}
}
I've created a Static class for the ListView items. Still Why is the images go on interchanging while loading. Please tell me what I'm doing wrong here.
Add holder.imgProfilePic.setTag(accountId); before you call the AsyncTask. Add an extra parameter accountId to your task. Then in onPostExecute check if it is the same accountId as in the image view
Maybe try to use libraries like picasso or universal image loader or something.
They have solved most of problems with image loading

Android - Listview adapter with asynctask to load images

I'm trying to handle an image loading at the background.
Now, I've look at the next link - here
And I've got few things I don't understand -
1) I've made the next CursorAdapter for the listview items-
public class ChatCursorAdapter extends CursorAdapter implements OnClickListener {
public ChatCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public int getCount() {
return getCursor() == null ? 0 : super.getCount();
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int _position) {
Cursor cursor = (Cursor) getItem(_position);
return getItemViewType(cursor);
}
private int getItemViewType(Cursor cursor) {
String sender = cursor.getString(2);
SharedPreferences userPref = PreferenceManager
.getDefaultSharedPreferences(MainChat.this);
String saveUser = userPref.getString("user", "");
if (saveUser.equalsIgnoreCase(sender)){
return 0;
}else{
return 1;
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
holder = (ViewHolder) view.getTag();
holder.mesg.setText(getSmiledText(MainChat.this,msg));
holder.mesg2.setText(getSmiledText(MainChat.this,msg2));
holder.myImage.setTag(picPath);
holder.myImage.setImageBitmap(setImageToImageView(picPath));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
View itemLayout = null;
switch(getItemViewType(cursor)){
case 0:
itemLayout = getLayoutInflater().inflate(R.layout.msg_item1,parent, false);
break;
case 1:
itemLayout = getLayoutInflater().inflate(R.layout.msg_item13, parent,false);
break;
}
itemLayout.setTag(holder);
holder.mesg = (TextView) itemLayout.findViewById(R.id.text_start);
holder.mesg2 = (TextView) itemLayout.findViewById(R.id.text_end);
holder.myImage = (ImageView) itemLayout.findViewById(R.id.imageView_msgpic);
return itemLayout;
}
Now i wnat to use the info from the link.
But i don't understand - What i need to pass into the and what to AsyncTask leave at CursorAdapter?
Also the sample code uses -
.execute(holder);
Can't I call to the AsyncTask like this -
new AsyncTask().execute();
And how and where should i call the AsyncTask, I don't understand it?
Thanks for any kind of help
You could always use an external lib like Universal-Image-Loader or Picasso to achieve what you are trying to do =)
Take a look at AsyncTask. You must Override doInBackground method. You may define a constructor to supply view in which you want to put downloaded image.
public class ImageDownloader extends AsyncTask<String, Void, List<Bitmap>> {
private ImageView ivImageHolder;
private Context context;
public ImageDownloader(Context context, ImageView imageHolder) {
this.ivImageHolder = imageHolder;
this.context = context;
}
...
#Override
protected List<Bitmap> doInBackground(String... params) {
//This happens in background
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
for (String url : params) {
Bitmap bitmap = DownloadImage(url);
bitmaps.add(bitmap);
}
return bitmaps;
}
....
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
...
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
#Override
protected void onPostExecute(List<Bitmap> bitmaps) {
super.onPostExecute(bitmaps);
for (int i = 0; i < bitmaps.size(); i++) {
final Bitmap bitmap = bitmaps.get(i);
ivImageHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new ImageViewActivity(context, bitmap).show();
}
});
// iv.setImageBitmap(bitmap);
ivImageHolder.setImageBitmap(bitmap);
ivImageHolder.setVisibility(ImageView.VISIBLE);
}
}
if you write your asyntask method I can say how can you use it, If it need to string value
you can use like this:
new your_async(context).execute(url) ;
But in my advice : you should use lazyadapter to use bitmaps on listview because there is a mermory issue if you do not pay attention properties of images.
here is link : stackoverfow

Why my application crashes when I scroll quickly (or a lot) my GridView?

I am filling a GridView with my facebook friends' photo.
When I use my account of tester with few friends my application works good. But when I use my main account and I scroll quickly my application I get This error:
AndroidRuntime(6131): java.util.concurrent.RejectedExecutionException: Task android.os.AsyncTask$3#42230f20 rejected from java.util.concurrent.ThreadPoolExecutor#4206af70[Running, pool size = 128, active threads = 128, queued tasks = 10, completed tasks = 61]
otherwise
If i scroll a lot i get this error:
java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299)
Caused by: java.lang.NullPointerException at it.alfonso.utils.GetImageFromUrlAsyncTask.downloadImage(GetImageFromUrlAsyncTask.java:62)
if (facebookAdapter == null) {
facebookAdapter = new ImageAdapterFacebook(this, facebookResponses);
gridview.setAdapter(facebookAdapter);
}
else {
gridview.setAdapter(facebookAdapter);
}
My adapeter for my GridView
public class ImageAdapterFacebook extends BaseAdapter {
private Context mContext;
private FacebookResponses facebookFrinds;
public ImageAdapterFacebook(Context c, FacebookResponses facebookFrinds) {
mContext = c;
this.facebookFrinds = facebookFrinds;
}
public int getCount() {
return facebookFrinds == null ? 0 : facebookFrinds.getData().length;
}
public Object getItem(int position) {
return facebookFrinds == null ? null
: facebookFrinds.getData()[position];
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View amico, ViewGroup parent) {
final ImmageViewHolder viewHolder;
if (amico == null) { // if it's not recycled, initialize some attributes
LayoutInflater li = (LayoutInflater) parent.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
amico = li.inflate(R.layout.details_img_facebook_user, parent,
false);
viewHolder = new ImmageViewHolder();
viewHolder.userImage = (ImageView) amico
.findViewById(R.id.userLikesimg);
amico.setTag(viewHolder);
} else {
viewHolder = (ImmageViewHolder) amico.getTag();
}
if (facebookFrinds != null) {
viewHolder.userImage.setImageResource(R.drawable.image_loader);
String imgUserurl = facebookFrinds.getData()[position]
.getPic_square();
// Create an object for subclass of AsyncTask
GetImageFromUrlAsyncTask task = new GetImageFromUrlAsyncTask(
mContext, new DownloadImageLister() {
#Override
public void onDownloadImageSucces(Bitmap immagine) {
viewHolder.userImage.setImageBitmap(immagine);
}
#Override
public void onDownloadImageFail() {
System.out.print("errore");
}
});
task.execute(imgUserurl);
}
return amico;
}
public class ImmageViewHolder {
ImageView userImage;
}
}
My AsyncTask
public class GetImageFromUrlAsyncTask extends AsyncTask<String, Void, Bitmap> {
private Context contesto;
private DownloadImageLister listenerImage;
public GetImageFromUrlAsyncTask(Context context,
DownloadImageLister listener) {
contesto = context;
listenerImage = listener;
}
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null ) {
listenerImage.onDownloadImageSucces(result);
}
if (result == null ) {
listenerImage.onDownloadImageFail();
}
}
// 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;
}
}
Since you are performing so many requests for each image load your app is crashing. You could use the Volley Android library and its NetworkImageView. This is what several Google apps are using for async image loading and http requests. There is a good tutorial explaining how to use it here: http://www.captechconsulting.com/blog/clinton-teegarden/android-volley-library-tutorial.
Hope that helps!

Display Image in a Listview (In Adapter) using Json

Please bear with me before downvoting this.I am a beginner to Android. After trying multiple solutions on here I have failed to resolve this.
I am trying to set the Image in the listview with the following items in place.I want to be able to insert the image code somewhere on the Schedule adapter class.
The following code is my Schedule Adapter
public class Schedule_ArrayAdapter extends ArrayAdapter<String> {
private final Activity activity;
private final String[] name, category, image;
Typeface colab, colab_bold, Bebas;
int selected = -1;
public Schedule_ArrayAdapter(Activity activity, String[] name, String[] category, String[] image) {
super(activity, R.layout.schedule_item, category);
this.activity = activity;
this.name = name;
this.category = category;
this.image = image;
this.colab = Typeface.createFromAsset(activity.getAssets(), "ColabThi.otf");
this.colab_bold = Typeface.createFromAsset(activity.getAssets(), "ColabMed.otf");
this.colab_bold = Typeface.createFromAsset(activity.getAssets(), "BebasNeue.otf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get view and textview from xml
View rowView = inflater.inflate(R.layout.schedule_item, parent, false);
rowView.setBackgroundColor(0xffffffff);
LinearLayout background = (LinearLayout) rowView.findViewById(R.id.back);
if (selected != -1) {
if (selected == position) {
background.setBackgroundColor(0xffeaac4b);
} else {
background.setBackgroundColor(0xffffffff);
}
}else{
background.setBackgroundColor(0xffffffff);
}
TextView TimeView = (TextView) rowView.findViewById(R.id.category);
TextView TitleView = (TextView) rowView.findViewById(R.id.title);
ImageView vi = (ImageView) rowView.findViewById(R.id.imgPreview);
GetImage getimage = new GetImage();
getimage.execute(image);
//change names
TitleView.setText(category[position]);
TitleView.setTextSize(fontpercent_screenheight(3.5));
TitleView.setPadding(dp(10), dp(5), dp(5), dp(0));
TitleView.setTypeface(Bebas);
TimeView.setText(name[position]);
TimeView.setTextSize(fontpercent_screenheight(3.5));
TimeView.setPadding(dp(10), dp(2), dp(5), dp(5));
TimeView.setTypeface(colab);
return rowView;
}
The following is my ImageDownloader class
public class ImageDownloader {
private InputStream OpenHttpConnection(String image) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(image);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
conn.setUseCaches(true);
HttpURLConnection httpConn = (HttpURLConnection) conn;
try {
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting" + ex);
}
return in;
}
public Bitmap DownloadImage(String image) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(image);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
}
Parsing of JSON and fetching Data is working as normal. When looking in the debugger the "image" array is also been fetched. How do i set the images in the view ?
So in your getView of the adapter you should make a request to some url and use the
Bitmap bitmap=BitmapFactory.decodeStream(inputstream);
now set this in your imageview of your layout
ImageView i=(ImageView)findViewById(R.id.imageiew);
i.setImageResource(bitmap);
so that shows the image.
You can also try this code
ImageView iv=(ImageView) findViewById(R.id.imageview);
try {
iv.setImageDrawable(grabImageFromUrl(Global.a5));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the function of fetching image from URL is
private Drawable grabImageFromUrl(String url) throws Exception {
return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src"); }

Insert Image from an URL inside a ListView

I would like to know if it is possible to load an image inside a ListView directly from the web, when the URL is stocked inside a json.
Edit : Solved, It is possible to use an AsyncTask
public class ParseImage extends AsyncTask<Object, String, Drawable> {
private ProgressBar pd;
private ImageView imv;
private int position;
public ParseImage(int position, ImageView imv, ProgressBar pd2) {
this.position = position;
this.imv = imv;
this.pd = pd2;
}
#Override
public Drawable doInBackground(Object... params) {
Drawable d = null;
try {
d = Drawable.createFromStream(
(InputStream) new URL(list.get(position).get("Cover"))
.getContent(), "src");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return d;
}
public void onPostExecute(Drawable result) {
if (result != null && imv != null) {
pd.setVisibility(View.INVISIBLE);
imv.setImageDrawable(result);
}
}
}
}
You need to create your own custom Listview to show more than a String.Here is a piece of code you can refer:
MovieAdaptor.java:
public class MovieAdaptor extends ArrayAdapter<Movie> {
Context context;
int layoutResourceId;
ArrayList<Movie> movieArrayList = new ArrayList<Movie>();
public MovieAdaptor(Context context, int layoutResourceId, ArrayList<Movie> movies) {
super(context, layoutResourceId, movies);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.movieArrayList = movies;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ContactHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ContactHolder();
holder.thumbnail = (ImageView) row.findViewById(R.id.imageThumbnail);
holder.title = (TextView) row.findViewById(R.id.MovieTitle);
holder.synopsis = (TextView) row.findViewById(R.id.synopsis);
row.setTag(holder);
} else {
holder = (ContactHolder) row.getTag();
}
holder.title.setText(movieArrayList.get(position).title);
holder.synopsis.setText(movieArrayList.get(position).synopsis);
newAsyncDownloadImage(holder.thumbnail).execute(movieArrayList.get(position).posters.get("thumbnail"));
return row;
}
static class ContactHolder {
ImageView thumbnail;
TextView title;
TextView synopsis;
}
}
Activity.class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
moviesListView = (ListView) findViewById(R.id.list_movies);
moviesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position > HEADER) {
Intent intent = new Intent(getBaseContext(), MovieActivity.class);
intent.putExtra(MOVIE_OBJECT, movieArrayList.get(position - 1));
startActivity(intent);
}
}
});
View header = (View) getLayoutInflater().inflate(R.layout.listview_row_header, null);
moviesListView.addHeaderView(header);
movieAdaptor = new MovieAdaptor(this, R.layout.listview_row_item, movieArrayList);
moviesListView.setAdapter(movieAdaptor);
AsyncDownloadImage.java:
public class AsyncDownloadImage extends AsyncTask<Object, Object, Object> {
ImageView iv;
private HttpURLConnection connection;
private InputStream is;
private Bitmap bitmap;
public AsyncDownloadImage(ImageView mImageView) {
iv = mImageView;
}
#Override
protected Object doInBackground(Object... params) {
URL url;
try {
url = new URL((String) params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
is = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
if (null != result) {
iv.setImageBitmap((Bitmap) result);
} else {
iv.setBackgroundResource(R.drawable.ic_launcher);
}
}
}
}
Can you send the return of
JSONfunction.getJSONfromURL("http://colmarmagazine.ctai.fr/issues.php");
Please ?
I think it's a bad parting ! Because you have :
Unable to decode stream: java.io.FileNotFoundException: /http:/colmarmagazine.ctai.fr/content/numerodemo/numerodemo.png: open failed: ENOENT (No such file or directory)
and a "/" too much in the url for your cover !

Categories

Resources