Load items on ViewHolderAdapter - android

I have implemented a ViewHolderAdapter to load items and display it on a ListView, but I want to display also a AdMob Banner in some rows. I have created a custom Adapter for two different Layouts. But the problem is that only display two rows, one for each Layout, when the item list is longer than 400 items.
Somebody can help me?
I show the code below:
[![enter image description here][1]][1]public class SubliguesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static List<Subligues> items;
public static class ClasGeneralViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
// Campos respectivos de un item
public TextView subligue_name;
public TextView created_at;
public TextView members;
public ImageView icon;
public ClasGeneralViewHolder(View v) {
super(v);
subligue_name = (TextView) v.findViewById(R.id.txt_subligue_name);
created_at = (TextView) v.findViewById(R.id.txt_created_at);
members = (TextView) v.findViewById(R.id.txt_members);
icon = (ImageView) v.findViewById(R.id.imageViewIcon);
v.setOnClickListener(this);
}
public void onClick(View view){
String subligue_name= items.get(getPosition()).getSubligueName();
// Launch RegisterUser
Intent intent = new Intent(view.getContext(),
RegisterUser.class);
// Pasar el nombre de la liga del usuario a RegisterUser.java
intent.putExtra("subligue_name",subligue_name);
view.getContext().startActivity(intent);
((Activity) view.getContext()).finish();
}
}
public static class BannerViewHolder extends RecyclerView.ViewHolder{
// Admob banner
public AdView mAdView;
public BannerViewHolder(View v) {
super(v);
mAdView = (AdView) v.findViewById(R.id.adView);
}
}
#Override
public int getItemViewType(int position) {
// here your custom logic to choose the view type
return position %10;
}
public SubliguesAdapter(List<Subligues> items) {
this.items = items;
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
switch (i) {
case 0:
View v2 = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_banner, viewGroup, false);
return new BannerViewHolder(v2); // view holder for banner items;
case 1:
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.activity_register_existente_abierta_card, viewGroup, false);
return new ClasGeneralViewHolder(v); // view holder for normal items;
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int i) {
switch (viewHolder.getItemViewType()) {
case 0:
BannerViewHolder viewHolder2 = (BannerViewHolder)viewHolder;
AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
viewHolder2.mAdView.loadAd(adRequest);
break;
case 1:
ClasGeneralViewHolder viewHolder0 = (ClasGeneralViewHolder)viewHolder;
viewHolder0.subligue_name.setText(String.valueOf(items.get(i).getSubligueName()));
String created_at = items.get(i).getCreatedAt().substring(0, items.get(i).getCreatedAt().length() - 9);
viewHolder0.created_at.setText(created_at);
viewHolder0.members.setText(String.valueOf(items.get(i).getMembers())+" ");
new ImageDownloaderTask(viewHolder0.icon).execute(items.get(i).getIcon());
break;
}
}
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) {
return downloadBitmap(params[0]);
}
#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.no_team);
imageView.setImageDrawable(placeholder);
}
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}

#Override
public int getItemViewType(int position) {
// here your custom logic to choose the view type
return position %2;
}
I haven't run ur code but clearly this part is responsible for displaying different views in alternative viewholders, because you are taking modulus by 2, which will return you 0 for even numbers and 1 for odd numbers.
Do two things
return position % 10 will increase interval for ads you can give
any number after which u want to put ad.
Also to make it work perfectly with this logic change case 0 to adview and 1 to otherview.
This will resolve your problem.

Related

Listview item image and textview reloading in multiple position in Realmbaseadapter

