Android: Array Loop - next element only after first loop finish - android

I would like to initiate void function with Array element. Simple example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seven_minutes);
Excercise();
final String Array[] = {"e1","e2","e3"};
for (int i = 0; i < Array.length; i++ ){
jump(Array[i]);
}
}
private void jump (String i){
wait 30s;
}
How to make, that second [i] would be initiate only after jump (Array[i]) function is finished? Like after 30s of it?

Assuming that jump method executed in a different thread, you need to execute inside the UI thread (onCreate) a join() method, that allows a thread to wait the finish of another thread, until it can continue its execution.
However, this does not seems a good idea, since your UI thread will be blocked for too much time.
You should manage them asynchronously. There are a lot of ways you can do it. For example you can use [AsyncTask][1] that allows you to execute some code in background (inside doInBackground) and at the end of this code executed in background, will be executed some code in the UI thread (onPostExecute).
So, you can check your condition the first time, then call the AsyncTask, and in onPostExecute recheck the condition (Array.lenght < i), and if it is verified, you can relaunch the AsyncTask.

Related

AsyncTask starts after function is finished

I just have a public function where I have some loops etc. and in the beginning of my function I start my AsyncTask which returns me a value which is needed in the near of the end of this function. But somehow the AsyncTask just starts after this function finished ? Is there a way to run the Asynctask before or parallel ? Until today I thought AsyncTask are normally running parallel. I found out the method
.get()
but this is freezing the thread ... I need an alternative or fix
public void my_function ()
{
new async_task().execute()
... //do something
if (returned_value_from_async_task == 10) //Here I need the variable which is returned in the async_task
{
... //do something
}
} //End of function
//When I go to debug mode the AsyncTask starts right here
Yes. Thats the "Async" part of AsyncTask. The code at the end of the function isn't going to wait for the task to finish. so you can't rely on that data to be there. The code you're running in your function probably takes less time than it takes the ThreadPoolExecutor to spool up your task.
Execute the code that depends on the data from the AsyncTask in onPostExecute
EDIT:
Without knowing what "more complex" means, it's hard to say what your best option is. But you could split the function, thusly
public void preExecutePrep() {
YourTask yourTask = new YourTask();
yourTask.execute();
//do what you can without the result
}
private void postExecuteCode(int result) {
if (result != 10) return;
//do the rest
}
then call postExecuteCode in onPostExecute. If this isn't going to cut it, I'll need more specific information to help

Android ProgressBar not updating as expected?

