I'm having a problem which is probably much simple than I think. I have a GridView that load images from URL sent in JSON. The Url are then converted to bitmap and every image is passed to a GridView item. That all works perfectly. Then when i click on the image I send the image url to another view that displays it in fulls size, my problem is that every time I click on an item in the GridView it always loads the image in the last item of that GridView, so I'm asumming that probably when I send the image url to the next view I'm always passing the url of the last image. Does someone know what I can do to display the proper image after it has been clicked in the list view? any help will be appreciated.
Code:
/**
* Background AsyncTask to load profiles images by making HTTP Request
*/
class GetProfileImages extends AsyncTask<String, String, String> {
// Progress Dialog
private ProgressDialog pDialog;
URL url = null;
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileImages.this);
pDialog.setMessage("Loading images...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Gets all the notices from URL that correspond to the current user
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// Gets JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_profile_images, "GET", params);
// Check your log cat for JSON response
Log.d("Profile images: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Image found
// Gets Array of notices
images = json.getJSONArray(TAG_IMAGES);
// Loops through all images
for (int i = 0; i < images.length(); i++) {
JSONObject image = images.getJSONObject(i);
// Storing each JSON item in variable
imagePath = ("http://gatoandroidapp.comeze.com/" + image.getString(TAG_PATH));
//Gets image path and passed the image in bitmap format
try {
url = new URL(imagePath);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
}catch (IOException e) {
}
// Creates new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// Ads child nodes to HashMap
map.put(TAG_PATH, bmp);
// Ads HashList to ArrayList
imagesList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
*/
protected void onPostExecute(String file_url) {
//Dismiss the dialog after getting images
pDialog.dismiss();
//Updates UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//Updates parsed JSON data into ListView
ListAdapter adapter = new ExtendedSimpleAdapter(
ProfileImages.this, imagesList,
R.layout.profile_images_custom_gridview, new String[] {TAG_PATH},
new int[] {R.id.profilesImages_customGridView});
//Updates ListView
gridview.setAdapter(adapter);
}
});
}
}
Code to pass the image url:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Creates intent
Intent i = new Intent(v.getContext(), PictureView.class);
//Sends image path to next view
i.putExtra(TAG_PATH, imagePath);
startActivityForResult(i, 0);
}
});
Code that receive intent with image url (path)
// Get image path from intent
imagePath = getIntent().getStringExtra(TAG_PATH);
//Load image from server into ImageView
profilePicture = (ImageView) findViewById(R.id.pictureView_imageView);
URL url = null;
Bitmap bmp = null;
try {
url = new URL(imagePath);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
}catch (IOException e) {
}
profilePicture.setImageBitmap(bmp);
Thanks!
I guess, you have declared imagePath with Class-level scope. Since at the end of for loop imagePath is updated with the last item URL so you're always passing the url of the last image.
To resolve the issue, make use of View.setTag() and View.getTag() methods to pass the URL (or) Use the position in onItemClick() to retrieve the
JSONObject image = images.getJSONObject(position); and construct the URL.
Related
I have a JSON array which has with it several strings among which is the link that will be is being used to download my images, I am new to AsyncTask, the strings are being placed in their rightful places properly but am having issues figuring out how to position the image download task, I am following this tutorial http://www.mybringback.com/android-sdk/13239/android-mysql-php-json-part-6-json-parsing-and-android-design/
Can someone highlight me on how I should call the AsyncTask so that it goes in flow with all the other downloads? Below is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// note that use read_comments.xml instead of our single_post.xml
setContentView(R.layout.read_comments);
ActionBar mActionBar = getActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.customactionbar, null);
EditText msearch = (EditText) mCustomView.findViewById(R.id.mquerybox);
ImageButton mstartsearch = (ImageButton) mCustomView.findViewById(R.id.msearch);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v) {
Intent i = new Intent(ReadComments.this, AddComment.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content, for example,
// message it the tag, and "I'm awesome" as the content..
mCommentList = new ArrayList<HashMap<String, String>>();
// Bro, it's time to power up the J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
// back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
// when parsing JSON stuff, we should probably
// try to catch any exceptions:
try {
// I know I said we would check if "Posts were Avail." (success==1)
// before we tried to read the individual posts, but I lied...
// mComments will tell us how many "posts" or comments are
// available
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
String downloadUrl = c.getString(TAG_IMAGE);
new DownloadImageTask((RoundedImageView) findViewById(R.id.downloaded))
.execute(downloadUrl);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
map.put(TAG_IMAGE, downloadUrl);
// adding HashList to ArrayList
mCommentList.add(map);
// annndddd, our JSON data is up to date same with our array
// list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[]{TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME, TAG_IMAGE}, new int[]{R.id.title, R.id.message,
R.id.username, R.id.downloaded});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// This method is triggered if an item is click within our
// list.
}
});
}
private class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ReadComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
RoundedImageView bmImage;
public DownloadImageTask(RoundedImageView 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);
}
}
}
To download images in asynctask, I recommend you to use a library to handle that. So will cache images and will reduce the possible number of errors and data downloading. Universal Image Download or Picasso are the most common libraries used for this.
You should call downloadImage in onPostExecute from LoadCommentsTask
To load the image into imageview with url Picasso is the best solution available. Its very easy to use. See yourself at Picasso
And if you want to save the image as file in sd card, then ION can be the better solution.
Universal Image Loader is more powerful in terms of supported features but is bit of complicated than picasso or ion.
This is My code,I'm trying to pass the image to listview but i get error.
how can i pass image ? should i download it into local memory first and then send it listview ??
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all, "GET", params);
if(json == null)
System.out.println("NULL");
else{
// Check your log cat for JSON reponse
Log.d("All Developers: ", json.toString());
try {
// Checking for SUCCESS TAG
int status = json.getInt(TAG_STATUS);
if (status == 1) {
// products found
// Getting Array of Products
developers = json.getJSONArray(TAG_all);
// looping through All Products
for (int i = 0; i < developers.length(); i++) {
JSONObject c = developers.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
String image = c.getString(TAG_IMAGE_PATH);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_UID, id);
map.put(TAG_NAME, name);
//map.put(TAG_IMAGE_PATH, image);
// adding HashList to ArrayList
developersList.add(map);
//Iamge Download
}
} else {
System.out.println("No Data");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(),
developersList,R.layout.list_data, new String[] { TAG_UID,
TAG_NAME,TAG_IMAGE_PATH},
new int[] { R.id.uid, R.id.name,R.id.image });
// updating listview
lv.setAdapter(adapter);
}
});
}
}
}
Errors
03-30 13:34:03.475: E/BitmapFactory(22326): Unable to decode stream: java.io.FileNotFoundException
You don't have to re-invent the wheel - assuming you have the url to the image you can use nostra13 library for image loading it'll do all the nasty staff for you (cache handling downloading\ saving thumbnail etc..) it also have an exmaple project you can look at to better unnderstand of how to use it.
I am displaying images in a GridView with Universal Image Loader. The images are from a database. I added a context menu to delete pictures as needed out of the database. Everything works great up to there. After deleting the picture I need it to refresh the view but it's still displaying the deleted picture. (I used the default setup for UIL and did not enable caching) I tried to call destroy and then init to the imageloader and then called the async task to query the images again but it gives me an error saying file not found (the deleted one). Here is my (lengthy) code. Can anyone see what I am missing?
GridView gridview;
AdapterContextMenuInfo info;
ImageLoaderConfiguration config;
ImageView imageView;
ArrayList<String> pictures = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_grid);
config = new ImageLoaderConfiguration.Builder(this).build();
imgLoader = ImageLoader.getInstance();
imgLoader.init(config);
class getalbum extends AsyncTask<String, String, String> {
//pre execute here
#Override
protected String doInBackground(String... args) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", restoredemail));
params.add(new BasicNameValuePair("album_name", album_name));
json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
mPictures = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object
// returned
for (int i = 0; i < mPictures.length(); i++) {
JSONObject c = mPictures.getJSONObject(i);
String dir = c.getString("dir");
String album = c.getString("album");
String pic = c.getString("photo");
String picture = thecompletedpicture;
pictures.add(picture);
}
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
setpictures();
}
}
private void setpictures() {
// TODO Auto-generated method stub
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this, pictures));
registerForContextMenu(gridview);
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}
// and then finally the context menu makes
// an async thread to delete the picture and
// remove it from the database. On the
// post execute I put the call to load the pictures again
// This is where the problem is. I need it to just display
// the remaining pictures. Maybe trying to remove the deleted
// picture from the array and then reloading it? I really need
// help with the code.
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
imgLoader.destroy();
imgLoader.init(config);
new getalbum().execute();
}
Try using this to empty your image cache:
Collection<String> c = ImageLoader.getInstance().getMemoryCache().keys();
for(String key : c) {
try {
MemoryCacheUtil.removeFromCache(key, ImageLoader.getInstance().getMemoryCache());
} catch(Exception ex) {ex.printStackTrace();}
}
I have made a program in which I am using PHP to encode data as JSON. My program is working fine, and is not showing any errors or problems; I am getting what I want but I am facing very small issue.
Here, I am not able to show an item's image in ListView but whenever I click on one of the item rows to view full item detail, I get the image of selected item. It means I should be getting the image in ListView, but I'm unable to show that, so could someone please help to sort out this mistake?
public class AlbumsActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> albumsList;
// albums JSONArray
JSONArray albums = null;
String imagepath;
// albums JSON url
private static final String URL_ALBUMS = "MY URL";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_IMAGEPATH = "imagepath";
private static final String TAG_SONGS_COUNT = "songs_count";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
ListView lv = getListView();
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
// send album id to tracklist activity to get list of songs under that album
String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Albums ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
String imageurl = c.getString(TAG_IMAGEPATH);
String songs_count = c.getString(TAG_SONGS_COUNT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_IMAGEPATH,imageurl);
map.put(TAG_SONGS_COUNT, songs_count);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, albumsList,
R.layout.list_item_albums, new String[]
{
TAG_ID, TAG_NAME, TAG_DESCRIPTION, TAG_IMAGEPATH, TAG_SONGS_COUNT
},
new int[]
{
R.id.album_id, R.id.album_name, R.id.album_description, R.id.list_image, R.id.songs_count
}
);
// updating listview
setListAdapter(adapter);
}
});
}
}
You have to first download the image and then show it in list view. You can not directly pass the image URL, it will not work.
Change your current code as and also remove runOnUiThread() from onPostExecute method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String,
ArrayList<HashMap<String, String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Albums ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected ArrayList<HashMap<String, String>>
doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
String imageurl = c.getString(TAG_IMAGEPATH);
String songs_count = c.getString(TAG_SONGS_COUNT);
// creating new HashMap
HashMap<String, String> map = new
HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_IMAGEPATH,imageurl);
map.put(TAG_SONGS_COUNT, songs_count);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return albumsList;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(ArrayList<HashMap<String,
String>> file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// get listview
ListView lv = getListView();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, file_url,
R.layout.list_item_albums, new String[]
{
TAG_ID, TAG_NAME, TAG_DESCRIPTION,
TAG_IMAGEPATH, TAG_SONGS_COUNT
},
new int[]
{
R.id.album_id,
R.id.album_name, R.id.album_description, R.id.list_image, R.id.songs_count
}
);
// updating listview
lv.setListAdapter(adapter);
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
Intent i = new Intent(getApplicationContext(),
TrackListActivity.class);
// send album id to tracklist activity to get list of songs
//under that album
String album_id = ((TextView) view.
findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
}
NOTE : if you are given direct web URL in ImageView then this will never work because you will need first download image from Web then set it to ImageView src.
see this post how we take image from web server
How to load an ImageView by URL in Android?
It means that you want to customize your list view with image and text. For that (what i did in my case), get the image url and text in two arrays. then set the adapter of the list view by passing context, both arrays.
For setting up images, you need to import the library (Either image url helper or Universe image loader). Both can help you well but i will recommend you for the image url helper library because it is easy to use.
Try this in your Adapter, It might help you:
String imageURL = "htp://domain/some-path/kdhfbdskf.jpg";
Bitmap bmp = null;
try {
InputStream in = new java.net.URL(imageURL).openStream();
bmp = BitmapFactory.decodeStream(in);
}
catch (IOException e) {
e.printStackTrace();
}
if (bmp != null) {
holder.UserImageView.setImageBitmap(bmp);
} else {
holder.UserImageView.setImageResource(R.drawable.ic_launcher);
}
remov the runOnUiThread() from the post Execute and you do not run UI component into thread.. simply set images...
I've been having lots of troubles using adapter to display my images properly into my imageView. So basically I have a JSON string and I am parsing through it to get the url of each image. Then I want to display the each image with its title in a list view fashion.
I found this code online where it works perfectly when only one image needs to be displayed, but it doesn't work when I have to do this dynamically. Anyone has some good suggestions on how to get it to work? I attached parts of my codes for references.
Thank you!!!
//results => JSON string
ArrayList<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
for(int i = 0; i < results.length(); i++){
JSONObject c = results.getJSONObject(i);
// Storing each json item in variable
cover = c.getString(TAG_COVER);
String title = c.getString(TAG_TITLE);
try {
URL urlS = new URL(cover);
new MyDownloadTask().execute(urlS);
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_COVER, cover);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
resultList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, resultList,
R.layout.list_item,
new String[] {TAG_TITLE}, new int[] {
R.id.title});
setListAdapter(adapter);
And here is the image downloaded codes I found :
private class MyDownloadTask extends AsyncTask<URL, Integer, Bitmap> {
#Override
protected Bitmap doInBackground(URL... params) {
URL url = params[0];
Bitmap bitmap = null;
try {
URLConnection connection = url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
//is.close(); THIS IS THE BROKEN LINE
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
ImageView myImage = (ImageView) findViewById(R.id.list_image);
myImage.setImageBitmap(bitmap);
} else {
Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show();
}
}
}
There is pretty good library calling AQuery. YOu can use it and simple get all this stuff by writting only 2 line of code, plus it will cache all images for you and it's very good especcially if you are using them in ListView
AQuery aq = new AQuery(activity);
aq.id(R.id.image).image(url, false, true);
Also i think it will be better to use CustomAdapter. I'm not sure it's possible to handle this situation using SimpleAdapter.
Hope this will help you.