I need to change the content of progress dialog when sync activity is running it shows "synchronizing data"
when it has completed it goes for another background activity and still shows the same text what I want is to change the text when it goes to other background task?
protected void onPreExecute() {
mDialog = ProgressDialog.show(viewContext, "", "Synchronizing Data",
true);
};
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Boolean doInBackground(Void... arg0) {
if (type.contains("ferry")) {
return SynchronizeRepositoryFerry(false);
} else {
boolean value = SynchronizeRepositories(false, initialSync);
mDialog.setTitle("Loading Images");//FROM HERE I WANT TO CHANGE DIALOG
com.jumbybay.businessobjects.User user = new com.jumbybay.businessobjects.User();
DatabaseHelper dbHelper = new DatabaseHelper(viewContext);
IUserRepository repository = dbHelper.getUserRepository();
List<com.jumbybay.businessobjects.User> imageList;
try {
int id;
String url = "http://i.zdnet.com/blogs/3-29-androids.jpg";
imageList = repository.Retrieve();
for (int i = 0; i < imageList.size(); i++) {
user = imageList.get(i);
// url = user.getPicture();
id = user.getId();
fetchImage fetch = new fetchImage();
fetch.savesd(id, url);
}
} catch (SQLException e) {
// TODO Auto-generated catch block// url = user.getPicture();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
}
protected void onProgressUpdate(Integer... progress) {
mDialog.setTitle("lOADING IMAGES...");
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Boolean result) {
this.syncComplete = result;
mDialog.dismiss();
Intent intent = new Intent();
intent.setClass(viewContext, classType);
viewContext.startActivity(intent);
}
have you tried using it like this
mDialog.setTitle("Loading Images");
mDialog.show();
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 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.
Hi i want to display progressdialog until a command is executed through telnet.
so i use asynctask for that purpose.
private class AsyncAction extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pd.dismiss();
}
// pd.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
And i call asynctask in oncreate() like below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
The problem is that i could not see progressdialog until command executes.
please help me solve the issue.
Thanks in advance.
EDIT
The code to send and read command
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length()-1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar)
{
if (sb.toString().endsWith(pattern))
{
if (sb.toString().contains("cdkk"))
{
disconnect();
break;
}
else
{
return sb.toString();
}
}
else
{
disconnect();
break;
}
}
else if(sb.toString().contains("Failed"))
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String error="Invalid username or password!";
alertbox.setMessage(error);
alertbox.setTitle("Error");
alertbox.show();
System.out.println("bad user name");
disconnect();
break;
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently you are trying to do Network operations from onPostExecute because this method called from UI Thread . change your code as to get work in proper way
private class AsyncAction extends AsyncTask<String, Void, String>
{
public static boolean status=false;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
// make status true or false if command successfully executed
status=true;
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
// check status if true then show AlertDialog
if(status==true){
AlertDialog.Builder alertbox =
new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
else{
// your code here
}
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
You need to show the progress bar in onPreExecute() do the work in doInBackground() and then hide the progress bar in onPostExecute(). onPreExecute() and onPostExecute() are both executed on the main thread, where as doInBackground is executed in the background.
You are doing your work on onPostExecute() method which should be inside doInBackground()
show your progress dialog inside onPreExecute() and dismiss inside onPostExecute().
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().
private static String CONSUMER_KEY = "mrnCC41nxtwkdFAmToEhtg";
private static final String CONSUMER_SECRET = "kmmVuahEspGvdl14aCD1GSBZpeHbxvkpAez7aKaaQ";
EditText editPinCode;
LinearLayout lin;
public Logger slr;
LinearLayout container;
public LoginT(){
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.twitter);
editPinCode = new EditText(this);
lin = (LinearLayout)findViewById(R.id.LinearLayout01);
handleEvent = new Handler();
twitterConnection = new TwitterFactory().getInstance();
context = this;
oHelper = new OAuthHelp(this);
getTwitter(context);
}
/**
* Connects to twittter
* #param v
*/
public void getTwitter(Context ctx) { //updated code
handleEvent.post(new Runnable() {
// handleEvent.postAtFrontOfQueue(new Runnable() {
public void run() {
if (oHelper.hasAccessToken())
{
Log.e("run if","run");
oHelper.configureOAuth(twitterConnection);
try
{
i=i+1;
Log.e("run try","run");
twitterConnection.updateStatus(Calendar.MINUTE+i+"Hi this is Arun......");
//twitterConnection.se
Log.e("finish","start");
finish();
Log.e("finish","end");
}
catch (TwitterException e)
{
Log.d("TWEET", "Error Updating status " + e.getMessage());
e.printStackTrace();
}
}
else
{
Log.e("run else","run");
try {
twitterConnection.setOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);
requestToken = twitterConnection.getOAuthRequestToken("");
Log.e("REQUEST_TOKEN",requestToken+"");
webViewDialog(requestToken.getAuthorizationURL(), 0);
}
catch (TwitterException e)
{
e.printStackTrace();
}
}
}});
}
/**
* Shows Dialog for authentications
*
* #param authorizationURL
* #param type
*/
private void webViewDialog(final String authorizationURL, final int type) {
Log.e("webViewDialog","webViewDialog");
container = new LinearLayout(this);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(this);
webView.setMinimumWidth(200);
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
// webView.dispatchWindowFocusChanged(true);
webView.setWebViewClient(new MyWebViewClient(this,LoginT.this));
webView.loadUrl(authorizationURL);
container.addView(webView);
lin.addView(container);
// Builder webDialog = new AlertDialog.Builder(this);
// webDialog.setView(container).setTitle("Twitter Client").setCancelable(true)
// .show();
}
/**
* Pin code dialog Requests the user to enter pin shown on twitter
*/
public void twitterPinCodeDialog() {
try {
// accessToken = twitterConnection.getOAuthAccessToken(requestToken,ss);
try{
accessToken = twitterConnection.getOAuthAccessToken(requestToken);
}
catch(Exception e1){
Log.w("Excep e1",e1+"");
}
oHelper.storeAccessToken(accessToken);
Log.w("ohelper",oHelper.toString());
twitterConnection.updateStatus("Tweeted Successfully"+new Date().toString());
Log.e(" ","2 "+accessToken);
Log.e(" ","3");
webView.destroy();
webView.removeAllViews();
container.removeAllViews();
this.finish();
// Log.i("Access Token:", accessToken.getToken());
// Log.i("Access Secret:", accessToken.getTokenSecret());
} catch (TwitterException te) {
oHelper.storeAccessToken(accessToken);
try {
twitterConnection.updateStatus("HI.... ");
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id) {
// case DIALOG_LOADING:
// {
// // dialog = new ProgressDialog(this);
// dialog.setMessage("Please wait while loading...");
// dialog.setIndeterminate(true);
// dialog.setCancelable(true);
// return dialog;
// }
}
return null;
}
//
// #Override
public void dismiss() {
Log.w("dismiss","dismiss");
try{
// webView.destroy();
// webView.removeAllViews();
// container.removeAllViews();
// this.finish();
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
//
#Override
public boolean onSearchRequested() {
Log.e("Search","Search");
return super.onSearchRequested();
}
I use the above Code for making connection for twitter but it only works for one time if I want another time for connection then it never provide me second time connection.
Thankx
Could this be an Activity lifecycle issue? Your call to getTwitter() occurs in onCreate, which only gets called when the Activity is created. If a user navigates away then comes back to your app, it may still be running, so onCreate would not get called again. Have a look at the Activity lifecycle, and add some debug code to each of the lifecycle methods (onResume, onPause etc) to get an idea of when they are called.