As and when i click to button, it waits for 20 seconds and then getting text to text view, my requirement is that after 1 second, progress bar has to increment by 5 values.
Can any one guide me in following code
public class ProgressBar1 extends Activity{
TextView tvpbview;
ProgressDialog pd1;
ProgressBar pbhr1;
Button btnhp1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progressbar1);
btnhp1 = (Button) findViewById(R.id.btnProgress);
pbhr1 = (ProgressBar) findViewById(R.id.pbHori1);
pbhr1.setMax(100);
btnhp1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//--- For Horizontal Progress Bar------
for(int i=0;i<=20;i++)
{
pbhr1.incrementProgressBy(5);
tvpbview.setText(""+pbhr1.getProgress()+"% done");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
You approach is incorrect, you need to use correct form of Threads. Especially for your case i recommend to you use following:
Handler
AsyncTask
Most likely you need to read some tutorial so have look at
Android Threads, Handlers and AsyncTask -
Tutorial
this is a great source.
Note: AsyncTask is more complex than Handler and also is generic-type and is especially designed for updating UI with some progress.
create an asynchronous task. Android provides the AsyncTask class for this purpose. You create a progress bar on the UI thread, then call the publishProgress() method to update your progress bar. It's really simple to use, the documentation is excellent.
try this
After they have been initially set, if you want to then change the values you need to set it to zero in between:
ProgressBar dataProgressBar = (ProgressBar) findViewById(R.id.progressBarData);
//set to 0 first to stop the bug from happening
dataProgressBar.setMax(0);
dataProgressBar.setProgress(0);
//set your new values
dataProgressBar.setMax((int) dataAllowanceValue);
dataProgressBar.setProgress((int) dataMBytes);
Related
I'm beginner in Android Devloping, I have a trouble with UI in Android
I have a code look like this:
public class MainActivity extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
tv1.setVisibility(View.GONE);
tv2.setVisibility(View.GONE);
String s="abc";
MyAsyncTask BkGroundTask = new MyAsyncTask();
BkGroundTask.execute(s);
try {
s = BkGroundTask.get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();}
tv1.setVisibility(View.VISIBLE);
tv2.setVisibility(View.VISIBLE);
}
}
But tv1 and tv2 do not disappear when AsyncTask is running.
What should I do to fix this?
an asynctask executes asynchronously, you are on the assumption that everything pauses when you call execute which is wrong and would defeat the purpose of an asynctask. in reality it is disappearing but then reappearing. it is happening so fast that you probably cant even notice it.
if you want to textview to display when the task is done you need to do that in the onpostexecute of the task
example
#Override
public void onPostExecute(Void void){
tv1.setVisibility(View.VISIBLE);
tv2.setVisibility(View.VISIBLE);
}
This has been discussed many times but I will explain again for what you want since you want a special scenario...
You almost never want to use .get() because it is a blocking call. This means that it will lock up your UI until the task is finished. .execute(), as you have, is what you want.
If you want them to be gone while the task is running and be visible again when the task finishes then you want to put the code to show them inside of onPostExecute() if it is an inner-class and if not then you can use a callback to the Activity from onPostExecute() and show them in the callback method.
This answer discusses how to use an interface with your AsyncTask
Related Post
I have an activity class as below.
public class LoginActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (ImageView) findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
loader = (ProgressBar) findViewById(R.id.loader);
Thread processThread = new Thread(loaderThread);
loader.setVisibility(View.VISIBLE);
processThread.start();
try {
Thread.currentThread().join();
Log.i("Activity","gone past join()");
loader.setVisibility(View.INVISIBLE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private Runnable loaderThread = new Runnable() {
public void run() {
ServiceCaller serviceCaller = new ServiceCaller();
boolean status = serviceCaller.checkProcess(url);
}
};
}
Further Question [EDITED]
Here is the scenario. The main activity class creates a thread on a click. The then created thread fetches some data from the server. It is a time consuming task. So a progress bar is displayed on the UI. Currently I am using AsyncTask (not shown here) to accomplish server data retrieval. But the real challenge is wait for the background task to complete and get the value from it. What I am looking for is:
wait until server calls are made and get the results. Meanwhile show the progress bar.
Any thoughts? Apologies in case I confuse you.
Thanks in advance!
You must have a look at AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
http://www.vogella.com/articles/AndroidPerformance/article.html
and you can show the ProgressBar in onPreExecute()
do the task in doInBackground()
and hide the ProgressBar in onPostExecute()
Join method blocks the current thread. In your case Onclick method is called in UI thread, so all UI operations are blocked. It is never a good idea to block Ui thread.
So you probably should use either a Handler or Asynctask to keep updating Progressbar
In an effort to learn Android I am writing a small app. The first thing I am trying to do is login via a remote API.
I would like to show a "loading" dialog when the call is being made (in case he user in using mobile internet). Researching this has shown two possible methods.
One is to use a ProgressDialog and a private class that extends Thread, the other is using a private class that extends AsyncTask.
Which is best/more appropriate for this task?
I have tried using the ProgressDialog version but am struggling. I have put the function making the http request in the extended Thread run() method, but am unsure on how to pass the response data (JSON) back into my activity.
Any and all help gratefully received.
The best way possible is to use an AsyncTask with a ProgressDialog. You should extend AsyncTask and implement all the methods you need:
onPreExecute() - here you initialize your ProgressDialog and show() it
doInBackground() - here you do your work
onPostExecute() - here you call dismiss() on ProgressDialog to hide it
(optional) onProgressUpdate() - here you can change the progress of your ProgressDialog if it's determinate
There is a get() method in AsyncTask class that lets you retrieve the result of the work. Also you can implement an interface between the AsyncTask and calling Activity to return the result. Hope this helps.
Efforts come with rewards :) Egor is right, AsyncTask is the best way to do it. But
You have to know that Activity is working on the UI thread and threads not. So the only way to share things is via handler. Here an example:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
handler= new Handler();
}
public void startProgress(View view) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
progress.setProgress(value);
}
});
}
}
};
new Thread(runnable).start();
}
I have some TextViews in my app that I want updated automatically each 5 seconds. I have a method for refreshing them, but how do I make a timer that runs the method every 5 seconds? Thanks!
Provide another solution
Handler h=new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
h.post(new Runnable(){
#Override
public void run() {
// call your function
h.postDelayed(this,5000);
}
});
Look at extending a CountDownTimer, it has an onFinish() method you can overwrite to update your TextView, and restart the timer if you wish to make it repeat. You can also bind to onTick() if you only want to update a finite number of times.
I tried the Handler solution myself, especially after reading this article on the resource pages: http://developer.android.com/resources/articles/timed-ui-updates.html. But I wanted to be able to start and stop the timer much like a stopwatch, and after resuming the timer the Handler solution started updating much less regularly - on the emulator about every five seconds. In the end I found a tip on a blog that suggested the solution with an inner class extending AsyncTask. You can make use of the publishProgress()-onProgressUpdate() functionality in AsyncTask. From onProgressUpdate(), you're allowed to make changes "directly" in your UI thread e.g. myTextView.setText(...). This publishes results much more frequently. Here's a super simple implementation of that inner class:
private class UpdateTimerLabel extends AsyncTask<Integer, Integer, Integer> {
#Override
protected Integer doInBackground(Integer... arg0) {
while (true) {
try {
Thread.sleep(1000);
publishProgress(arg0);
Log.d(tag, "AsyncTask tries to publish");
} catch (InterruptedException e) {
e.printStackTrace();
}if (1 == 0) break; // Silly but necessary I think
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
updateTimerTextView(); // Call to method in UI
}
}
Can I use progress bar in android, without the thread?
HERE IS CODE OF MY CURRENT WAY OF IMPLEMENTING PROGRESS DIALOG
// Adding Progress bar
String[][] data; //Global variable
//called on onCreate() or onItemSelected
final ProgressDialog myProgressDialog;
myProgressDialog = ProgressDialog.show(ListingPage.this,"Please Wait", "Loading Date", true);
new Thread() {
public void run() {
try{
setSelected();
sleep(5000);
} catch (Exception e) { }
myProgressDialog.dismiss();
}
}.start();
populateList(Split.splitToTwoDimArray(data)); // populates the list view
HOPE ABOVE HELPS, IF USING THREAD THE LIST IS NOT BEING POPULATED.
Sure, you can always set the progress manually via
progressBar.setProgress(int progress);
Above question/added code is a bit confusing cause you asked how to use the progress bar without a thread but now in your code you're using a thread. I thought that you initially wanted to avoid.
Anyway, maybe you should use an AsyncTask instead of the Thread, which allows you to modify anything in the main UI thread.
https://sites.google.com/site/androidhowto/how-to-1/create-a-custom-progress-bar-using-asynctask
http://developer.android.com/reference/android/os/AsyncTask.html