How to add Loading dialog While fetching image from server in Android? - 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

Related

RecycleView not calling methods

I'm trying to fetch data from a JSON, but it doesn't seem to work. OnBindViewHolder is never called...
ADAPTER CODE:
public class AdapterRallye extends RecyclerView.Adapter<AdapterRallye.MyViewHolder> implements View.OnClickListener {
private Context context;
private View.OnClickListener listener;
private List<DataRallye> data;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView Rallye_Nom;
public ImageView Rallye_Foto;
public TextView Rallye_Provincia;
public TextView Rallye_DataI;
public TextView Rallye_Tipus;
// create constructor to get widget reference
public MyViewHolder(final View itemView) {
super(itemView);
Rallye_Nom = (TextView) itemView.findViewById(R.id.tv_nom);
Rallye_Foto = (ImageView) itemView.findViewById(R.id.iv_foto);
Rallye_Provincia = (TextView) itemView.findViewById(R.id.tv_provincia);
Rallye_DataI = (TextView) itemView.findViewById(R.id.tv_datai);
Rallye_Tipus = (TextView) itemView.findViewById(R.id.tv_tipus);
}
}
// create constructor to innitilize context and data sent from MainActivity
public AdapterRallye(List<DataRallye> dadesrally) {
this.data = dadesrally;
}
// Inflate the layout when viewholder created
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.container_rallye, parent, false);
view.setOnClickListener(this);
return new MyViewHolder(view);
}
// Bind data
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
DataRallye current = data.get(position);
holder.Rallye_Nom.setText(current.getRallyeNom());
holder.Rallye_Tipus.setText(current.getRallyeTipus());
holder.Rallye_DataI.setText(current.getRallyeDataI());
holder.Rallye_Provincia.setText(current.getRallyeProvincia());
holder.Rallye_Provincia.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
// load image into imageview using glide
Glide.with(context).load("http://rallyecat.esy.es/fotos/" + current.getRallyeFoto())
.placeholder(R.drawable.rallyecatlogo)
.error(R.drawable.rallyecatlogo)
.into(holder.Rallye_Foto);
}
public void setOnClickListener(View.OnClickListener listener) {
this.listener = listener;
}
#Override
public void onClick(View view) {
if (listener != null)
listener.onClick(view);
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
}
FRAGMENT CODE:
public class FragmentRally extends Fragment {
public FragmentRally() {
// Required empty public constructor
}
private List<DataRallye> llistarallyes = new ArrayList<>();
private RecyclerView recyclerView;
private AdapterRallye mAdapter;
private Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_rally, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.llistarallyes);
mAdapter = new AdapterRallye(llistarallyes);
recyclerView.setAdapter(mAdapter);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
new AsyncFetch().execute();
mAdapter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(getActivity(), ActivitatDetalls.class);
intent.putExtra("nombarra", llistarallyes.get(recyclerView.getChildAdapterPosition(view)).getRallyeNom());
startActivity(intent);
}
});
return rootView;
}
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tCarregant...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json llistarallyes
url = new URL("http://www.rallyecat.esy.es/Obtenir_events.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive llistarallyes from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve llistarallyes from json file
//conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read llistarallyes sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line + "\n");
}
// Pass llistarallyes to onPostExecute method
return (result.toString());
} else {
Toast.makeText(getActivity(), "No hi ha connexió a internet.",
Toast.LENGTH_LONG).show();
return ("No hi ha connexió a internet.");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract llistarallyes from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataRallye dadesrallye = new DataRallye();
dadesrallye.setRallyeNom(json_data.getString("nom"));
dadesrallye.setRallyeTipus(json_data.getString("tipus"));
dadesrallye.setRallyeDataI(json_data.getString("datai"));
dadesrallye.setRallyeProvincia(json_data.getString("provincia"));
dadesrallye.setRallyeFoto(json_data.getString("foto"));
llistarallyes.add(dadesrallye);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.fragment_fragment_rally, parent, false));
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(v.getContext(), ActivitatDetalls.class);
context.startActivity(intent);
}
});
}
}
}
I've seen other StackOverflow posts where the problem is already solved, but I've been trying alot of the solutions the user said, but none is working...
Thanks!
Try to call mAdapter.notifyDataSetChanged(); in onPostExecute() method.
You need to notify your adapter after you made changes.

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));
}

progress bar freezes for few seconds and then grid view shows

