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;
}
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 need to load an image from the web in my app, I found a good example here, but I can't figure out how to use the returned Bitmap in my Main Activity :
the class :
public class GetImageFromServer extends AsyncTask<Void, Void, Bitmap {
private String sURL;
GetImageFromServer(String urlParam) {
sURL = urlParam;
}
#Override
protected Bitmap doInBackground(Void... urlParam) {
Bitmap bmp = null;
//ImageView img = (ImageView) findViewById(R.id.imageView1);
try {
URL url = new URL(sURL);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception ex) {
Log.println(1, "Profile:getImg", ex.getMessage());
}
return bmp;
}
#Override
protected void onPreExecute() {}
}
And the MainActivity code :
String urlImage = "http://www.xxxxxx.com/css/images/xxxxxx.png";
GetImageFromServer gifs = new GetImageFromServer(urlImage);
gifs.execute();
if(person.has("Avatar")) {Avatar.setImageBitmap( gifs.execute())}
The error is :
gifs.execute()
Thanks for your help !
Add :
I added this "cancel(true)" because I have connection problems to JSON webservices after severals start/debug/close, but I doesn't seem to work :
#Override
protected Bitmap doInBackground(String... urlParam) {
if (isCancelled())
this.cancel(true);
Bitmap b = null;........
and
#Override
protected void onPostExecute(Bitmap result) {
// use the result
mImageView.setImageBitmap(result);
this.cancel(true);
}
Could the assynctasks prevent my app to connect to my webservices ?
There is a good library for doing async image loadings, here is a link: https://github.com/square/picasso.
Or you could follow this approach:
public class LoadImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
private ImageView mImageView;
public LoadImageAsyncTask(ImageView imageView) {
mImageView = imageView;
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception ex) {
Log.println(1, "Profile:getImg", ex.getMessage());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}
}
In your activity call:
LoadImageAsyncTask task = new LoadImageAsyncTask(findViewById(R.id.yourImageId)).execute(stringUrl);
you have to implement a callback
your asynctask
public class GetImageFromServer extends AsyncTask<Void, Void, Bitmap> {
private String sURL;
private Bitmap b;
YourCallback mOwner;
GetImageFromServer(YourCallback owner, String urlParam) {
sURL = urlParam;
mOwner = owner;
}
#Override
protected Bitmap doInBackground(Void... urlParam) {
try {
URL url = new URL(sURL);
b = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
} catch (Exception ex) {
Log.println(1, "Profile:getImg", ex.getMessage());
}
return b;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Bitmap result) {
// use the result
super.onPostExecute(result);
if (mOwner != null)
mOwner.CallbackFunction(result);
}
public interface YourCallback {
void CallbackFunction(Bitmap result);
}
}
your MainActivity
public class MainActivity extends Activity implements YourCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
GetImageFromServer gifs = new GetImageFromServer(urlImage, b);
gifs.execute();
}
#Override
public void CallbackFunction(Bitmap result) {
if (person.has("Avatar")) {
Avatar.setImageBitmap(result);
}
}
}
I have a problem which I don't understand. I want to show a simple Progress Dialog in Android. So I created an AsyncTask and create the dialog in the constructor. I use the methods onPreExceution to initialise the dialog and the onPostExecute method I destory the dialog. So until now this looks total correct for me. But when I start the App on my Nexus 7 the dialog doesn't show up till the job is done. So it shows up for a half of a second at the end of the job... What am I doing wrong?
Thank you for your help ;)
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
public ParseHTMLCodeNew(Context context) {
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
UPDATE
This is my new AsyncTask:
public class ParseHTMLCodeNew extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private final OnCompleteTaskListener onCompleteTaskListener;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result){
onCompleteTaskListener.onComplete(result);
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
And i am calling it this way:
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
gData = data;
}
}).execute(url);
As i commented on your post, data has no value.
If you calling this code so:
String data = new ParseHTMLCodeNew(CommentActivity.this).execute(url).get();
Then you do not really see your dialogue because there is a blocking UI.
Method get() waits if necessary for the computation to complete, and then retrieves its result.
Call so:
new ParseHTMLCodeNew(CommentActivity.this).execute(url);
and the result of the work is handled directly in the AsyncTask.
If you need to transfer the data to the main thread, you should tell him that the task was completed.
Wat is the simple code, I just added OnCompleteTaskListener interface
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
private final OnCompleteTaskListener onCompleteTaskListener;
private ProgressDialog dialog;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
// einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
// your code here
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
sb.append(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
onCompleteTaskListener.onComplete(result);
}
}
And the example of a call
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
Toast.makeText(CommentActivity.this, data, Toast.LENGTH_LONG).show();
}
}).execute("your_url");
Be careful, this code can produce errors when you rotate your Phone.
When Activity destroyed but task is performed:
- progress dialog will close and will not open again
- local variable to dialog or context is incorrect.
If the operation is performed for a long time can make it through the of the services?
I've wrote a code that get data from online database and populate that data in lisview here is the part of my code hope that help !
class LoadMyData extends AsyncTask<String, String, String> {
//Before starting background thread Show Progress Dialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//Your code here
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the data
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// In my case use my adapter to display the data in a listview
adapter = new MyAdaper();
list.setAdapter(adapter);
}
});
}
}
Progress dialog should be shown from UI thread
runOnUiThread(new Runnable() {
public void run() {
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}});
I know that the first you gonna this is... why the heck on the world you then use AsyncTask.
So here is my problem i am working on some Android app (API 7 for android 2.1 or higher) , and i am testing on emulator and everything was fine, so then i tested on HTC Sensation and it says NetworkOnMainThreadExeption!
I was downloading some pictures and then draw on the map.
So to solve this problem every (internet connection) in this case downloading the pictures i must put on AsyncTask to work.
So i need a method how to know when all pictures are done so i can start drawing..
I was trying so much and no result i have no idea. I got one solution with handler but if run on slower net i get nullpointer(because the pictures are not downloaded).
So please help me.
EDIT:
here is the idea:
Bitmap bubbleIcon ;
onCreate(){
...
// i am making call for Async
new ImgDown().execute(url);
//and then i calling functions and classes to draw with that picture bubbleIcon !
DrawOnMap(bubbleIcon);
}
//THIS IS ASYNC AND FOR EX. SUPPOSE I NEED TO DOWNLOAD THE PIC FIRST
class ImgDown extends AsyncTask<String, Void, Bitmap> {
private String url;
public ImgDown() {
}
#Override
protected Bitmap doInBackground(String... params) {
url = params[0];
try {
return getBitmapFromURL(url);
} catch (Exception err) {
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
bubbleIcon = result;
bubbleIcon = Bitmap
.createScaledBitmap(bubbleIcon, 70, 70, true);
}
public Bitmap getBitmapFromURL(String src) {
try {
Log.e("src", src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
// /tuka decode na slika vo pomalecuk kvalitet!
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
Bitmap myBitmap = BitmapFactory
.decodeStream(new FlushedInputStream(input));
Log.e("Bitmap", "returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("getBitmapFromURL", e.getMessage());
return null;
}
}
class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int byteValue = read();
if (byteValue < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
}
i hope now is more clear.
class OpenWorkTask extends AsyncTask {
#Override
protected Boolean doInBackground(String... params) {
// do something
return true;
}
#Override
protected void onPostExecute(Boolean result) {
// The results of the above method
// Processing the results here
myHandler.sendEmptyMessage(0);
}
}
Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
// calling to this function from other pleaces
// The notice call method of doing things
break;
default:
break;
}
}
};
You can write your own Delegate to delegate info about finishing the task, using OOP principles:
task_delegate.java
public interface TaskDelegate {
void TaskCompletionResult(String result);
}
main_activity.java
public class MainActivity extends Activity implements TaskDelegate {
//call this method when you need
private void startAsynctask() {
myAsyncTask = new MyAsyncTask(this);
myAsyncTask.execute();
}
//your code
#Override
public void TaskCompletionResult(String result) {
GetSomethingByResult(result);
}
}
my_asynctask.java
public class MyAsyncTask extends AsyncTask<Void, Integer, String> {
private TaskDelegate delegate;
protected MyAsyncTask(TaskDelegate delegate) {
this.delegate = delegate;
}
//your code
#Override
protected void onPostExecute(String result) {
delegate.TaskCompletionResult(result);
}
}
class openWorkTask extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
//do something
return true;
}
#Override
protected void onPostExecute(Boolean result) {
// The results of the above method
// Processing the results here
}
}
I would use a Progress Dialog if I were you. This way users can see that something is happening while the ASyncTask downloads the picture. On PostExecute, call a method from your main code that checks if the pictures are null. Remember you cannot update the UI in the doInBackground method so do any UI work in either onPreExecute or onPostExecute
private class DownloadPictures extends AsyncTask<String, Void, String>
{
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params)
{
//Download your pictures
return null;
}
#Override
protected void onPostExecute(String result)
{
progressDialog.cancel();
//Call your method that checks if the pictures were downloaded
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(
YourActivity.this);
progressDialog.setMessage("Downloading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
// Do nothing
}
}
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);
}