Android AsyncTask wait until Status.FINISHED - android

Well I am downloading a image from url with AsyncTask,
I want to show this image in dialog, right after image downloaded.
I m trying with this code: It ıs not waiting until finish, this code is returning RUNNING.
if(dt.getStatus() == AsyncTask.Status.FINISHED) {
dialog.show();
}

You need to set an event listener. Just setting an if-then statement means it will be executed the moment it finds the code. A event listener will wait until the event happens (In this case, Status.FINISHED) and then execute the code inside the listener.

With Ken Wolf helps..
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
private Context mcontec;
public DownloadImageTask(ImageView bmImage, Context mContextr) {
this.bmImage = bmImage;
mcontec=mContextr;
}
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) {
dialog(result, mcontec);
}
public void dialog(Bitmap resim, final Context ctx){
final Dialog dialog = new Dialog(ctx, R.style.CustomDialogTheme);
dialog.setContentView(R.layout.perdereklam);
ImageView reklam = (ImageView) dialog.findViewById(R.id.reklampng);
reklam.setImageBitmap(resim);
reklam.setOnTouchListener(new OnTouchListener() {
// fill your stuff...
}
dialog.show();
}
calling from any class:
public static void showRateDialog(final Context mContextr) {
final Dialog dialog = new Dialog(mContextr, R.style.CustomDialogTheme);
ImageView reklam = (ImageView) dialog.findViewById(R.id.reklampng);
final DownloadImageTask dt = new DownloadImageTask(reklam, mContextr);
dt.execute("your url");
}

Related

Load Image in RecycleView with Picasso

Hi guys i have an problem,
I have a list and I have to view it in a list using the reycleview but when I go to the image via cericare phat and to do this use picasso
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
this.viewHolder=viewHolder;
if(scheduler.size()>=1){
viewHolder.time.setText(scheduler.get(i).getTime());
viewHolder.data.setText(scheduler.get(i).getData());
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeItem(i);
}
});
String phat=scheduler.get(i).getImageString();
//result paht: content://com.android.providers.media.documents/document/image%3A445
Picasso.with(c).load(phat).into(viewHolder.img);//does not display the image
viewHolder.img.setOnClickListener(new MyClikListener(i));
viewHolder.time.setOnClickListener(new MyClikListener(i));
viewHolder.data.setOnClickListener(new MyClikListener(i));
viewHolder.card_view_reminder.setOnClickListener(new MyClikListener(i));
}
}
I also tried converting the pat in a URI but nothing.
Making debugging tells me onBitmapFailed
Use the below code:
Picasso.with(c).load(new File(phat)).into(viewHolder.imageView);
Hope this helps.
Try this
new DownloadImage(yourImageView).execute(URL);
create AsyncTask for download image from background process
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) 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.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
It will work for all..

Changing the pictures after seconds in android

Here is my main activity-after OnCreate code is :
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView 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);
}
}
and I have one ImageView so I can show the url-picture in this ImageView with below code:
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
new DownloadImageTask(imageView).execute("http://url.com/background1.jpg");
what i need exactly, i need to add three image in this ImageView and in every 3 seconds, picture automatically changed to another link.
Picture 2 and after three second, Picture 3
How we can do this?
Thanks
Use this to change image after 3 sec
call this in your OnCreate()
handler=new Handler();
handler.postDelayed(myRunnable, 3000);
define it outside the OnCreate()
private Runnable myRunnable=new Runnable() {
#Override
public void run() {
// change your url to imgeview here some thing like
new DownloadImageTask(imageView).execute("http://url.com/picutre2.jpg");
handler.postDelayed(this, 3000);
}
}
Note : my suggestions is to cache the downloaded image so to avoid network usage

Opening a url from another url using Intent?