ok im fetching images from server and showing them in a gridview with title ... im using baseadapter for gridview ... everything is working good and fine ... i have just one problem that i need to show a progressdialog when data is fetched from server and populated on the gridview ...
im using AsyncTask right now for showing progress dialog but it freezes for few (like 10) seconds and then gridview shows...
this is my baseadapter class:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = listInflater.inflate(R.layout.grid_adapter_view, null);
holder = new ViewHolder();
holder.gridImg = (ImageView) convertView
.findViewById(R.id.grid_item_image);
holder.gridTitle = (TextView) convertView
.findViewById(R.id.grid_item_label);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.gridTitle.setText(catItems.get(position).getName());
try {
URL url = new URL(catItems.get(position).getImg());
Bitmap img = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
holder.gridImg.setImageBitmap(img);
} catch (Exception e) {
// TODO Auto-generated catch block
holder.gridImg.setImageResource(R.drawable.no_image);
e.printStackTrace();
}
return convertView;
}
public class ViewHolder {
ImageView gridImg;
TextView gridTitle;
}
and here is asynctask im using:
mytask = new AsyncTask<Void, Void, Boolean>() {
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
main_grid.setAdapter(adater);
if (progress.isShowing()) {
progress.dismiss();
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress.show();
}
#Override
protected Boolean doInBackground(Void... params) {
JSONArray jArray = request.getCategories();
try {
for (int i = 0; i < jArray.length(); i++) {
CategoriesDetail catDetail = new CategoriesDetail();
JSONObject jobj = jArray.getJSONObject(i);
catDetail.setId(jobj.getString("id").toString());
catDetail.setName(jobj.getString("name").toString());
catDetail.setImg(jobj.getString("img").toString());
catDetail.setOrder(jobj.getString("order").toString());
items.add(catDetail);
}
adater = new CatGridAdapter(MainActivity.this, items);
return true;
} catch (Exception e) {
e.printStackTrace();
progress.dismiss();
Toast.makeText(MainActivity.this,
"Error: " + e.getMessage(), Toast.LENGTH_LONG)
.show();
return false;
}
}
};
please tell me where and what im doing wrong ...
You are doing a network operation on the UI thread.
BitmapFactory.decodeStream(url.openConnection().getInputStream());
Take a look at this: http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
EDIT:
Instead of decoding the stream in getView() only set the default image to the gridImg and trigger loadBitmap(catItems.get(position).getImg(), holder.gridImg).
public void loadBitmap(String url, ImageView imageView) {
new BitmapWorkerTask(imageView).execute(url);
}
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(String... params) {
return BitmapFactory.decodeStream(params[0].openConnection().getInputStream());
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
This is all described in the link above. You should really read it to get a better understanding of threading in android.

getView is called several times for the first position in GridView

I have an adapter with this getView:
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("getView gv", position+"");
NewsLine holder = null;
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.grid_entry, parent, false);
holder = new NewsLine();
holder.iv= (ImageView) convertView.findViewById(R.id.photo);
convertView.setTag(holder);
} else {
holder = (NewsLine) convertView.getTag();
}
NewsItem item=news.ITEMS.get(position);
//---------
if(item.imgurl!=null && item.imgurl.compareToIgnoreCase("null")!=0)
{
holder.iv.setVisibility(View.VISIBLE);
mMemoryCache.loadBitmap(item.imgurl, holder.iv,position);
}
else
holder.iv.setVisibility(View.INVISIBLE);
//-------------
return convertView;
}
I have two problems:
the getView is called several times for position 0 (the bitmap is downloaded with an AsyncTask if its missed in a LruCache). I have an animation (alpha from 0-1) that restarts several times for that position.
because I'm recycling the view sometimes you can see the old imageView content for a fraction of a second.
//----
And here is the cache class (only heap):
public class SetImgAT extends LruCache<String, Bitmap> {
private static SetImgAT instance;
private Animation FadeInAnimation;
private SetImgAT(int size, Context context) {
super(size);
FadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fadein);
}
public static synchronized SetImgAT getInstance(int size, Context context) {
if (instance == null) {
instance = new SetImgAT(size, context);
}
return instance;
}
#Override
protected int sizeOf(String key, Bitmap value) {
return (value.getRowBytes() * value.getHeight());
}
public void loadBitmap(String url, ImageView imageView,int pos) {
Bitmap bitmap = instance.get(url.hashCode() + "");
if (bitmap != null) {
Log.d("ImageCache", "hit - "+url.hashCode()+"pos:"+pos);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} else {
Log.d("ImageCache", "miss");
BitmapWorkerTask task = new BitmapWorkerTask(imageView);
task.execute(url);
}
}
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
ImageView mImageView;
public BitmapWorkerTask(ImageView imageView) {
mImageView = imageView;
}
#Override
protected Bitmap doInBackground(String... url) {
Bitmap Picture = null;
if (url[0] != null && url[0].compareToIgnoreCase("null") != 0) {
Log.d("GetBMP from", url[0]);
URL img_value = null;
try {
img_value = new URL(url[0]);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Picture = BitmapFactory.decodeStream(img_value
.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Picture == null) {
Log.d("deb", "no bitmap");
} else {
Log.d("got deb", "got bitmap to "+url[0].hashCode());
instance.put(url[0].hashCode()+"", Picture);
}
}
return Picture;
}
#Override
protected void onPostExecute(Bitmap result) {
// super.onPostExecute(result);
if (result != null) {
Log.d("deb", "set bitmap");
mImageView.setImageBitmap(result);
//mImageView.startAnimation(FadeInAnimation);
}
}
}
//----------------
}
Thank you! :)
I've seen similar behavior when scrolling back and forth or haphazardly calling notifyDataSetChanged().
As an enhancement to what you are doing now I would suggest using Picasso instead since it handles this case very well, in addition to the fade in animation.
A one liner in your getView():
Picasso.with(context).load(urlToLoad).into(imageView);
See:
http://square.github.io/picasso/