I am dynamically populating a TableLayout with rows using an AsyncTask and am not getting the expected ProgressBar behavior.
I initially set the max value of the ProgressBar to three times the number of items I'm processing to accommodate three operations. Here's my code:
onPreExecute:
progress.setMax(items.size() * 3); // We need to create the rows and add listeners to them
Async Class
public class TableLoader extends AsyncTask<Object, String, Boolean>{
#Override
protected Boolean doInBackground(Object... params) {
for (int i = 0; i < items.size(); i++) {
// doStuffToCreateRow
rows.add(row);
progress.publishProgress();
}
}
Then I have:
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (!isCancelled()) {
for (int i = 0; i < rows.size(); i++) {
table.addView(rows.get(i));
progress.incrementProgressBy(1);
}
table.requestLayout();
listener.onTaskCompleted();
}
}
Where publishProgress is simply:
protected void onProgressUpdate(String... values) {
progress.incrementProgressBy(1);
}
Finally, in my onPostExecute method, I have a callback to the activity that uses the AsyncTask, which looks like this in the main activity:
public void onTaskCompleted() { // TableRows have been generated
TableLayout itemTable = (TableLayout) findViewById(R.id.itemTable);
for (int i = 0; i < itemTable.getChildCount(); i++) {
TableRow row = (TableRow) itemTable.getChildAt(i);
// Create and add a listener to that row's checkbox
// progress.incrementProgressBy(1);
}
progress.setVisibility(View.GONE);
}
For some reason, the initial increment works properly and causes the progressBar to reach 1/3 full after its completion (generation of TableRows). Afterwards, there's a 2-5 second pause where the UI thread blocks and then the progressBar disappears, which I've set to occur after the for loop in the onTaskCompleted (the third and final operation) terminates. The data then shows up.
Why is my progressBar not updating as expected?
I've looked the issue up but have found people incrementing the bar by < 1 using division or not using the UI thread. To my knowledge, I'm updating using the UI thread and incrementing by 1/number of items * 3 each time.
For some reason, the initial increment works properly and causes the progressBar to reach 1/3 full after its completion
It means the Async part is working properly, your first third is the one involving doInBackground / ProgressUpdate, that is, heavy stuff is done outside of the UI thread and just signals progress update. The UI thread is sleeping and happily waiting for update requests.
Afterwards, there's a 2-5 second pause where the UI thread blocks and then the progressBar disappears, which I've set to occur after the for loop in the onTaskCompleted (the third and final operation) terminates. The data then shows up.
The other two operations take place in the UI thread. Both for in onPostExecuted and onTaskCompleted run on the UI Thread and are tight loops. The UI thread is blocked in your loops. So while you are inside those tight loops no matter how many thousand times you mingle with any UI component: setprogress, settext, etc.... It will not update until the for loop ends, your routine finishes, and the system takes control again of the UI thread.
What you can do is, as it looks like there's a big number of rows, to add them in chunks then update the progress. This will give some air. Take a look at the following prototype
Handler handler=new Handler();
interface AddRowListener {
public void onRowsAdded();
}
private void addRowChunk(final int startRow, final int totalRows, final AddRowListener listener) {
for (int i=startRow; i<startRow+CHUNK_SIZE; i++) {
if (i>=totalRows) {
// we have finished! Just call the listener
listener.onRowsAdded();
return;
}
addView....
}
// After adding some rows, we end here, and schedule a call to this function again
// to continue. The 25ms delay is optional, but it will give some air to Android for sure
handler.postDelayed(new Runnable() {
addRowChunk(startRow+CHUNK_SIZE, totalRows, listener);
}, 25);
}
private void addRows(AddRowListener listener) {
TableLayout itemTable = (TableLayout) findViewById(R.id.itemTable);
// we start the process, it will create row chunks and call the listener when done
addRowChunk (0, itemTable.getChildCount(), listener);
}
So to add the rows you now can do:
addRows (new AddRowListener() {
public void onRowsAdded() {
// the rows have been added.
}
});
By the way, what's your row size? it has to be huge !
PD_ You have to select a CHUNK_SIZE. Just experiment with values until the UI is snappy. I'd say 40-50 is OK, but it's just a wild guess and depends on the phone hardware.
Don't set your progress.setMax() inside doInBackground(), do it inside onPreExecute() instead. You should not modify the UI thread(Main Thread) from a worker/background thread, and there is exactly where doInBackground() runs. onPreExecute(), onProgressUpdate(), and onPostExecute() run on the UI Thread.
Why you are not using a thread to update the progress bar. This approach is perfect to update the progress........but if you want to set manually then first set the max for progress bar just call below method in your onPreExecute and then onPostExecute
progressBar.setProgress(value);
Where Value should be half of the max when you are calling from onPreExecute and then cent percent from onPostExecute......but I recommend you to use a thread to update the correct progress.
Do not use publishProgress in onPostExecute. Just call incrementProgressBy.

AsyncTask Android in For Structure

I want to implement something like the following on Android:
for(int i=0; i<num; i++){
//a,b.. are changing
aTask = new myAsyncTask(a,b..);
aTask.execute();
//Code to wait for myAsyncTask to finish
}
The problem is how can I wait for myAsyncTask to finish before starting the new iteration. One possible solution I thought is to put a Handler inside to wait for some seconds. For example:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 5000);
But this is not right even if it is working, because you have to put a standard time to wait for myAsyncTask. And it isn't sure if myAsyncTask finishes early or late because the a,b.. parameters change in every iteration.
Another solution I thought is to ask every time in a loop the object aTask to get the Status of myAsyncTask and check if it is FINISHED. For example:
while(!aTask.getStatus().equalsTo(AsyncTask.Status.FINISHED)){
}
But this isn't working because myAsyncTask is always RUNNING.
Can somebody help me?
//Code to wait for myAsyncTask to finish
If you wait there, you would freeze the UI. What is the point of another thread if you plan on waiting?
My guess what you need is to make use of the optional parameters in the execute(Params...) method. You can put your 'a','b' or what ever those objects are and how many you put doesn't matter. This will allow your task to execute all of them and have better contorl.
protected Long doInBackground(Objects... objs){
for(int i = 1; i < objs.length; i++){
// Do Work
}
}
In Android you must not stay in the UI Thread and wait for something. This includes waiting for AsyncTasks that run in the background. If you would wait in the calling Thread, it would block the user and would freeze your device.
You must separate the code into two pieces.
First start the AsyncTasks:
for(int i=0; i<num; i++){
//a,b.. are changing
aTask = new myAsyncTask(a,b..);
aTask.execute();
// dont wait here. It would freeze the UI Thread
}
Second run code when Task has finished just overwrite the onPostExecute() method in MyAsyncTask.
Then Android can do its work while the AsyncTasks run.
a simple suggestion, depending on what your for loop is actually doing, is to use the loop to create a 'queue' of items you want processed. then, fire off an asynctask with the first object in the queue, and upon completion of that task, fire off the next object in the queue until the length of your queue is zero
The easiest way is to create a method from where you call asynTask.execute() and call that method from onPostExecute().
public class ParentClass extends Activity
{
int asyncCalls = 0;
......
public void callAsyncTaskAgain()
{
aTask = new myAsyncTask(a,b..);
aTask.execute();
asyncCalls++;
}
public class AnotherClass extends AsyncTask
{
protected Void onPostExecute(Void result)
{
....
if(asyncCalls < SOME_NUMBER)
callAsyncTaskAgain();
}
}
}
Hope this helps

