I'm trying to show a ProgressDialog when loading an Activity, but it doesn't show up.
Here is the method called on Activity onCreate
private void loadBuilding(String[] b) {
ProgressDialog pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(6);
pd.setTitle(R.string.loading);
pd.show();
LoadBuilding lb = new LoadBuilding();
lb.initialize(this, pd);
lb.execute(b);
try {
lb.get();
} catch (Exception e) {
e.printStackTrace();
}
pd.dismiss();
if (building == null)
showError();
}
The LoadBuilding is an AsyncTask in which I load the building and set the progress.
Thanks to all.
Problem was that the progressDialog.dismiss() must be in:
The catch of the try/catch showed in the code
The onPostExecute method of AsyncTask.
Also I'm using too few data for testing, so it comes up and down too fast.
Use AsyncTask for Background processing and Updating Progressing in Foreground. I think that best suited your task.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Try to add your progressDismiss() in try and catch block
try
{
pg.dismiss();
}
Catch()
{
}
Related
I am a newbie in android. I want to make an application that show dialog loading when I get data from server. I want my loading screen such as this picture below:
I don't know any key to searching to make this loading :(. Is This application show in the picture using progress bar with animation?. I have some picture when I extract apk file of this application and I have some pictures as below:
try this.
in run() put code which rewrite your progressbar...
if you want stop timer. use timer.cancel();
and for example start faster timer for finish progress..
imer timer= new Timer();
timer.schedule(
new TimerTask() {
#Override
public void run() {
runOnUiThread(
new Runnable() {
#Override
public void run() {
**thise code run every 100ms**
}
}
);
}
}, 0, 100);
it's simply, if you want correctly resolve thise problem use Threats.
Have you tried using AsyncTask?
You should look on Android Threading concepts. and as mentioned remember runOnUiThread for calls that updates your UI.
You should extend a progressbar and handle the images position on it...
Here is the AsyncTask example code:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
I need to have a network process running on a non-UI Thread and a UI thread running at the same time to inform the user that the process is running, and that the app isn't frozen, and won't allow the next block of code to be executed until the network connection gives its response.
What would the best way to go about doing this?
AsyncTasks are the way to go.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
I the code blow.
And I need to call execute within a loop.
Problem is I need the loop to pause while execute is completing and then continue.
The loop runs but it calls execute immediately, which causes the files not be to downloaded.
private class DownloadVerses extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
//Thread.sleep(5000);
if(Utils.downloadFile(params[0])){
int progressPercentage = Integer.parseInt(params[2]);
downloadProgress.setProgress(progressPercentage);
return "Downloading: "+params[1];
}
else{
return "ERROR Downloading: "+params[1];
}
} catch (Exception e) {
Thread.interrupted();
return "ERROR Downloading: "+params[1];
}
}
#Override
protected void onPostExecute(String result) {
if(result.contains("ERROR")){
downloading.setTextColor(Color.parseColor("#f05036"));
}
else{
downloading.setTextColor(Color.parseColor("#79a1ad"));
}
downloading.setText(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
And I am currently trying:
DownloadVerses download = new DownloadVerses();
int i = 0;
while(i < verseTitles.size()){
String progressString = String.valueOf(progress);
if(download.getStatus() != AsyncTask.Status.RUNNING){
download.execute(Mp3s.get(i), Titles.get(i),progressString);
if(progress < 100){
if((progress + increment) > 100){
progress = 100;
}
else{
progress += increment;
}
}
i++;
}
}
Remove this line...
DownloadVerses download = new DownloadVerses();
And every time create a new object of DownloadVerses to execute a new AsyncTask...This procedure will not stop any AsyncTask from execution and it will allow every AsyncTask to execute independently.
new DownloadVerses().execute(Mp3s.get(i), Titles.get(i),progressString);
Update your code as follows...
int i = 0;
while(i < verseTitles.size()){
String progressString = String.valueOf(progress);
if(download.getStatus() != AsyncTask.Status.RUNNING){
new DownloadVerses().execute(Mp3s.get(i), Titles.get(i),progressString);
if(progress < 100){
if((progress + increment) > 100){
progress = 100;
}
else{
progress += increment;
}
}
i++;
}
}
Update:
You can use onProgressUpdate() method to update progress update. For more details, you can see AsyncTask document from Android Developer site.
I have created a program in android for multithreading.
When I hit one of the button its thread starts and print value to EditText now I want to determine that thread is running or not so that I can stop the thread on click if it is running and start a new thread if it is not running here is mu code:
public void startProgress(View view) {
final String v;
if(view == b1)
{
v = "b1";
}
else
{
v = "b2";
}
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
//for (int i = 0; i <= 10; i++) {
while(true){
if(v.equals("b1"))
{
i++;
}
else if(v.equals("b2"))
{
j++;
}
try {
if(v.equals("b1"))
{
Thread.sleep(3000);
}
else if(v.equals("b2"))
{
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
// progress.setProgress(value);
if(v.equals("b1"))
{
String strValue = ""+i;
t1.setText(strValue);
}
else
{
String strValue = ""+j;
t2.setText(strValue);
}
//t1.setText(value);
}
});
}
}
};
new Thread(runnable).start();
}
#Override
public void onClick(View v) {
if(v == b1)
{
startProgress(b1);
}
else if(v == b2)
{
startProgress(b2);
}
}
Instead of that messy code, an AsyncTask would do the job you need with added readability ...
It even has a getStatus() function to tell you if it is still running.
You'll find tons of examples by looking around a bit (not gonna write one more here). I'll simply copy the one from the documentation linked above:
Usage
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
Here is an example of subclassing:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
Use a static AtomicBoolean in your thread and flip its value accordingly. If the value of the boolean is true, your thread is already running. Exit the thread if it is true. Before exiting the thread set the value back to false.
There are some way can check the Thread properties
You able to check Thread is Alive() by
Thread.isAlive() method it return boolean.
You able to found runing thread run by
Thread.currentThread().getName()
Thanks
I want to add a simple process bar to my code with asy task. I tryed some exampels but cant see that process bar working.
I post here my code hope you can help me.
I want to stop process bar when some of my code is done like with some flag to stop the proses bar.
plese post some code.
thanks a lot!
here my code:
private class loading extends AsyncTask<Void, Void, Integer> {
Context context;
ProgressBar progressBar;
static final long waitTime = 1 * 4000L;
long preTime;
int progress;
public loading(Context context) {
this.context = context;
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setProgress(0);
}
protected void onPostExecute(Integer result) {
Intent intent = new Intent(this.context, first.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(intent);
finish();
return;
}
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
preTime = System.currentTimeMillis();
}
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
}
#Override
synchronized protected Integer doInBackground(Void... arg0) {
int waited = 0;
while (waited < 3000) {
try {
// SystemClock.sleep(100);
this.wait(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
waited += 100;
}
return null;
}
}
Your doInBackground method needs to call publishProgress() in order for you to update the UI.
After the line waited += 100; add:
int progress = Math.round((float)waited / 3000 * 100);
publishProgress(progress);
Also, the signature of AsyncTask is wrong if you intend on using an integer to reflect your progress. The generic parameters are AsyncTask<Params, Progress, Result>, so in your case, you're not accepting any arguments, or returning any meaningful value from doInBackground, but, you do want to return an Integer to indicate progress. So, change your class declaration to match:
private class loading extends AsyncTask<Void, Integer, Integer>
{
//your implementation
}
You are not calling AsyncTask.publishProgress and that is why your onProgressUpdate method is never called.
And by the way, your class name loading brokes naming conventions, that's not a good practice.