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();}
}
Related
what I am currently doing is allowing users to look up tracks, it will display the song name and display the artist and then start downloading the images in the background so that the user sees the results quickly. What I currently do is take the first 10 queries and dislpay those and download those images, then when the user clicks show more it will download 10 more and so on, but the only image that actually displays once it is done loading is the first one. The rest of the images download, but the imageviews do not populate unless i scroll away from them and then back over them. I can't figure out why, but here is my code.
My code for the custom list adapter:
public class SearchSongAdapter extends BaseAdapter {
ArrayList<ArrayList<String>> track_info;
private static LayoutInflater inflater=null;
String token;
ArrayList<ImageView> imageViews;
ArrayList<Bitmap> imageBitMaps;
DownloadImageTask downloadImageTask;
int downloadsCounter = 0;
public SearchSongAdapter(Context context, ArrayList<ArrayList<String>> track_info, String token)
{
imageViews = new ArrayList<ImageView>();
imageBitMaps = new ArrayList<Bitmap>();
inflater = (LayoutInflater)context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.track_info = track_info;
this.token = token;
//start the downloads
if(track_info.size() > 0) {
downloadImageTask = new DownloadImageTask();
downloadImageTask.execute("https://api.spotify.com/v1/tracks/" + track_info.get(0).get(1).replace("spotify:track:", ""), String.valueOf(downloadsCounter));
}
}
#Override
public int getCount() {
return this.track_info.size();
}
#Override
public Object getItem(int position) {
return track_info.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView songNameTextView, artistNameTextView;
ImageView trackIconImageView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
Holder holder = new Holder();
rowView = inflater.inflate(R.layout.song_list_items, null);
holder.songNameTextView = (TextView) rowView.findViewById(R.id.songName);
holder.artistNameTextView = (TextView) rowView.findViewById(R.id.artistNameTextView);
holder.trackIconImageView = (ImageView) rowView.findViewById(R.id.trackIconImageView);
holder.songNameTextView.setText(track_info.get(position).get(0));
holder.artistNameTextView.setText(track_info.get(position).get(2));
imageViews.add(position, holder.trackIconImageView);
if(position < imageBitMaps.size()) {
holder.trackIconImageView.setImageBitmap(imageBitMaps.get(position));
}
return rowView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
int position;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... urls) {
HttpResponse response = null;
HttpClient httpClient = new DefaultHttpClient();
String albumpicture;
Bitmap mIcon11 = null;
position = Integer.valueOf(urls[1]);
HttpGet httpPost = new HttpGet(urls[0]);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Accept", "application/json"));
params.add(new BasicNameValuePair("Authorization Bearer ", token));
try {
response = httpClient.execute(httpPost);
// writing response to log
} catch (IOException e) {
e.printStackTrace();
}
try {
try {
JSONObject jsonObject = new JSONObject(EntityUtils.toString(response.getEntity()));
albumpicture = jsonObject.getJSONObject("album").getJSONArray("images").getJSONObject(0).getString("url");
InputStream in = new java.net.URL(albumpicture).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
mIcon11 = getResizedBitmap(mIcon11, 50, 50);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return mIcon11;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageViews.get(position).setImageBitmap(bitmap);
imageBitMaps.add(position, bitmap);
if(position < track_info.size() - 1) {
downloadImageTask = new DownloadImageTask();
downloadImageTask.execute("https://api.spotify.com/v1/tracks/" + track_info.get(downloadsCounter).get(1).replace("spotify:track:", ""), String.valueOf(downloadsCounter));
}
downloadsCounter++;
}
}
DownloadImageTask is where I download the image and I first call it in the constructor.
Summary:
The first imageView loads and populates, but the others do not populate unless I scroll away from there (scroll down) and then back up.
#Rockyfish,
you can reduce your hustle about loading the Images and managing the network call all by your self.
your loading image logic can be replaced by one line of code like this.
Picasso.with(getApplicationContext()).load(image_url).into(holder.trackIconImageView);
where,
getApplicationContext() ===> is context which can be replaced with context you you are assigning to the `adapter`
image_url =================> is the url to the imgae,
the process of loading the ImgaeView from a image kept at some url is done by Picasso as you know he is a great painter so let him do the work.
to add the Picasso library adding following code to the dependencies block in the build.gradle file like this
compile 'com.squareup.picasso:picasso:2.5.2'
and you would be able to use picasso
We have awesome open source libraries to handle the image download and caching stuff - Picasso Square.
We should always try to use existing and proven solutions rather than trying to reinvent the wheel.
So, I used Android - configure Spinner to use array to try and display just one field of a custom java class. My Java class is as follows (it is a part of my Google App Engine backend)
public class CropVariety {
private String varietyId;
private String varietyName;
public String getVarietyId() { return varietyId; }
public String getVarietyName() {
return varietyName;
}
public void setVarietyId(String data) {varietyId = data; }
public void setVarietyName(String data) {
varietyName = data;
}
public String toString()
{
return varietyName;
}
}
and then in the activity Async task, I have the following in Post Execute
super.onPostExecute(result);
varietyList = result;
spinner = (Spinner) findViewById(R.id.variety_spinner);
spinner.setSelection(0);
dataAdapter = new ArrayAdapter(context,android.R.layout.simple_spinner_item, varietyList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.notifyDataSetChanged();
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
The OnItemSelectedListener is implemented as follows:
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
// String selectedItem = parent.getItemAtPosition(pos).toString();
CropVariety selectedItem = (CropVariety) parent.getItemAtPosition(pos);
//check which spinner triggered the listener
switch (parent.getId()) {
case R.id.variety_spinner:
selectedVarietyName = selectedItem.getVarietyName();
selectedVarietyId = selectedItem.getVarietyId();
break;
}
So while selectedVarietyName and selectedVarietyId get the right values, each item on the drop down list looks as follows:
{"varietyId":"sefs","varietyName":"asfd"}
I followed the link and don't know why the variety name isn't being displayed in the spinner. Thank you
you are downloading json Object from that link .. you have to parse th json in your doInBackground .. and store the result in a list to use it later in the postExecute here is an exemple:
class ModifierParam extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityMed.this);
if (action.equals("rdvmed")) {
pDialog.setMessage(getString(R.string.enrParam));
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
}
protected String doInBackground(String... args) {
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
//here are the password and email for login
params.add(new BasicNameValuePair("Email", email));
params.add(new BasicNameValuePair("Mdp", mdp));
json = jsonParser.makeHttpRequest(url_parametres,
"POST", params);
}
try {
if(json != null && !json.isNull("yourArrayName")){
list.clear();
if (json.has("yourArrayName")) {
JSONArray ja = json.getJSONArray("yourArrayName");
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
String varietyNames= String.valueOf(c.getInt("varietyName"));
String varietyId= c.getString("varietyId"));
//store data in the list
list.add(new YourObjectName(varietyName, varietyId));
}
}
}
}
}} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
//here you create your adapter from that list
// and then Spinner.setAdapter(the Adapter);
}
}
you need jsonParser i think you have it... if you dont here it is :
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
now your data will be displayed correctly
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.
I'm trying to load a facebook photo by ID and place it in a ListView with my custom adapter.
My issue is that in MyAdapter, mIcon1 can't be resolved to a variable, and in LoadAllProducts, mIcon1 is not used.
It's obvious that I'm not properly referencing mIcon1 in the adapter, or I didn't set it up properly in LoadAllProducts, but I don't know which one is wrong!
Any help appreciated greatly! Thank you!
LoadAllProducts AsyncTask:
public class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading videos...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
String fbid = fbID;
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fbid", fbid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_videos, "POST", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
//GETTING PROFILE PICTURE START-----------------------//
URL img_value = null;
try {
img_value = new URL("http://graph.facebook.com/"+TAG_FACEBOOKID+"/picture?width=100&height=100");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
//GETTING PROFILE PICTURE END-----------------------//
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String facebookid = c.getString(TAG_FACEBOOKID);
String to_user = c.getString(TAG_TO_USER);
String available = c.getString(TAG_AVAILABLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_FACEBOOKID, facebookid);
map.put(TAG_TO_USER, to_user);
map.put(TAG_AVAILABLE, available);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} 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 products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
MyAdapter adapter = new MyAdapter(AllProductsActivity.this, R.layout.list_item, productsList);
// updating listview
setListAdapter(adapter);
}
});
}
}
MyAdapter:
public class MyAdapter extends ArrayAdapter<HashMap<String, String>> {
Context context;
int resourceId;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> items;
public MyAdapter (Context context, int resourceId, ArrayList<HashMap<String, String>> items)
{
super(context, resourceId, items);
this.items =items;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
final ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.userpicture=(ImageView)findViewById(R.id.userpicture);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
HashMap<String,String> item = (HashMap<String,String> ) items.get(position);
if (item != null)
{
// This is where you set up the views.
holder.name.setText(item.get(TAG_FACEBOOKID));
holder.userpicture.setImageBitmap(mIcon1);
}
return convertView;
}
public class ViewHolder
{
TextView name;
ImageView userpicture;
}
}
You didnt put any reference in the holder.userpicture.setImageBitmap(mIcon1); so the compiler will tell you that that variable mIcon1 does not exist please make it.
Also in the Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream()); no one can access mIcon1 outside the scope of the doInbackground.
Solution:
Make the MyAdapter as a inner of the LoadAllProducts and create a global variable inside the LoadAllProducts which is the Bitmap mIcon1 and use it in the background thread and in the adapter
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.