Implementing a while loop in android

I can't understand the implementation of a while loop in android.
Whenever I implement a while loop inside the onCreate() bundle, (code shown below)
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView=(TextView)findViewById(R.id.TextView);
while (testByte == 0)
updateAuto();
}
nothing boots up, and the program enters a "hanging" state after a while and I can't understand why. Testbyte is as follows:
byte testByte == 0;
and updateAuto() is supposed to update the code per 1 second and display inside the textView portion. I've been using setText inside updateAuto() as shown below and everything works fine, but once i implement the while loop all i see is a black screen and then an option to force close after a few seconds due to it "not responding".
TextView.setText(updateWords);
I've changed it to a button format (meaning i have to click on the button to update itself for now), but i want it to update itself instead of manually clicking it.
Am i implementing the while loop in a wrong way?
I've also tried calling the while loop in a seperate function but it still gives me the black screen of nothingness.
I've been reading something about a Handler service... what does it do? Can the Handler service update my TextView in a safer or memory efficient way?
Many thanks if anyone would give some pointers on what i should do on this.
Brace yourself. And try to follow closely, this will be invaluable as a dev.
While loops really should only be implemented in a separate Thread. A separate thread is like a second process running in your app. The reason why it force closed is because you ran the loop in the UI thread, making the UI unable to do anything except for going through that loop. You have to place that loop into the second Thread so the UI Thread can be free to run. When threading, you can't update the GUI unless you are in the UI Thread. Here is how it would be done in this case.
First, you create a Runnable, which will contain the code that loops in it's run method. In that Runnable, you will have to make a second Runnable that posts to the UI thread. For example:
TextView myTextView = (TextView) findViewById(R.id.myTextView); //grab your tv
Runnable myRunnable = new Runnable() {
#Override
public void run() {
while (testByte == 0) {
Thread.sleep(1000); // Waits for 1 second (1000 milliseconds)
String updateWords = updateAuto(); // make updateAuto() return a string
myTextView.post(new Runnable() {
#Override
public void run() {
myTextView.setText(updateWords);
});
}
}
};
Next just create your thread using the Runnable and start it.
Thread myThread = new Thread(myRunnable);
myThread.start();
You should now see your app looping with no force closes.
You can create a new Thread for a while loop.
This code will create a new thread to wait for a boolean value to change its state.
private volatile boolean isClickable = false;
new Thread() {
#Override
public void run() {
super.run();
while (!isClickable) {
// boolean is still false, thread is still running
}
// do your stuff here after the loop is finished
}
}.start();

How to load one image at a time in the Android UI thread

I currently have a UI that uses an AsyncTask class to make a web service call. This call gets several pictures and stores them in a HashMap. The UI is then notified and the UI is created with these images. However, this sometimes takes as long as 10 - 15 seconds, which is annoying. Is there a way to populate the UI one picture at a time with a background service so that the user starts to see images faster than they currently are?
Thanks.
here is a rough example of how to do this:
public Void doInBackground(String... urls) {
int len = urls.length;
for(int i = 0; i < len; ++i) {
Bitmap b = downloadImage(urls[i]);
publishProgress(new Object[] {b, i});
}
return null;
}
public void onProgressUpdate(Object... values) {
Bitmap b = (Bitmap)values[0];
Integer bitmapIndex = (Integer)values[1];
//replace the image at location "bitmapIndex" in your collection of images with "b"
//update your adapter via notifyDataSetChanged
}
Use the AsyncTask's onProgressUpdate method to publish progress inside doInBackground. This method(onProgressUpdate) runs on the UI thread.
I don't know if you're aware of this, but just in case, an AsyncTask has the onProgressUpdate function which you could use to perform operations on the UI thread, before the AsyncTask ends with calling onPostExecute. From the doInBackground method just call publishProgress with relevant arguments.

Categories

Resources