I use the function to show picture:
Bitmap imageBitmap = loadBitmap(URL);
loadBitmap() as below:
private Bitmap loadBitmap(String url) {
try {
Bitmap bm = BitmapFactory.decodeStream((InputStream)this.fetch(url));
return bm;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
And fetch() below:
public Object fetch(String address) {
try {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
catch(Exception e) {
e.printStackTrace();
}
return this;
}
I want to show the loading progress or a load.png while it loading.
And end with the picture loading finish and show it.
How can I do?
I try to make like ProgressDialog.
But I don't know how to use?
You can use AsyncTask to show a Progress Dialog on the PreExecute() method and hide/dismiss it in the PostExecute() method.
ProgressDialog prog = new ProgressDialog(this); // Create Progress Dialog
private class DownloadBitmap extends AsyncTask<Void, Integer, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Display progressDialog before download starts
prog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prog.hide(); //Hide Progress Dialog else use dismiss() to dismiss the dialog
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
/*
* Perform download and Bitmap conversion here
*
*/
return null;
}
}
And finally call the AsyncTask through,
DownloadBitmap dd = new DownloadBitmap();
dd.execute();
You can use a ProgressBar for this.
Check out these links:
Tutorial 1
Tutorial 2
you can't do that directly, as Android doesn't support GIF files. So to away with that you have to create separate image (loading image into split images) and make animation of it. At the time of loading run the animation and once Bitmap avail stop animation and set Bitmap on ImageView
This example shows progressbar while downloading the image and later it is invisible.
public class ImageDownload extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
ImageView mainImageView = (ImageView) findViewById(R.id.imageView);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
String imageurl = "http://ipadwallpaperportal.com/wp-content/main/2011_09/purple-flower-close-up-1024x1024-wallpaper.jpg";
ImageDownloadMessageHandler imageDownloadMessageHandler1 = new ImageDownloadMessageHandler(
progressBar, mainImageView);
ImageDownlaodThread imageDownlaodThread = new ImageDownlaodThread(
imageDownloadMessageHandler1, imageurl);
imageDownlaodThread.start();
}
class ImageDownlaodThread extends Thread {
ImageDownloadMessageHandler imageDownloadMessageHandler;
String imageUrl;
public ImageDownlaodThread(
ImageDownloadMessageHandler imageDownloadMessageHandler,
String imageUrl) {
this.imageDownloadMessageHandler = imageDownloadMessageHandler;
this.imageUrl = imageUrl;
}
#Override
public void run() {
Drawable drawable = LoadImageFromWebOperations(imageUrl);
Message message = imageDownloadMessageHandler.obtainMessage(1,
drawable);
imageDownloadMessageHandler.sendMessage(message);
System.out.println("Message sent");
}
}
class ImageDownloadMessageHandler extends Handler {
ProgressBar progressBar;
View imageTextView;
public ImageDownloadMessageHandler(ProgressBar progressBar,
View imageTextView) {
this.progressBar = progressBar;
this.imageTextView = imageTextView;
}
#Override
public void handleMessage(Message message) {
progressBar.setVisibility(View.GONE);
imageTextView.setBackgroundDrawable(((Drawable) message.obj));
imageTextView.setVisibility(View.VISIBLE);
}
}
Drawable LoadImageFromWebOperations(String strUrl) {
/**
* This is one method
*/
long x1 = System.currentTimeMillis();
Drawable d = null;
InputStream is = null;
try {
is = (InputStream) new URL(strUrl).getContent();
d = Drawable.createFromStream(is, "src name");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
long x2 = System.currentTimeMillis();
long res = x2 - x1;
Log.v("Image Downloading Time", "" + res);
}
Related
How to download images from server without pressing the button in Android Studio. The code runs ok but only if I press the button to download. How to make automatically download the image
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.bDownloadImage:
new DonwloadImage(downloadImageName.getText().toString()).execute();
break;
}
}
private class DonwloadImage extends AsyncTask<Void, Void, Bitmap> {
String name;
ProgressDialog loading;
public DonwloadImage (String name){//constractor
this.name = name;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Receiver.this);
mProgressDialog.setTitle("Downloading Image"); // title of progress dialog
mProgressDialog.setMessage("Loading..."); // message displaying
mProgressDialog.setIndeterminate(false);
mProgressDialog.show(); // show method
}
#Override
protected Bitmap doInBackground(Void... voids) {
// loading.dismiss();
String url = SERVER_ADDRESS + "pictures/" + name + ".JPG";
try
{
URLConnection connection = new URL(url).openConnection();
connection.setConnectTimeout(1000 * 30);
connection.setReadTimeout(1000 * 30);
return BitmapFactory.decodeStream((InputStream) connection.getContent(), null, null);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Bitmap bitmap)
{
super.onPostExecute(bitmap);
if(bitmap != null)
{
downloadImage.setImageBitmap(bitmap);
mProgressDialog.dismiss();
}
}
}
you should add
DonwloadImage(downloadImageName.getText().toString()).execute();
in onCreate of Activity, for autoDownload property.
I have implemented a simple custom progress dialog, which I show on onPreExecute method. However after the show of dialog AsycnTask does not progress to doInBackground method. Hence dialog is shown for ever. When I comment out the dialog show it works fine. Please see the code below. How can I resolve this.
public class CustomProgressDialog extends ProgressDialog
{
public CustomProgressDialog(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customprogress);
}
#Override
public void show() {
super.show();
}
}
private CustomProgressDialog getProgressDialog() {
CustomProgressDialog p = new CustomProgressDialog(activity);
p.setCancelable(true);
p.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
loadMainFragment();
if(imageTask != null)
imageTask.cancel(true);
}
});
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
CustomProgressDialog ringProgressDialog = null;
Bitmap bitmap = null;
#Override
protected Bitmap doInBackground(String... param) {
Bitmap b = downloadBitmap(param[0]);
image = b;
return b;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
ringProgressDialog = getProgressDialog()
ringProgressDialog.show();
// after showing this no progression
}
#Override
protected void onPostExecute(Bitmap result) {
if(isCancelled())
return;
if (result == null)
return;
super.onPostExecute(result);
bitmap = result;
// do work
if(ringProgressDialog != null)
ringProgressDialog.dismiss();
}
private Bitmap downloadBitmap(String url) {
Bitmap bm = null;
InputStream is = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.setConnectTimeout(Utils.timeout);
conn.setReadTimeout(Utils.timeout);
conn.connect();
is = conn.getInputStream();
bm = Utils.decodeBitmapFromInputStream(is,width, width, true);}
catch(Exception e){}
return bm;
}
I'm trying to display an image from a url in a "InfoWindowAdapter" ,I have the following code, but does not show me the image. What is wrong please ?
public class ObjectInfoWindow implements GoogleMap.InfoWindowAdapter {
private Activity activity;
private HashMap<String, LostObject> markers;
private Marker markerShowingInfoWindow;
private boolean mRefreshingInfoWindow;
private View v = null;
ImageUrlView imgThumbnail;
public LostObjectInfoWindow(Activity activity, HashMap<String, LostObject> markers) {
this.activity = activity;
this.markers = markers;
}
#Override
public View getInfoContents(Marker marker) {
DebugLog.d("TAG", "getInfoContents mRefreshingInfoWindow "+mRefreshingInfoWindow);
if(v==null){
v = activity.getLayoutInflater().inflate(R.layout.lost_object_info_window, null);
}
LostObject lostObject = markers.get(marker.getId());
if (lostObject != null) {
String imgThumbnailPath = lostObject.getPhoto();
if(imgThumbnailPath==null || imgThumbnailPath.trim().length() == 0){
TextView title = (TextView) v.findViewById(R.id.title);
TextView description = (TextView) v.findViewById(R.id.description);
title.setText(lostObject.getType());
if (lostObject.getContact() != null) {
description.setText(activity.getResources().getString(R.string.lost_object_contact_info_window, lostObject.getContact()));
}
imgThumbnail = (ImageUrlView) v.findViewById(R.id.thumbnail);
imgThumbnail.setScaleType(ImageView.ScaleType.FIT_CENTER);
imgThumbnail.setImageResource(R.drawable.ic_ayn_list_grey);
} else {
if (!mRefreshingInfoWindow) {
TextView title = (TextView) v.findViewById(R.id.title);
TextView description = (TextView) v.findViewById(R.id.description);
title.setText(lostObject.getType());
if (lostObject.getContact() != null) {
description.setText(activity.getResources().getString(R.string.lost_object_contact_info_window, lostObject.getContact()));
}
imgThumbnail = (ImageUrlView) v.findViewById(R.id.thumbnail);
markerShowingInfoWindow = marker;
imgThumbnailPath = imgThumbnailPath.replace(".jpg", "_100_100.jpg");
imgThumbnail.setListener(listener);
imgThumbnail.load(imgThumbnailPath);
}else{
v.invalidate();
}
}
}
// Returning the view containing InfoWindow contents
return v;
}
This method is called after the bitmap has been loaded. It checks if the currently displayed
info window is the same info window which has been saved. If it is, then refresh the windown to display the newly loaded image.
private ImageUrlView.ImageUrlViewListener listener = new ImageUrlView.ImageUrlViewListener() {
#Override
public void imageAdded(ImageUrlView img) {
if (markerShowingInfoWindow != null ) {
mRefreshingInfoWindow = true;
markerShowingInfoWindow.showInfoWindow();
mRefreshingInfoWindow = false;
}
}
};
}
Firstly, I do not see any variable that is storing the URL path/address. Hence there is no way for the program to get the location of the image and display it on to the info window. There are two ways to do that:
One is by using Universal Image Loader which is a library that you can embed in your app project. Which is quite similar to what you are doing in your app code using custominfoadapter. Please refer to this link for the complete implementation of the code.
Another method is to use a separate thread (Async Task is the best option to do that). This will load the image from the URL in the background and glue it inside the custominfowindow in a synchronized manner.
Here is a code snippet for that, Put this method inside your ObjectInfoWindow class and pass in URL and marker as parameters:
protected void handleMarkerClicked(final Marker marker, final String url) {
new AsyncTask<Void, Void, Void>()
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
_infoImageDrawable = null;
}
#Override
protected Void doInBackground(Void... params)
{
InputStream is;
try {
is = (InputStream) new URL(url).getContent();
_infoImageDrawable = Drawable.createFromStream(is, "");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
marker.showInfoWindow();
}
}.execute();
}
}
Hope this would Help!!
My program crashs after doInBackground and doesn't come to onPostExecute.
My activity code's related parts are like this:
public static class News {
private String title;
private String content;
private Bitmap image;
public News(String nTitle, String nContent, Bitmap nImage){
title = nTitle;
content = nContent;
image = nImage;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
final AsyncTask task = new DatabaseConnection(this, Method.GET_ALL_NEWS).execute();
try {
task.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public final void fillListView(List<News> news){
recentNews = news;
if(recentNews != null && !recentNews.isEmpty()){
((ListView)findViewById(R.id.lvNews)).setOnItemClickListener(this);
final int size = recentNews.size();
final String newsTitles[] = new String[size];
for(int i=0; i<size; ++i)
newsTitles[i] = recentNews.get(i).title;
((ListView)findViewById(R.id.lvNews)).setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, newsTitles));
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final News selectedNews = recentNews.get(position);
startActivity(new Intent(this, ANewsActivity.class)
.putExtra("title", selectedNews.title)
.putExtra("content", selectedNews.content)
.putExtra("image", BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)));
}
My AsyncTask code's related parts are like this:
public DatabaseConnection(Context nContext, Method nMethod){
method = nMethod;
context = nContext;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(context.getString(R.string.database_connection_wait_message));
progressDialog.setTitle(R.string.database_connection_wait_title);
progressDialog.show();
}
#SuppressWarnings("incomplete-switch")
#Override
protected Void doInBackground(String... params) {
if(method != Method.NONE){
open();
try{
switch(method){
case GET_ALL_NEWS:
final ResultSet rs = conn.createStatement().executeQuery("select baslik, metin, resim from haberler");
news = new ArrayList<News>();
while(rs.next())
news.add(new News(rs.getString(1), rs.getString(2), BitmapFactory.decodeStream(rs.getBlob(3).getBinaryStream())));
break;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
}
return null;
}
#SuppressWarnings("incomplete-switch")
#Override
protected void onPostExecute(Void temp) {
if (progressDialog.isShowing()){
progressDialog.dismiss();
switch(method){
case GET_ALL_NEWS:
((NewsActivity)context).fillListView(news);
break;
}
method = Method.NONE;
}
}
I want UI thread waits until database operations finishes.
By the way there is no initialization problem at variables etc and database returns proper infos and my "news" variable is filled normally.
By the way again I realized it is WORKING on PHONE, STUCKS on EMULATOR interestingly (if I remove wait() method and its try-catch block on main thread code).
It's difficult to say what is crashing without the logcat output, but it would most likely be the main thread of the app because of the .wait() method you are calling in onCreate(). Your onCreate() cannot wait - it must initialize and exit, otherwise you are blocking the main thread of your app and defeating the purpose of the AsyncTask.
I have the queryAppIcon() method that queries and stores images in the array appIconDrawable. However, I'm only getting blank where images should pop up. Please let me know if I should post any other relevant code
This is the relevant code inside the ViewActivity:
// global vars
final Drawable[] appIconDrawable = null;
int i;
public Drawable[] queryAppIcon() throws ParseException, IOException {
ParseQuery<ParseObject> query = ParseQuery.getQuery("AndroidStoreContent");
query.whereExists("appIcon");
List<ParseObject> ParseResult = query.find();
// Drawable array
appIconDrawable = new Drawable[ParseResult.size()];
for (i = 0; i < ParseResult.size(); i++) {
ParseFile pf = (ParseFile) ParseResult.get(i).get("appIcon");
startDownload(pf);
}
return appIconDrawable;
}
public void startDownload(ParseFile pf) {
new DownloadImageTask(this).execute(pf);
}
public class DownloadImageTask extends AsyncTask<ParseFile, Void, Drawable> {
private AsyncResponse ar;
DownloadImageTask(AsyncResponse ar) {
this.ar = ar;
}
#Override
protected Drawable doInBackground(ParseFile... pf) {
return fetchDrawable(pf[0]);
}
protected void onPostExecute(Drawable result) {
ar.processFinish(result);
}
public Drawable fetchDrawable(ParseFile pf) {
InputStream is;
try {
is = (InputStream) new URL(pf.getUrl()).getContent();
return Drawable.createFromStream(is,null);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public void processFinish(Drawable d) {
appIconDrawable[i] = d; // i also tried testing appIconDrawable[1] = d and the app loaded with all blank images and then crashes
}
This is the interface, AsyncResponse:
public interface AsyncResponse {
void processFinish(Drawable d);
}
It seems like you need a bit of refactor...
You are expecting Drawable[] from queryAppIcon() but you will always get an empty set because you start the download which takes place in a separate thread to then update the return value.
You should be setting the Drawable to the ImageView from within processFinish.
Signs of things done wrong: Async methods such as downloading images should never have a return value.
UPDATE
Here is a very simple download AsyncTask but there are many checks, optimizations, etc. missing, like CACHE! Also, ImageView inside DownloadImageTask should be held by a WeakReference (Google it) otherwise it WILL leak your activity.
public class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
private static final String TAG = DownloadImageTask.class.getSimpleName();
private ImageView mImageView;
DownloadImageTask(ImageView imageView) {
mImageView = imageView;
}
#Override
protected Drawable doInBackground(String... url) {
return fetchDrawable(url[0]);
}
#Override
protected void onPostExecute(Drawable result) {
if (result != null) {
mImageView.setImageDrawable(result);
} else {
Log.w(TAG, "Could download image!");
}
}
public static Drawable fetchDrawable(String url) {
Log.v(TAG, "Downloading: " + url);
InputStream is;
try {
is = (InputStream) new URL(url).getContent();
return Drawable.createFromStream(is, null);
} catch (MalformedURLException e) {
Log.e(TAG, e.getMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
return null;
}
}
Adapter:
public class ImageDownloadAdapter extends ArrayAdapter<String>{
public ImageDownloadAdapter(Context context, String[] objects) {
super(context, R.layout.item_image_download, R.id.txt_url, objects);
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
String url = getItem(position);
ImageView imageView = (ImageView) view.findViewById(R.id.img_download);
DownloadImageTask downloadImageTask = new DownloadImageTask(imageView);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
downloadImageTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
} else {
downloadImageTask.execute(url);
}
return view;
}
}
Activity:
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(new ImageDownloadAdapter(this, new String[]{
"http://www.beautystat.com/site/wp-content/uploads/2011/02/happy-faces-small.jpg",
"http://www.ducthide.com/new_wallet_pics/happy_face.JPG"
}));