progress dialog for downloading pics - android

I am downloading roughly 231 pics and would like to have a progress dialog say downloading pics please wait until all the pics are available and then disappear. How would I go about doing this?
protected class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... url)
{
int count;
try
{
URL url1 = new URL(url[0]);
URLConnection conexion = url1.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url1.openStream());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
}
input.close();
}
catch (Exception e)
{
}
return null;
}
public void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
// here you will have to update the progressbar
// with something like
setProgress(numPokemon);
}
}

I think u have dont wrong thing,
show progress dialog in onpreExecute() , ur logic in doinBackground() and dismiss progress dialog in onPostExecute().
Hope u get it

try this ::
class AddTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pDialog = ProgressDialog.show(Recording.this,"Please wait...", "Retrieving data ...", true);
protected void onPreExecute() {
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
SaxParser(Username,Password);
}
protected Void doInBackground(Void... unused) {
// your code
return(null);
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}

Related

How do I disconnect this AsyncTask?

How can I close this connection and Asynctask if url doesn't exist. Please kindly help me .
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFile().execute("https://i.stack.imgur.com/w4kCo.jpg");
}
Download task is below and I can't control it to be stopped, progress is started and still showing if url is invalid.
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading Image ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
#Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="downloadedimage.jpg";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+"/myImage/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
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;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download Completed !", Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(String result) {
}
}
All required permissions added properly.
You can call cancel() on the AsyncTask. Any calls to isCancelled() after that will return true. This doesn't necessarily mean your doInBackground method will stop executing. You have to manually check isCancelled() during that method to exit gracefully. Although once you call cancel(), onPostExecute() will not get called. onCancelled() will get called however.
Change this line in your code
class DownloadFile extends AsyncTask<String,Integer,Boolean> {
protected Boolean doInBackground(String... aurl) {
Now when you url fails on doInBackground method just return false from there
Now you can check this on
#Override
protected void onPostExecute(Boolean result) {
if(!result){
mProgressDialog.dismiss();
}
super.onPostExecute(aLong);
}

how to a set progress bar till get a data from server using json? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Android AsyncTask Progress bar
Am using login process,during tat time am getting the data from server is delay.so i want set a progress bar for tat delay.how to set progress bar till get a response from server.any know the answer please help me.
private class LongOperation extends AsyncTask<String, Void, String>
{
protected void onPreExecute()
{
progressDialog = new ProgressDialog(activity.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(true);
progressDialog.show();
}
protected String doInBackground(String... params)
{
try
{
//Getting data from server
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
progressDialog.dismiss();
Intent n = new Intent(firstactivity.this, secondactivity.class);
startActivity(n);
}
}
How to call this
ProgressDialog progressDialog;
LongOperation mytask = null;
mytask = new LongOperation();
mytask.execute();
Use AsyncTask in your code and put your code in doInBackground(....) process.
Show your progress dialog in onPreExecute and dismiss it in onPostExecute(...) .
Add an infinite progressbar view to your layout and make it invisible first.
Create an AyncTask to do the server communication.
In onPreExecute() make the progressbar visible.
In onPostExecute() hide the progressbar again.
You can use the onProcessupdate method of an AsyncTask
private class GetLogin extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show("Downloading...");
}
#Override
protected String doInBackground(String... params) {
for (String myUrl : params) {
try {
URL url = new URL(myUrl);
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("Accept", "application/xml");
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
String str = new String(baf.toByteArray(), "UTF8");
return str;
} catch (MalformedURLException e) {
//error
} catch (IOException e) {
//error
}
}
return "All Done!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pd.setMessage("Downloading... (" + values[0] + "%)");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}

Download File with Progressbar showDialog - error

i keep getting this error telling me to suppress my showdialog code for my progress bar.
now what can i do to fix this, also i dont want to use any other way. im trying to learn showdialog for downloads
here my code
public class download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://practicalbuddhist.com/wp-content/uploads/2012/03/Synapses-Image-for-March-17-2010-Blog-Entry.jpg";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Running Download Test...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#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);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/Downloadtest.jpg");
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;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
Use the Dialog class methods directly not the Activity helper methods.
In the Dialog API guide at http://developer.android.com/guide/topics/ui/dialogs.html they say explicitly to do not use ProgressDialog but use a custom layout with a ProgressBar.
On the other hand you could just use the DownloadManager to download files asynchrously. Check https://github.com/commonsguy/cw-android/blob/master/Internet/Download/src/com/commonsware/android/download/DownloadDemo.java for a simple example even with notifications.
If you still wants this method check http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/ for a simple example using a ProgressDialog-

Download File Progress Dialog

I want to perform a file download and show a dialog. But when I try to show the dialog I get a error, any help?
The problem is at showDialog(DIALOG_DOWNLOAD_PROGRESS);
Here is the error message : The method showDialog(int) from the type Activity is deprecated
Heres my code:
public class download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://practicalbuddhist.com/wp-content/uploads/2012/03/Synapses-Image-for-March-17-2010-Blog-Entry.jpg";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Running Download Test...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask {
#SuppressWarnings("deprecation")
#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);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/Downloadtest.jpg");
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;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
Here is the error message: The method showDialog(int) from the type Activity is deprecated
This is a warning, not an error. You can either upgrade to using Fragments or ignore it.
You can also use ProgressDialog and show() method that is not depracated instead of using showDialog. Declare your dialog in AsyncTask:
class DownloadFileAsync extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
}
and in onPostExecute() use
pDialog.dismiss();

File download progress bar in android

How to show the remaining KB's of file is to be downloaded in progress bar in android.
e.g 12kb/120kb is remaining..then 97kb/120kb...etc
Can we have this progress dialog as shown in the image
class DownloadFileAsync extends AsyncTask<String, String, String> {
private ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(UrlTestActivity.this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
for (int i = 0; i < 3; i++) {
URL url = new URL("http://nodeload.github.com/nexes/Android-File-Manager/zipball/master");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Folder");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory+ "/"+(i+100)+".zip");
byte data[] = new byte[1024];
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
publishProgress(""+ progress_temp);
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
}
} catch (Exception e) {}
return null;
}
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);
}
}
The best way what you have described is to perform the download using an AsyncTask. In the onProgressUpdate method, you can update a ProgressDialog to indicate the user the percentage of completion. It will look like that:
progressDialog.setMax(fileLength/1000);
publishProgress(String.valueOf(total /1000));
The below code is only available after API 11
progressDialog. setProgressNumberFormat ("%1d kb of %2d kb");
Take a look at http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog
You can use a progress dialog, as discussed in the docs. Alternatively (and perhaps more elegantly), you can use a progress indicator in your activity's title bar. In your activity, before calling setContentView, add this line:
requestWindowFeature(Window.FEATURE_PROGRESS);
Then by calling setProgress(int) you can indicate progress. When progress reaches 10000, the progress indicator in the title bar fades away. Note that if you determine progress in a non-UI thread, you should use a Handler to call setProgress.

Categories

Resources