I am writing a code in which I need to move all file and folders to the sdcard. I used Async task for this purpose. During this activity I am showing a progressbar with percentage on my screen instead of just showing me the "Loading..." popup. But it does not meet my requirement.
public class syncMgr extends AsyncTask<String, Long, String> {
public LoginActivity activity;
public Context context;
syncMgr(LoginActivity activity1,Context c)
{
activity = activity1;
context=c;
}
//public ProgressDialog progress;
protected void onPreExecute() {
super.onPreExecute();
activity.progress = ProgressDialog.show(context,"","Files Downloading, Please Wait...",true);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
copyFilesToSdCard();
return null;
}
private void copyFilesToSdCard() {
copyFileOrDir("");
}
private void copyFileOrDir(String path) {
AssetManager assetManager = activity.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() " + path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path=" + fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir " + fullPath);
for (int i = 0; i < assets.length; ++i) {
publishProgress((int) ((i / (float) 658) * 100));
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
copyFileOrDir(p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void publishProgress(int i) {
// TODO Auto-generated method stub
activity.progress.setProgress(i);
}
#Override
protected void onProgressUpdate(Long... values) {
activity.progress.setProgress(values[0].intValue());
}
#Override
protected void onPostExecute(String result) {
activity.progress.dismiss();
super.onPostExecute(result);
//return "asdas";
//return result;
}
}
Here is my Activity Class Code...
ProgressDialog progress;
public static final int progress_bar_type = 0;
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
progress = new ProgressDialog(this);
progress.setMessage("Downloading file. Please wait...");
progress.setIndeterminate(false);
progress.setMax(100);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setCancelable(true);
progress.show();
return progress;
default:
return null;
}
}
Have you tried putting the asyncTask initiation code into a worker thread like this?
// set progressBar .VISIBLE first
// then...
new Thread(new Runnable() {
public void run() {
// webview initiation code
}
}).start();
I turn on progressBar visibility beforehand and not in onPreExecute().
Here is how it solved my own problem & here are the docs.
Related
Hi in the below downloading images for showing progessbar to 100 but completeld 100% images are not showing still downloading and not showing .i want after 100% i want to move to activity.
But it's taking time to move next activity.
java
public class DownloadTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
final DialogProgressBarRunnable progressDialog =
new DialogProgressBarRunnable(getActivity(), false, 2);
progressDialog.show();
// the dialog box shouldn't get cancelled when clicking outside it or pressing back button.
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
// pd.setMessage("Downloading catalogue images.");
// pd.show();
}
protected String doInBackground(Void... Params) {
parsingObject = new ParsingForFinalImages(catid, responseJson);
/* ConnectionDetector cd = new ConnectionDetector(getActivity().getBaseContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent==true)
{
}
*/
// put your code here
// JSON parsing begins here via the parsing class
// Put this code in async task
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// pd.hide();
// pd.dismiss();
Intent intent = new Intent(getActivity(), ImageGallery.class);
startActivity(intent);
}
}
private class DialogProgressBarRunnable extends ProgressDialog implements
Runnable {
private boolean showSecondary;
private int incrementAfter;
public DialogProgressBarRunnable(Context context,
boolean showSecondary, int incrementAfter) {
super(context);
setCancelable(true);
setMessage(getString(R.string.download_message));
setSecondaryProgress(0);
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
setMax(100);
setProgress(0);
this.showSecondary = showSecondary;
this.incrementAfter = incrementAfter;
}
#Override
public void show() {
super.show();
new Thread(this).start();
}
#Override
public void run() {
while (progress < 100) {
progress++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// increment the first/second progress bar after every %
progressBar();
}
}
private void progressBar() {
if (progress % incrementAfter == 0) {
progressFirstBar();
}
if (showSecondary) {
progressSecondaryBar();
}
}
private void progressSecondaryBar() {
while (secondaryProgress < 100) {
secondaryProgress++;
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
setSecondaryProgress(secondaryProgress);
}
});
}
}
private void progressFirstBar() {
secondaryProgress = 0;
handler.post(new Runnable() {
#Override
public void run() {
setProgress(progress);
if (progress == 100) {
dismiss();
}
}
});
}
}
class DownloadFileFromURL extends AsyncTask {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
// Declear Variables
int count;
try {
URL url1 = new URL(url);
URLConnection conection = url1.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url1.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString() + "/Report.xls");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
Log.d("Downloding"+data,"Count"+count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
#Override
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String reString) {
// dismiss the dialog after the file was downloaded
super.onPostExecute(null);;
dismissDialog(progress_bar_type);
Log.d("Download","Completed");
Intent intent1=new Intent(DownloadExcle.this,MainActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
}
I have made a progressbar in android,Which is horizontal,i want to freeze it when any button click in my activity,I have tried as below,But progress still displays.my code is as below:I want to do something like one question loaded after another,and onClick of any button counter and progress state should be stop,but rite now my timer stop but progress still ran up..it not stops.
code
public class QuestionAnswerActivity extends Activity implements OnClickListener {
// visible gone
ArrayList<HashMap<String, String>> QuestionList;
private int progressStatus = 0;
private Handler handler = new Handler();
Intent i;
private boolean run = true;
/**
* Answer [1=true / 0 =false]
*/
int myans;
String ans;
ProgressDialog pDialog;
TextView text_player_one;
String JsonStr;
ArrayList<HashMap<String, String>> questionList;
ImageView player_one_pic;
int count;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
ImageView answer_right_one;
ProgressBar pg_loading;
private CountDownTimer countDownTimer;
TextView timer_text;
private final long startTime = 8 * 1000;
private final long interval = 1 * 1000;
Button opt_1, opt_2, opt_3, opt_4;
Thread splashThread;
TextView answer_question;
LinearLayout answer_linear_3;
// Response variables...!!
// Single player*************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.question_answer_activity);
init();
}
// ***********************************************************************************************
/**
* Initialise the views
*/
#SuppressWarnings({ "deprecation", "unchecked" })
private void init() {
answer_linear_3 = (LinearLayout) findViewById(R.id.answer_linear_3);
answer_linear_3.setVisibility(View.GONE);
questionList = new ArrayList<HashMap<String, String>>();
answer_question = (TextView) findViewById(R.id.answer_question);
player_one_pic = (ImageView) findViewById(R.id.player_one_pic);
text_player_one = (TextView) findViewById(R.id.text_player_one);
text_player_one.setText(Pref.getValue(QuestionAnswerActivity.this,
Const.PREF_NAME, ""));
pg_loading = (ProgressBar) findViewById(R.id.pg_loading_answer);
timer_text = (TextView) findViewById(R.id.timer_text_loading11);
answer_right_one = (ImageView) findViewById(R.id.answer_right_one);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(QuestionAnswerActivity.this));
options = new DisplayImageOptions.Builder().cacheOnDisc(true)
.displayer(new RoundedBitmapDisplayer((int) 3.5f))
.showStubImage(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher).build();
imageLoader.displayImage(Pref.getValue(QuestionAnswerActivity.this,
Const.PREF_PROFILE_PIC, ""), player_one_pic, options);
opt_1 = (Button) findViewById(R.id.option_1);
opt_2 = (Button) findViewById(R.id.option_2);
opt_3 = (Button) findViewById(R.id.option_3);
opt_4 = (Button) findViewById(R.id.option_4);
count = 0;
questionList = (ArrayList<HashMap<String, String>>) getIntent()
.getSerializableExtra("queList");
System.out.println("::::::::My questions::::::::;+++++++"
+ questionList);
/*
* answer_question.setText(questionList.get(count).get("q_title"));
* opt_1.setText(questionList.get(count).get("opt1"));
* opt_2.setText(questionList.get(count).get("opt2"));
* opt_3.setText(questionList.get(count).get("opt3"));
* opt_4.setText(questionList.get(count).get("ans"));
*/
handler.postDelayed(new ViewUpdater(answer_linear_3), 1000);
answer_question.setText(questionList.get(count).get("q_title"));
opt_1.setText(questionList.get(count).get("opt1"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("ans"));
opt_1.setOnClickListener(this);
opt_2.setOnClickListener(this);
opt_3.setOnClickListener(this);
opt_4.setOnClickListener(this);
countDownTimer = new MyCountDownTimer(startTime, interval);
/*
* Initialise NoResponse Timer
*/
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
if (run) {
pg_loading.setProgress(progressStatus);
pg_loading.setProgressDrawable(getResources()
.getDrawable(R.drawable.progress));
}
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
// ***********************************************************************************************
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
run = false;
switch (v.getId()) {
case R.id.option_1:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
/* questionTask(count); */
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
break;
case R.id.option_2:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
break;
case R.id.option_3:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
break;
case R.id.option_4:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
/*
* answer_question.setText(QuestionList.get(count).get("q_title"));
* opt_1.setText(QuestionList.get(count).get("opt1"));
* opt_2.setText(QuestionList.get(count).get("opt2"));
* opt_3.setText(QuestionList.get(count).get("opt3"));
* opt_4.setText(QuestionList.get(count).get("ans"));
* timer_text.setText(timer_text.getText() +
* String.valueOf(startTime / 1000));
*
* countDownTimer.start();
* answer_right_one.setVisibility(View.VISIBLE);
* pg_loading.setVisibility(View.GONE); countDownTimer.cancel();
*
* Toast.makeText(QuestionAnswerActivity.this,
* timer_text.getText().toString(), 1).show();
*/
break;
}
}
// ***********************************************************************************************
/**
* CountDown Timer for Starting No response activity if user doesnt
* responds.
*/
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
public void onpause() {
// TODO Auto-generated method stub
Toast.makeText(QuestionAnswerActivity.this, "Clicked", 1).show();
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "onFinish",
Toast.LENGTH_SHORT).show();
/*
* If finish , that is user not responding , go to NoResponse
* screen.
*/
Intent intent = null;
intent = new Intent(QuestionAnswerActivity.this,
NoResponseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
timer_text.setText("" + millisUntilFinished / 1000);
}
}
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
void questionTask(int count) throws InterruptedException {
if (count < 8) {
answer_linear_3.setVisibility(View.GONE);
answer_question.setText(questionList.get(count).get("q_title"));
handler.postDelayed(new ViewUpdater(answer_linear_3), 100);
myans = randomGenerator();
System.out.println(":::::::::::::;randomized answer::::::::::::;;;"
+ myans);
if (myans == 1) {
opt_1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("ans"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("opt1"));
} else if (myans == 2) {
opt_2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("opt2"));
opt_2.setText(questionList.get(count).get("ans"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("ans"));
} else if (myans == 3) {
opt_3.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("opt1"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("ans"));
opt_4.setText(questionList.get(count).get("opt3"));
} else {
opt_4.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("opt1"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("ans"));
}
countDownTimer = new MyCountDownTimer(startTime, interval);
/*
* Initialise NoResponse Timer
*/
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
}
}
private class ViewUpdater implements Runnable {
private LinearLayout mView;
public ViewUpdater(LinearLayout linView) {
mView = linView;
}
#Override
public void run() {
mView.setVisibility(View.VISIBLE);
}
}
// Answer webservice call..!
private class LeaveResponse extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
countDownTimer.cancel();
pDialog = new ProgressDialog(QuestionAnswerActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
BackendAPIService sh = new BackendAPIService();
String ResponseURL = Const.API_RESPONSE
+ "?os=droid&user_id="
+ Pref.getValue(QuestionAnswerActivity.this,
Const.PREF_USER_ID, "") + "&myrole="
+ Const.MY_ROLL + "&q_id=" + params[0] + "&ans=" + ans
+ "&time=5&game_id=" + Const.GAME_ID + "";
JsonStr = sh.makeServiceCall(ResponseURL, BackendAPIService.GET);
System.out.println("::::::::::::;My Response request::::::::::;;;"
+ ResponseURL);
Log.d("Response: ", "> " + JsonStr);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
countDownTimer.cancel();
pg_loading.setProgress(0);
progressStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
if (run) {
pg_loading.setProgress(progressStatus);
pg_loading
.setProgressDrawable(getResources()
.getDrawable(
R.drawable.progress));
}
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
questionTask(count);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public int randomGenerator() {
Random r = new Random();
int ans = r.nextInt(4 - 1) + 1;
return ans;
}
}
You can easily hold some boolean variable for that case:
private boolean run = true;
then gather all the Buttons onClickListeners in one click listener, like the main one of the class, and upon anyclick make that variable run=false, So, check that before set the progress:
if(run){
pg_loading.setProgress(progressStatus);
}else{
//stop, finish, do whatever you want
}
in onClick listener:
public void onClick(View v) {
// TODO Auto-generated method stub
run = false;
Intent i;
switch (v.getId()) {
.
.
.
}
UPDATE:
make the thread as the following:
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
if(run){
pg_loading.setProgress(progressStatus);
pg_loading.setProgressDrawable(getResources()
.getDrawable(R.drawable.progress));
}
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
UPDATE 2:
your onPostExcute in the AsyncTask must be:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
countDownTimer.cancel();
pg_loading.setProgress(0);
progressStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
pg_loading.setProgress(progressStatus);
pg_loading
.setProgressDrawable(getResources()
.getDrawable(
R.drawable.progress));
}
});
I am reading lat/lon from file, creating polygon and adding it to the map in AsyncTask. Everything is working fine - except progressDialog allways freezes at start of the action and dismissed after action is completed.This is my code:
UPDATED CODE:
private class shpLoading extends AsyncTask<GoogleMap, List<LatLng>, String> {
private ProgressDialog dialog;
private String path;
private int loaded;
public void setPath(String p){
this.path = p;
}
#Override
protected String doInBackground(GoogleMap... params) {
final ShpReader shpRead = new ShpReader();
try {
shpRead.read(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidShapeFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.setMax(shpRead.daugiakampiai().size());
int i = 0;
for(List<LatLng> a: shpRead.polygons()){
function.arAntLinijos(a);
for(int h = 0; h < a.size()-1; h++){
LatLng point = function.midPoint(a.get(h), a.get(h+1));
a.add(h+1, point);
h++;
if(i > 3000){
message("You reached max count!");
break;
}
}
publishProgress(a);
i++;
}
return "Done";
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(Measuring.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage(getString(R.string.loading));
dialog.setCancelable(false);
dialog.setProgress(0);
dialog.show();
}
}
#Override
protected void onProgressUpdate(List<LatLng>... values) {
dialog.setProgress(loaded++);
Polygon daug = mMap.addPolygon(new PolygonOptions()
.addAll(values[0])
.strokeWidth(1)
.strokeColor(Color.RED)
.fillColor(0x3F00FF00));
plotai.add(new Polygons(db.getMaxFieldID()+1, daug));
daug = null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
Because you should draw your polygons not in onProgressUpdate method, but in doInBackground method. In onProgressUpdate method you have to update progress in your ProgressDialog object (in your code ProgressDialog is showed, but not updated its progress at all).
I am downloading a file from dropbox which is taking a few seconds. I want to add a ProgressDialog for the download but I don't know how to do that.
public class DownloadFile extends AsyncTask<Void, Long, Boolean> {
DownloadFile(Context context ,DropboxAPI<?> mApi ,String dropboxpath,String sdpath,int pos,int s,ArrayList<String> folder) throws DropboxException {
FileOutputStream mFos;
File file=new File(sdpath);
String path = dropboxpath;
try{
mFos = new FileOutputStream(file);
mApi.getFile(path, null, mFos, null);
}catch (Exception e) {
// TODO: handle exception
}
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
Do it this way:
public final class DownloadFile extends AsyncTask<Void, Long, Boolean> {
private Context context;
private ProgressDialog progressDialog;
public DownloadFile (Context context) {
this.context = context;
}
/*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
try {
progressDialog = ProgressDialog.show(context, "", "message", true);
} catch (final Throwable th) {
//TODO
}
}
/*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Boolean doInBackground(Void... arg0) {
//do something
}
#Override
protected void onProgressUpdate(String... progress) {
//do something
super.onProgressUpdate(progress);
}
/*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Boolean result) {
progressDialog.dismiss();
} }
Use this simple code #sachin
public class DownloadFile extends AsyncTask<Void, Void, Void> {
Home home;
ProgressDialog dialog = null;
public DownloadFile(Home home) {
// TODO Auto-generated constructor stub
this.home = home;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//Call hare method for download
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(home, "Downloading......", "", true);
}
}
This article can be useful for you:
http://huuah.com/android-progress-bar-and-thread-updating/
Where inside the run() method of your thread you can invoke a function like this:
public boolean download(String url, String path, String fileName, Handler progressHandler) {
try {
URL sourceUrl = new URL(formatUrl(url));
if (fileName == null || fileName.length() <= 0) {
fileName = sourceUrl.getFile();
}
if (fileName == null || fileName.length() <= 0) {
throw new Exception("EMPTY_FILENAME_NOT_ALLOWED");
}
File targetPath = new File(path);
targetPath.mkdirs();
if (!targetPath.exists()) {
throw new Exception("MISSING_TARGET_PATH");
}
File file = new File(targetPath, fileName);
URLConnection ucon = sourceUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(100);
int current = 0;
int totalSize = ucon.getContentLength();
while ((current = bis.read()) != -1) {
baf.append((byte) current);
// BEGIN - Handler feedback
if (progressHandler != null && (baf.length() % 100) == 0) {
Message msg = progressHandler.obtainMessage();
Bundle b = new Bundle();
if (totalSize > 0) {
b.putInt("total", totalSize);
b.putInt("step", baf.length());
b.putBoolean("working", true);
}
msg.setData(b);
progressHandler.handleMessage(msg);
}
// END
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
// BEGIN - Handler feedback
if (progressHandler != null) {
Message msg = progressHandler.obtainMessage();
Bundle b = new Bundle();
if (totalSize > 0) {
b.putInt("total", 0);
b.putInt("step", 0);
b.putBoolean("working", false);
}
msg.setData(b);
progressHandler.handleMessage(msg);
}
// END
return file.exists();
}
Doing this way, you have a more accurate feedback about real progress of you download (byte per byte).
See there are actually 4 methods of AsyncTask:
onPreExecute() - you can do some pre execution task here.
doInBackground() - you can perform some background work here.
onPostExecute() - you can perform post execution task here. Means like displaying data in ListView, update TextView, etc.
onProgressUpdate() - To update UI while background operation is going on.
So in your case, you can show progress dialog or progress bar inside onPreExecute() method of AsyncTask and dismiss(() the same inside onPostExecute().
I have used following code for download some files from our internet.
public class SplashDownload extends Activity {
public static final int PROGRESS_DIALOG = 0;
private ProgressDialog mProgressDialog;
private WordDataHelper wordDataHelper;
private ExtraDataHelper extraDataHelper;
// put your file path here
private String filePath = "http://test.com/Assets/";
// put your filename here
private String fileName;
// put your download directory name here
private String downloadDir;
private int wordCounter = 0, extraCounter = 0, counter = 1;
private boolean wordDLOn = true;
private int totalFileNo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashdllayout);
getDownloadList();
}
private void goForward() {
Intent intent = new Intent().setClass(this, LangH.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
private void doNext() {
if (wordDLOn) {
System.out.print("wordDetails update: "
+ wordDetails[wordCounter - 1][0]
+ extraDetails[extraCounter][0] + fileName);
wordDataHelper.updateDLStat(Long
.valueOf(wordDetails[wordCounter - 1][0]));
} else {
System.out.print("extraDetails update: "
+ extraDetails[extraCounter - 1][0] + fileName);
extraDataHelper.updateDLStat(Long
.valueOf(extraDetails[extraCounter - 1][0]));
}
if (wordCounter < wordDetails.length) {
System.out.print("wordCounter: " + wordCounter + "/"
+ wordDetails.length);
startDownload(wordDetails[wordCounter][1]);
wordCounter++;
} else if (extraCounter < extraDetails.length) {
wordDLOn = false;
downloadDir = "LanH/extras";
System.out.print("extraCounter: " + extraCounter + "/"
+ extraDetails.length);
startDownload(extraDetails[extraCounter][1]);
extraCounter++;
} else {
goForward();
}
}
private void getDownloadList() {
// lessons download..........
String[] wordDetails = {"1.mp4","2.mp4","3.mp4","4.mp4","5.mp4","6.mp4","7.mp4","8.mp4",};
downloadDir = "LanH/words";
String[] extraDetails = {"a.mp4","b.mp4","c.mp4","d.mp4","e.mp4","f.mp4","g.mp4","h.mp4",};
totalFileNo = extraDetails.length + wordDetails.length;
if (wordDetails.length != 0) {
startDownload(wordDetails[wordCounter]);
wordCounter++;
} else if (extraDetails.length != 0) {
wordDLOn = false;
startDownload(extraDetails[extraCounter]);
extraCounter++;
} else {
goForward();
}
}
private void startDownload(String dlFilename) {
// tv = (TextView) findViewById(R.id.tv1);
fileName = dlFilename;
System.out.print("fileName: " + fileName);
File dir = new File(android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/"
+ downloadDir);
// creates the directory if it doesn't exists
if (dir.exists() == false) {
dir.mkdirs();
}
dir = null;
if (checkNet()) {
if (checkExternalMedia() == true) {
String url = filePath + fileName;
new DownloadFileAsync().execute(url, fileName);
mProgressDialog.setMessage("Downloading file.." + fileName);
} else {
Toast.makeText(getApplicationContext(),
"External Media is NOT readable/writable",
Toast.LENGTH_SHORT).show();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No Internet Connectivity. Check the connection and retry the app.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
/** Method to check whether external media available and writable. */
private boolean checkExternalMedia() {
boolean stat;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
stat = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
stat = false;
} else {
// Can't read or write
stat = false;
}
return stat;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file.." + fileName);
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(PROGRESS_DIALOG);
}
#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("DOWNLOAD_TEST", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
android.os.Environment.getExternalStorageDirectory()
+ "/" + downloadDir + "/" + aurl[1]);
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("DOWNLOAD_TEST", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(PROGRESS_DIALOG);
// tv.append("\n\nFile Download Complete!");
// Button btn = (Button) findViewById(R.id.btn1);
// btn.setVisibility(View.GONE);
// you can call a second intent here to redirect to another screen
doNext();
}
}
private boolean checkNet() {
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState() == NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
// we are connected to a network
connected = true;
} else
connected = false;
return connected;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
The process is running fine. It is reported following crash report:
java.lang.IllegalArgumentException: no dialog with id 0 was ever shown via Activity#showDialog
at android.app.Activity.missingDialog(Activity.java:2663)
at android.app.Activity.dismissDialog(Activity.java:2648)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:264)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:5068)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
What is the problem in my code? Is isShowing() check before dismissDialog will solve the prob?
Does your progress dialog actually show up?
Instead of dismissing it you could try using removeDialog(PROGRESS_DIALOG); to have it cleaned up.
See if this thread helps - AlerDialog is not created - java.lang.IllegalArgumentException: Activity#onCreateDialog did not create a dialog for id X
When you do the
mProgressDialog.show();
during
protected Dialog onCreateDialog(int id)
you already set the ID for the Dialog to some random or null value.
So when you call to dismiss it, the Application thinks you are crazy.