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.
Related
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;
}
My code:
private class selectBookInAutor extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
arr_book_title.clear();
arr_book_href.clear();
mProgressDialog = new ProgressDialog(_context);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
StringBuilder sb = new StringBuilder();
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
Elements links = doc.select("li>a");
for (Element link : links) {
sb.append(link.text());
arr_book_title.add(link.text());
arr_book_href.add(Jsoup.clean(link.attr("abs:href"), Whitelist.basic()));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
final CharSequence[] items = arr_book_title.toArray(new CharSequence[arr_book_title.size()]);
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
}else if(seletedItems.contains(indexSelected)){
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
for (Object s : seletedItems){
String[] separated = selGroupParam.split(";");
String _idautor = separated[0].toString();
long id_book = db.insertBOOK(_idautor, arr_book_href.get(Integer.valueOf(s.toString())).toString(), "", arr_book_title.get(Integer.valueOf(s.toString())).toString());
new **saveBookInAutor().execute(arr_book_href.get(Integer.valueOf(s.toString())).toString(), _idautor, String.valueOf(id_book));**
}
refreshList();
}
}).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog.dismiss();
}
}
private class saveBookInAutor extends AsyncTask<String, Void, String> {
String _idautor, _idbook;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog2 = new ProgressDialog(_context);
mProgressDialog2.setMessage("Save to file");
mProgressDialog2.setIndeterminate(false);
mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[1];
_idbook = params[2];
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
_html = doc.select("dd").outerHtml();
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
Toast.makeText(_context, "Save file", Toast.LENGTH_SHORT).show();
String html = "<html lang='ru'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>"+result+"</body></html>";
//String html = result;
**savePageToFile(_idautor + "_" + String.valueOf(_idbook), html);**
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog2.dismiss();
}
}
public void refreshList() {
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
}
public void savePageToFile(String filename, String html) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_context.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(html);
outputStreamWriter.close();
}
catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
}
}
When you select a page and clicking "Ok" ProgressDialog mProgressDialog2 opens and displays just a 1 second. Because of this, I do not see the download Page or not.
How to make mProgressDialog2 displayed all the while to save the page as a file?
Thank you!
UPD
What i want is :
Start mProgressDialog.
After downloading the page disappears and AlertDialog comes with the question what to choose.
After choosing, mProgressDialog2 should be displayed as long as it downloads and saves the file in the webpage.
However mProgressDialog2 disappears in 1 second, and process of saving the file goes on in silence.
In your onPostExecute method, you unconditionally call
mProgressDialog2.dismiss();
This is closing the dialog immediately after it is displayed. That call should be moved to the handler code for each of the buttons. (i.e.the onClick method for the positive and negative buttons)
in onPostExecute(), compare Strings like
if(!result.equals(""))
and try once.
use equals() method for String comparisons.
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();
}});
This is my download class in which I used Asynctask.Everything works fine, when the file is downloaded fully,it shows 'file downloaded' and on 'ok' press goes back to previous activity.Now I wanted to cancel the asynctask(pls not that 'cancel asynctask' and not only the 'loading' dialogue)on back button press and go back to previous activity.How to do that?someone please help.Thanks in advance
public class Download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.down);
startDownload();
}
private void startDownload() {
String url = data.proj;
new DownloadFileAsync().execute(url);
}
private void showMsg() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Document is downloaded")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//do things
Download.this.finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
String fname;
fname = data.proj.substring( data.proj.lastIndexOf('/')+1, data.proj.length() );
InputStream input = new BufferedInputStream(url.openStream());
String path=Environment.getExternalStorageDirectory()
.toString() + File.separator;
OutputStream output = new FileOutputStream(path+fname);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
showMsg();
}
}}
Really old question, but it seems many people still face an issue in cancelling AsyncTasks. So, here goes...
You will need a field in your AsyncTask class (DownloadFileAsync) to store the View which is being used to cancel the task (a ProgressDialog here).
For ProgressDialog, when creating the dialog, pass true to setCancelable()
mProgressDialog.setCancelable(true);
To pass the view, change the call to the Task as follows:
new DownloadFileAsync(mProgressDialog).execute(url);
and inside our AsyncTask class, create a constructor which saves this value to a field and register an OnCancelListener to call cancel method of AsyncTask:
ProgressDialog mProgressDialog;
DownloadFileAsync(ProgressDialog progressDialog) {
mProgressDialog = progressDialog;
mprogressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
}
In your while loop in doInBackground, add the following code inside the loop:
if (isCancelled()) {
outputStream.flush();
outputStream.close();
inputStream.close();
return null;
}
This way we are checking whether the task was cancelled, every once in a while, and if yes, we close open streams and stop running the task with return (return will be of type given for result of Task). Next, in onCancelled
#Override
protected void onCancelled (Integer fileSize) {
super.onCancelled(fileSize);
Log.d("TASK TAG", "Cancelled.");
//anything else you want to do after the task was cancelled, maybe delete the incomplete download.
}
this is how i did
public class downloadAllFeeds extends AsyncTask<Void, Void, Void>
implements OnCancelListener{
protected void onPreExecute() {
pDialog2.setCancelable(true);
pDialog2.setOnCancelListener(this);
}
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
downloadAllFeeds.this.cancel(true);
Log.d("on click cancel true","true");
}
#Override
protected Void doInBackground(Void... params) {
if(isCancelled()==true){
//cancel true stop async
Log.d("cancel true","true");
}else{
//perform your task
}
}
this worked for me, i know this is very old question but it didnt have a answer so i thought i should share what i just now could implement :)
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);
}