Progress Dialog in GridView

My code as follows:
public class wall extends Activity {
GridView webgridview;
Button web;
ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wall);
pd = ProgressDialog.show(wall.this,"Loading", "Please Wait...",true);
new Thread() {
public void run() {
try {
webgridview.setAdapter(new WebImageAdapter(wall.this));
}catch(Exception e)
{
}
handler.sendEmptyMessage(0);
pd.dismiss();
}
}.start();
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
Toast.makeText(wall.this, "finished", 1).show();
}
};
And my adapter class as follows. I code progress dialog in above class only.
public class WebImageAdapter extends BaseAdapter {
private Context mContext;
public static String[] myRemoteImages = {
"http://www.evergreenhits.com/ad/wallpapers/3d_1.jpg",
"http://www.evergreenhits.com/ad/wallpapers/3d_2.jpg",
"http://www.evergreenhits.com/ad/wallpapers/3d_3.jpg",
"http://www.evergreenhits.com/ad/wallpapers/3d_4.jpg",
"http://www.evergreenhits.com/ad/wallpapers/3d_5.jpg"
};
public WebImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
//return animals.length;
return this.myRemoteImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public ImageView getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
imageView = new ImageView(mContext);
if (convertView == null) {
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
try {
URL aURL = new URL(myRemoteImages[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Drawable d=Drawable.createFromStream(bis, "src Name");
bis.close();
is.close();
imageView.setImageDrawable(d);
} catch (IOException e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
return imageView;
}
The progress Dialog doesnt work properly. It shows and suddenly gone before the images loaded in gridview. Please help me asap.
Use AsyncTask:
calling:
dialog=ProgressDialog.show(wall.this,"Loading", "Please Wait...",true);
doback dob=new doback();
dob.execute();
Class
class doback extends AsyncTask<URL, Integer, Long>
{
#Override
protected Long doInBackground(URL... arg0)
{
try
{
//getImagepaths from Server
}
catch(Exception e)
{
}
return null;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Long result)
{
try
{
webgridview.setAdapter(new WebImageAdapter(wall.this));
dialog.dismiss();
}
catch(Exception e)
{
e.printStackTrace();
dialog.dismiss();
}
}
}
Adapter Code is some like this:
class WebImageAdapter extends BaseAdapter{
// #Override
public int getCount() {
return names.length;
}
// #Override
public Object getItem(int position) {
return null;
}
// #Override
public long getItemId(int position) {
return 0;
}
// #Override
public View getView(int pos, View convertView, ViewGroup parent) {
View row=getLayoutInflater().inflate(R.layout.nameitem,null);
ImageView image=(ImageView)row.findViewById(R.id.image);
image.setImageBitmap(convertImage(myRemoteImages[position]))// convertImage is to convert url to bitmap
return row;
}
}
Edit - From the Android Developer Documentation:ProgressDialog
This class was deprecated in API level 26.
ProgressDialog is a modal
dialog, which prevents the user from interacting with the app. Instead
of using this class, you should use a progress indicator like
ProgressBar, which can be embedded in your app's UI. Alternatively,
you can use a notification to inform the user of the task's progress.
setAdapter(), do not take more time, its getView() of Adapter class on each time hit web and taking time. So using of progressDialog on setAdapter is not appropriate. On scroll of your grids it took lot of time by using your code, as getView() call automatically on scrolling view.
you should have a reference from LazyList for loading image from web and placing them in ImageView.

Categories

Resources