According to my app requirement I am showing a row with textbox,imageview and image capture button in a listview. I am capturing an image and immediately saving that image in that realm row. Then adapter loads that image from related realm object when adaoter getview method gets called.
My problem is when the row data for each list is blank, has more than 4 rows and capturing any image; captured image gets loaded in several position along with the position it is meant to be.
For example if I take image for position 0 it shows after scrolling in position 5,then again reloads to position 6. I have noticed that since after scrolling from position 0 to position 6 adapter position returns 0 again. Which is the reason of the image reloading during scrolling in other positions. When I click in any button for either taking picture/text input this reloaded row again returns to proper position.
I went through almost all possible suggested SO questions related to issue imageview shuffling in listview but none of them works for me.Could you suggest any solution to this problem.
My Adapter code is below-
public class ProgressImageAdapter extends RealmBaseAdapter<ImageCommentRealm> implements ListAdapter {
private Context mContext;
String categoryName;
ProgressListener progressListener;
PopAlertDialog alertDialog;
boolean fromHistory;
public ProgressImageAdapter(Context context, OrderedRealmCollection<ImageCommentRealm> data, ProgressListener progressListener, boolean fromHistory) {
super(context, data);
this.mContext = context;
this.progressListener = progressListener;
FragmentActivity activity = (FragmentActivity) (context);
alertDialog = PopAlertDialog.createAlert(activity.getSupportFragmentManager());
this.fromHistory = fromHistory;
}
#Override
public void updateData(OrderedRealmCollection<ImageCommentRealm> data) {
super.updateData(data);
}
public void resetListener() {
this.progressListener = null;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.image_comment_list_item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.tv_title);
holder.editText = (TextView) convertView.findViewById(R.id.et_comment);
holder.imageView = (ImageView) convertView.findViewById(R.id.iv_camera_holder);
holder.imageButton = (ImageButton) convertView.findViewById(R.id.imgbtn_camera);
holder.btnDone = (Button) convertView.findViewById(R.id.btn_confirm);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ImageCommentRealm imageCommentRealm = getItem(position);
holder.textView.setText(String.format(Locale.getDefault(), "%s %d %2s %2s", mContext.getResources().getString(R.string.photo), position + 1, mContext.getString(R.string.of), categoryName));
if (Validator.blankCheck(imageCommentRealm.getFile_path()))
loadImage(holder.imageView, imageCommentRealm.getFile_path());
if (Validator.blankCheck(imageCommentRealm.getDesc()))
holder.editText.setText(imageCommentRealm.getDesc());
if (!fromHistory) {
holder.imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity) mContext).pickFromCamera();
((MainActivity) mContext).setPicker(new IPhotoPicker() {
#Override
public void setImageUri(String filePath) {
//loadImage(holder,filePath);
saveData(null, filePath, imageCommentRealm.getPk());
}
});
}
});
holder.editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = String.format(Locale.getDefault(), "%s %d %2s %2s", mContext.getResources().getString(R.string.description), position + 1, mContext.getString(R.string.of), categoryName);
alertDialog.showSingleInput(title, imageCommentRealm.getDesc(), imageCommentRealm.getPk(), new SingleInput.Listener() {
#Override
public void onClickGreen(String message, long id) {
if (Validator.blankCheck(message)) saveData(message, null, id);
}
});
}
});
}
return convertView;
}
protected void loadImage(ImageView imageView, String imgPath) {
if (imgPath.startsWith("http")) {
ImageUtility.loadProduct(mContext, imgPath, imageView, R.drawable.home);
} else {
try {
File image_file = new File(imgPath);
if (image_file.exists()) {
Bitmap image_profile = BitmapFactory.decodeFile(image_file.getAbsolutePath());
imageView.setImageBitmap(image_profile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void saveData(final String comment, final String filepath, final long pk) {
final Realm realm = Realm.getInstance(RealmUtility.getRealmConfig(mContext));
//ImageCommentRealm imageRealm = getItem(position);
//final long pk = imageRealm.getPk();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ImageCommentRealm imageCommentRealm = realm.where(ImageCommentRealm.class).equalTo("pk", pk).findFirst();
if (imageCommentRealm != null && imageCommentRealm.isLoaded()) {
if (Validator.blankCheck(comment)) {
imageCommentRealm.setDesc(comment);
}
if (Validator.blankCheck(filepath)) {
imageCommentRealm.setFile_path(filepath);
}
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
//notifyDataSetChanged();
realm.close();
try {
if (adapterData != null && adapterData.size() > 0) {
long count = adapterData.where().isNotNull("file_path").isNotNull("desc").count();
if (count == adapterData.size()) {
if (progressListener != null) progressListener.hasRequiredImage();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
error.printStackTrace();
realm.close();
}
});
}
static class ViewHolder {
TextView textView;
TextView editText;
ImageView imageView;
ImageButton imageButton;
Button btnDone;
}
}
Here is a screenshot after taking picture in first position and then scrolling to bottom
FYI: Testing device 4" Samsung J1 Nxt
Eh, this has nothing to do with Realm, you should clear the image if the image path is null.
if (Validator.blankCheck(imageCommentRealm.getFile_path())) {
loadImage(holder.imageView, imageCommentRealm.getFile_path());
} else {
holder.imageView.setImageBitmap(null);
}
if (Validator.blankCheck(imageCommentRealm.getDesc()))
holder.editText.setText(imageCommentRealm.getDesc());
} else {
holder.editText.setText("");
}

how to handling button click in tab fragment using RecyclerViewAdapter?

currently i had come out a screen that using tab fragment and RecyclerView like below. I want to know how i going to handle the button click that circle in red. Every time i click, i have get the details of the product that i want to add into the cart. Since the screen that i come out is using RecyclerView , so i'm confusing how to get all the details of the product that i want.
enter image description here
Adapter code
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView row_image;
TextView title;
TextView description;
public ViewHolder(View v, Context c) {
super(v);
mContext = c;
row_image = (ImageView) v.findViewById(R.id.row_image);
title = (TextView) v.findViewById(R.id.row_title);
description = (TextView) itemView.findViewById(R.id.row_description);
}
}
public CatalogPageAdapter(List<CatalogViewData> dataset) {
mDataset = dataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.catalog_layout, parent, false);
return new ViewHolder(v,parent.getContext());
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
final CatalogViewData fakePageVH = mDataset.get(i);
String points = Double.toString(Double.parseDouble(fakePageVH.getDescription()));
viewHolder.title.setText(fakePageVH.getTitle());
viewHolder.description.setText(points);
String var = fakePageVH.getImage();
new getImage(var, viewHolder).execute();
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Title: " + fakePageVH.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
public class getImage extends AsyncTask<String, String, String> {
String imageUrl;
ViewHolder holder;
Bitmap downloadedBitmap;
Bitmap scaled;
public getImage(String url, ViewHolder h){
imageUrl = url;
holder = h;
}
#Override
protected String doInBackground(String... args) {
try {
URL url = new URL(imageUrl);
downloadedBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
scaled = Bitmap.createScaledBitmap(downloadedBitmap, 150, 100, true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "done";
}
#Override
protected void onPostExecute(String result) {
holder.row_image.setImageBitmap(scaled);
}
}
#Override
public int getItemCount() {
return mDataset == null ? 0 : mDataset.size();
}
}
I guess the green icon isn't an ImageView otherwise would be a silly question. Add an empty ImageView, place it exactly on your circle. Then add it into your viewholder and use viewHolder.dummyImageView.setOnClickListener.
EDIT
xml:
<ImageView
android:id="#+id/dummyImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
VievHolder:
public ViewHolder(View v, Context c) {
super(v);
dummyImage = (ImageView) v.findViewById(R.id.dummyImageView);
}
OnClickListener:
ImageView dummyImage;
viewHolder.dummyImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Click!", Toast.LENGTH_SHORT).show();
}
});

Reload ImageView by URI on ListView

I have a ListView of elements composed with ImageView. I get a new image using an AsyncTask and in the onPostExecute(Object result) method I set the image using setImageUri(Uri uri) but it doesn't gets updated.
If I change of activity or between apps, image is shown perfectly, but I want to show the image immediately.
I tried calling invalidate() with all the combinations of the ImageView, the extended BaseAdapter, the parent ListView, but nothing worked. I tried many other techniques like calling setImageResource(0), setImageUri(null), but no results...
EDITED:
Here, part of the code:
public class ThingItemAdapter extends BaseAdapter {
protected List<Thing> things;
LayoutInflater inflater;
public ThingItemAdapter(Context context, List<Thing> things) {
this.things = things;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return things.size();
}
#Override
public Thing getItem(int position) {
return things.get(position);
}
#Override
public long getItemId(int position) {
return things.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.thing_list_item, parent, false);
holder.thingImageView = (ImageView) convertView.findViewById(R.id.thing_preview);
holder.button = (ImageButton) convertView.findViewById(R.id.apply_button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Thing thing = things.get(position);
final long thingId = thing.getId();
final Uri thingUri = thing.getPicture();
holder.thingImageView.setImageURI(thingUri);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// generate new file
final TypedFile typedFile = new TypedFile("multipart/form-data", new File(thingUri.getPath()));
new ReadAndStorePictureTask()
.execute(new Object[] { typedFile, holder.thingImageView, thing });
}
});
// item detailed view listener
holder.thingImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent((ThingApplication) ThingApplication.getContext(), ThingActivity.class);
intent.putExtra(ThingActivity.EXTRA_THING_ID, thingId);
context.startActivity(intent);
}
});
return convertView;
}
private class ViewHolder {
ImageView thingImageView;
ImageButton button;
}
private class ReadAndStorePictureTask extends AsyncTask<Object, Void, Void> {
ImageView imageView;
Thing thing;
ViewGroup parent;
protected Void doInBackground(Object... params) {
final TypedFile typedFile = (TypedFile) params[0];
imageView = (ImageView) params[1];
thing = (Thing) params[2];
((ThingApplication) ThingApplication.getContext()).getClient().apply(typedFile,
new Callback<Response>() {
#Override
public void failure(RetrofitError error) {
...
}
#Override
public void success(Response nothing, Response response) {
try {
byte[] bytes = ThingApplication.getBytesFromStream(response.getBody().in());
Uri newImageURI = Uri.parse("uri://valid_uri"); // whatever, it exists in real code
thing.setPicture(newImageURI);
File file = ((ThingApplication) ThingApplication.getContext())
.getFileFromURI(newImageURI); // this method works
ThingApplication.saveBytesToFile(bytes, file.getAbsolutePath());
thingService.storeThing(thing);
} catch (Exception e) {
...
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
imageView.setImageURI(thing.getPicture());
// force redraw. FIXME not working
/*
* ANSWER HERE, PLEASE
*/
}
}
}
How can I show the updated URI immediately inside onPostExecute(Object result) method?
onPostExecute you update the list of images that it's linked to the ListView adapter and after that you notify the adapter that you changed the items in the list by calling:
adapter.notifyDataSetChanged();
You can do something like this:
-Change third parameter in asynctask call.
new ReadAndStorePictureTask().execute(
new Object[] { typedFile, holder.thingImageView, pos });
-Then, modify the list items inside asynctask and refresh.
private class ReadAndStorePictureTask extends AsyncTask<Object, Void, Void> {
ImageView imageView;
int position;
ViewGroup parent;
protected Void doInBackground(Object... params) {
final TypedFile typedFile = (TypedFile) params[0];
imageView = (ImageView) params[1];
position = (Integer) params[2];
((ThingApplication) ThingApplication.getContext()).getClient().apply(typedFile,
new Callback<Response>() {
#Override
public void failure(RetrofitError error) {
...
}
#Override
public void success(Response nothing, Response response) {
try {
byte[] bytes = ThingApplication.getBytesFromStream(response.getBody().in());
Uri newImageURI = Uri.parse("uri://valid_uri"); // whatever, it exists in real code
things.get(position).setPicture(newImageURI);
File file = ((ThingApplication) ThingApplication.getContext())
.getFileFromURI(newImageURI); // this method works
ThingApplication.saveBytesToFile(bytes, file.getAbsolutePath());
thingService.storeThing(things.get(position));
} catch (Exception e) {
...
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
notifyDataSetChanged();
}
}
Good luck!

updating of Image Thumbnails using AsyncTask for Android ListView not coming proper

I am getting a big response from the server with data and image url. I need to display them on the List View. Images should be like thumbnails. To make it proper i have customized my Adapter and getting the images using Async Task. Here is my Adapter and Asynctask Code:
public class TalkofTownAdapter extends BaseAdapter{
private LayoutInflater inflater = null;
private Context context = null;
ImageView thumb_image = null;
private ProgressDialog progressbar = null;
ArrayList<String> items;
ArrayList<String> thumb_url;
public TalkofTownAdapter(Context c, ArrayList<String> list, ArrayList<String> thumb)
{
this.context = c;
this.items = list;
this.thumb_url = thumb;
progressbar = new ProgressDialog(c);
Log.d("Testing", "talk of town adapter constructor "+items.size());
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.talkoftown, null);
Log.d("Testing", "before creating holder object");
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.list_title);
holder.duration = (TextView)convertView.findViewById(R.id.duration);
holder.imageView = (ImageView) convertView.findViewById(R.id.list_image_playlist);
Log.d("Testing", "image view created :::::::: ");
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.d("Testing", "text::: "+items.get(position));
holder.headlineView.setText(items.get(position));
Log.d("Testing", "settting the text ");
holder.duration.setText("22/09/1987");
if (holder.imageView != null) {
Log.d("Testing", "getting the image "+thumb_url.get(position));
new ImageDownloaderTask(holder.imageView).execute(thumb_url.get(position));
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView duration;
ImageView imageView;
}
public static Bitmap getBitmapFromURL(String src) {
try {
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.d("Testing", "image loaded "+myBitmap);
// myBitmap = Bitmap.createBitmap(100, 50, Config.ARGB_8888);
myBitmap = Bitmap.createScaledBitmap(myBitmap,(int)(myBitmap.getWidth()), (int)(myBitmap.getHeight()), true);
return myBitmap;
} catch (IOException e) {
Log.d("Testing", "exception is getting the image "+e.toString());
e.printStackTrace();
return null;
}
}
public void startProgress()
{
progressbar.setMessage("Please wait");
progressbar.show();
}
public void stopProgress()
{
progressbar.dismiss();
}
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
return getBitmapFromURL(params[0]);
}
#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) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageDrawable(imageView.getContext().getResources()
.getDrawable(R.drawable.rihanna));
}
}
}
}
}
Now the thumbnails are showing with the default image and then changing with downloaded images. But if i am scrolling down the list view, images are keep on changing and coming duplicates of those that appeared in the rows above that were already scrolled up. So i mean to say here, the images are coming on proper order for the corresponding rows. I know there are lots of tutorials and QA here also. But i have tried lots of solutions and it did not work properly.
Can any one help me on this?
The problem is with you if condition. Just remove the if condition if (holder.imageView != null) { the problem is each and everytime getView will check for your view is null or not and based on that it will execute and inflate the image.
Change your if condition like
if(thumb_url.get(position) !=null)
{
Log.d("Testing", "getting the image "+thumb_url.get(position));
new ImageDownloaderTask(holder.imageView).execute(thumb_url.get(position));
}

How to add Loading dialog While fetching image from server in Android?

I am trying to add Loading dialog in following code to fetch image from server and display it in Gallery view. it shows blank screen untill image comes. please help me how do i show Loading dialog while getting image from server.
Here is the code, pls help.
public class ImagedisplaytestActivity extends Activity {
private ImageView leftArrowImageView;
private ImageView rightArrowImageView;
private Gallery gallery;
public int selectedImagePosition;
private GalleryImageAdapter galImageAdapter;
private String bitmapImg = "";
Bitmap bitmap = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupUI();
}
private void setupUI() {
Intent i = getIntent();
Bundle extras=i.getExtras();
bitmapImg = extras.getString("BitmapImage");
selectedImagePosition = extras.getInt("Pos");
leftArrowImageView = (ImageView) findViewById(R.id.left_arrow_imageview);
rightArrowImageView = (ImageView) findViewById(R.id.right_arrow_imageview);
gallery = (Gallery) findViewById(R.id.gallery);
leftArrowImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (selectedImagePosition > 0) {
--selectedImagePosition;
}
gallery.setSelection(selectedImagePosition, false);
}
});
rightArrowImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (selectedImagePosition < DetailView.bitmapURL.size() - 1) {
++selectedImagePosition;
}
gallery.setSelection(selectedImagePosition, false);
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selectedImagePosition = pos;
if (selectedImagePosition > 0 && selectedImagePosition < DetailView.bitmapURL.size() - 1) {
leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_disabled));
rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
} else if (selectedImagePosition == 0) {
leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_enabled));
} else if (selectedImagePosition == DetailView.bitmapURL.size() - 1) {
rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_enabled));
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
galImageAdapter = new GalleryImageAdapter(this, DetailView.bitmapURL);
gallery.setAdapter(galImageAdapter);
if (DetailView.bitmapURL.size() > 0) {
gallery.setSelection(selectedImagePosition, false);
}
if (DetailView.bitmapURL.size() == 1) {
rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
}
}
public class GalleryImageAdapter extends BaseAdapter {
private Activity context;
private ImageView imageView;
private List<String> plotsImages;
private ViewHolder holder;
public GalleryImageAdapter(Activity context, List<String> plotsImages) {
this.context = context;
this.plotsImages = plotsImages;
}
#Override
public int getCount() {
return plotsImages.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
imageView = new ImageView(this.context);
imageView.setPadding(3, 3, 3, 3);
convertView = imageView;
holder.imageView = imageView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
holder.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
try {
bitmap = DownloadImage(plotsImages.get(position));
holder.imageView.setImageBitmap(bitmap);
bitmap = null;
} catch (Exception e) {
e.printStackTrace();
}
return imageView;
}
private class ViewHolder {
ImageView imageView;
}
private Bitmap DownloadImage(String URL){
Bitmap bitmap = null;
try {
InputStream in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
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
public void onBackPressed() {
DetailView.bundleID = DetailView.idList.get(selectedImagePosition);
super.onBackPressed();
}
}
You should use AsyncTask!
See this also!
& in Vogella Example will clear your doubt .
see this for the lazy image Loading DEMO! on github.
use assynctask,
in that assynctask method you can write your getting images from server in doinbackground(),
in that time you can display alert dialogue using preexectue(), after loading from server just dismiss the alert dialogue in postexectue().
This code work for me
private class LoadGlobalDataSearch extends AsyncTask<String, Void, Void>
{
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected Void doInBackground(String... params)
{
//Load your images this task
setupUI();
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressdialog = ProgressDialog.show(MainActivity.this, "",getString(R.string.inprogress));
}
}
call this class in your oncreate method
new loadImages().execute(0);
You can use a progress dialoge until the image is downloaded then remove the dialog.
In OpenHttpConnection add this --
dialog = ProgressDialog.show(DutyRotaActivity.this, "",
"Please wait for few seconds...", true);
in DownloadImage dissmiss the dialog.
dialog.dismiss();
Or you can use asynchronous task too. cause network operation should always do on other thread
not in the main thread. In that case in preExecute add the dialog and in postExecute dissmiss the dialog. And in doinbackground call your downloadimage function that will also do the tricks.
Edit
Here is a complete source code and a library to load image lazily in the listView. I think its also can help you to solve your issue.Thanks
https://github.com/nostra13/Android-Universal-Image-Loader

Categories

Resources