I want to open a url of an image from another url of an image using intent.I am new to android so this code of mine not working.
url_1 = new URL("http://garooh.905pm.com"+com.org.constant.Helper.Gadd_list.get(0).thisEvent.getImage_four_thumb());
url_2 = new URL("http://garooh.905pm.com"+ com.org.constant.Helper.Gadd_list.get(0).thisEvent.getImage_four_thumb());
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(url_1, url_2);
startActivity(intent);
Am i right in thinking you have an imagebutton and when you click it you want to go to 1 of those URLs?
Try adding this to your imageButton.
imageButton.setOnClickListener(new locatorButtonClickListener());
private class imageButtonListener implements OnClickListener
{
#Override
public void onClick(View button) {
new DisplayImageFromUrl((ImageButton) findViewById(R.id.imageButtonEnd), this).execute(//Enter your link here);
}
UPDATE
Try using this Async task
//Display image to bitmap using URL
public class DisplayImageFromUrl extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
Context context1;
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context1);
pd.setMessage("Loading Images...");
pd.show();
}
public DisplayImageFromUrl(ImageView bmImage, Context context) {
this.bmImage = bmImage;
this.context1 = context;
}
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);
pd.dismiss();
}
}
and you call it like this in your activity.
new DisplayImageFromUrl((ImageButton) findViewById(R.id.imageButtonEnd), this).execute(//Enter your link here);

App force closing when Async tries to get Bitmap from url

I have an Async running to get data from a page I've created. It get's the text just fine, but when I try and get the image from the image src via another class the app force closes. Here is the code that it force closes on:
public class FullReportActivity extends NavigationActivity {
private TextView textView;
private String url = "http://www.backcountryskiers.com/sac/sac-full.html";
private ImageView ivDangerRose;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// tell which region this covers
getSupportActionBar().setSubtitle("...from Sierra Avalanche Center");
setContentView(R.layout.activity_fullreport);
textView = (TextView) findViewById(R.id.todaysReport);
ivDangerRose = (ImageView) findViewById(R.id.dangerRose);
fetcher task = new fetcher();
task.execute();
}
// GET THE IMAGE and RETURN IT
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);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
class fetcher extends AsyncTask<String, Void, String> {
private ProgressDialog dialog = new ProgressDialog(
FullReportActivity.this);
private Document doc = null;
private Document parse = null;
private String results = null;
private String reportDate = null;
private Bitmap bimage = null;
#Override
protected String doInBackground(String... params) {
try {
doc = Jsoup.connect(url).get();
Log.e("Jsoup", "...is working...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.getMessage());
}
parse = Jsoup.parse(doc.html());
results = doc.select("#fullReport").outerHtml();
Element dangerRoseImg = doc.getElementById("reportRose")
.select("img").first();
String dangerRoseSrc = dangerRoseImg.absUrl("src");
Log.i("Report Rose IMG", dangerRoseSrc);
bimage = getBitmapFromURL(dangerRoseSrc);
ivDangerRose.setImageBitmap(bimage);
return results;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// smooth out the long scrolling...
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
reportDate = parse.select("#reportDate").outerHtml();
textView.setText(Html.fromHtml(reportDate + results));
textView.setPadding(30, 20, 20, 10);
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Full Report from the Sierra Avalanche Center...");
dialog.show();
}
}
}
I have run this Async alone to get the image like so without a force close and I don't understand what i am doing different besides calling the method:
public class MainActivity extends Activity {
public String durl = "http://www.sierraavalanchecenter.org/dangerrose.png?a=2955";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadImageTask((ImageView) findViewById(R.id.dangerrose))
.execute(durl);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap drose = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
drose = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return drose;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
This class gets the image src and creates a bitmap and puts it into an ImageView, what is different here than on my first class???
Frustrated.
You can not modify UI from background thread.
move ivDangerRose.setImageBitmap(bimage); in onPostExecute
In the method doInBackground
remove --> ivDangerRose.setImageBitmap(bimage);
as you can't modify UI in background process.
If you still want you can try runOnUiThread Method
In doInBackground() we should not access the content of activity.

Android : Loading an image from the Web with Asynctask

How do I replace the following lines of code with an Asynctask ?
How do you "get back" the Bitmap from the Asynctask ? Thank you.
ImageView mChart = (ImageView) findViewById(R.id.Chart);
String URL = "http://www...anything ...";
mChart.setImageBitmap(download_Image(URL));
public static Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
I thought about something like this :
replace :
mChart.setImageBitmap(download_Image(graph_URL));
by something like :
mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));
and
public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
#Override
protected void onPostExecute(Bitmap result) {
mChart.setImageBitmap(result); // how do I pass a reference to mChart here ?
}
private Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
}
but How do I pass a reference to mChart in onPostExecute(Bitmap result) ???
Do I need to pass it with the URL in some way ?
I would like to replace all my lines of code :
mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));
with something similar ... but in Asynctask way !
mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));
Is there an easy solution for this ?
Do I get something wrong here ?
If there is no good reason to download the image yourself then I would recommend to use Picasso.
Picasso saves you all the problems with downloading, setting and caching images.
The whole code needed for a simple example is:
Picasso.with(context).load(url).into(imageView);
If you really want to do everything yourself use my older answer below.
If the image is not that big you can just use an anonymous class for the async task.
This would like this:
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
The Task class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}
Hiding the URL in the tag is a bit tricky but it looks nicer in the calling class if you have a lot of imageviews that you want to fill this way. It also helps if you are using the ImageView inside a ListView and you want to know if the ImageView was recycled during the download of the image.
I wrote if you Image is not that big because this will result in the task having a implicit pointer to the underlying activity causing the garbage collector to hold the whole activity in memory until the task is finished. If the user moves to another screen of your app while the bitmap is downloading the memory can't be freed and it may make your app and the whole system slower.
Try this code:
ImageView myFirstImage = (ImageView) findViewById(R.id.myFirstImage);
ImageView mySecondImage = (ImageView) findViewById(R.id.mySecondImage);
ImageView myThirdImage = (ImageView) findViewById(R.id.myThirdImage);
String URL1 = "http://www.google.com/logos/2013/estonia_independence_day_2013-1057005.3-hp.jpg";
String URL2 = "http://www.google.com/logos/2013/park_su-geuns_birthday-1055005-hp.jpg";
String URL3 = "http://www.google.com/logos/2013/anne_cath_vestlys_93rd_birthday-1035005-hp.jpg";
myFirstImage.setTag(URL1);
mySecondImage.setTag(URL2);
myThirdImage.setTag(URL3);
new DownloadImageTask.execute(myFirstImage);
new DownloadImageTask.execute(mySecondImage);
new DownloadImageTask.execute(myThirdImage);
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}
}
you can create a class say..BkgProcess which contains an inner class that extends AsyncTask. while instantiating BkgProcess pass the context of your Activity class in BkgProcess constructor. for eg:
public class BkgProcess {
String path;
Context _context;
public Download(Downloader downloader, String path2){
this.path = path2;
_context = downloader;
}
public void callProgressDialog(){
new BkgProcess().execute((Void)null);
}
class Downloads extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(_context);
protected void onPreExecute(){
dialog.setMessage("Downloading image..");
dialog.show();
}
protected void onPostExecute(Boolean success) {
dialog.dismiss();
if(success)
Toast.makeText(_context, "Download complete", Toast.LENGTH_SHORT).show();
}
#Override
protected Boolean doInBackground(Void... params) {
return(startDownload(path));
}
public boolean startDownload(String img_url) {
// download img..
return true;
}
}
}
from your activity class..
BkgProcess dwn = new BkgProcess (Your_Activity_class.this, img_path);
dwn.callProgressDialog();
This will get you images of any size...
if you dont want the progress dialog just comment the codes in onPreExecute();
for(int i = 0 ; i < no_of_files ; i++ )
new FetchFilesTask().execute(image_url[i]);
private class FetchFilesTask extends AsyncTask<String, Void, Bitmap> {
private ProgressDialog dialog = new ProgressDialog(FileExplorer.this);
Bitmap bitmap[];
protected void onPreExecute(){
dialog.setMessage("fetching image from the server");
dialog.show();
}
protected Bitmap doInBackground(String... args) {
bitmap = getBitmapImageFromServer();
return bitmap;
}
protected void onPostExecute(Bitmap m_bitmap) {
dialog.dismiss();
if(m_bitmap != null)
//store the images in an array or do something else with all the images.
}
}
public Bitmap getBitmapImageFromServer(){
// fetch image form the url using the URL and URLConnection class
}

Categories

Resources