Android Java how to stop the code from execute like break point - java

My code retrieving on AsyncTask data from cloud database.
I have notice, if I am putting break point(while debugging), My code runs ok, the data received and then my code manipulate that data.
If I am not using any break point my array is null, the code did not wait for the data to arrive.
I have tried,
Thread.sleep(timeInMills);
and
SystemClock.sleep(timeInMills);
but this did not help, It seems to stop the entire Thread.
Is there a way for me to stop the code the same way break point does for a second or two.
Again this does not effect my UI Thread as this run in AsyncTask.

i have faced a similar situation
if you send the result array to an adapter or a function make it execute at the end of onPostExecute method , as before that your data Array would be empty

Related

How do I make a android AsyncTask loading spinner while doInBackgroung()

I got an AsyncTask for URL connection. Now I want to have a loading spinner everytime I do the URL connection. I display the loading spinner in onPreExecute() and dismiss it in onPostExecute.
I tested this with an endless while loop in doInBackgroung().
The big problem is the GUI is freezing and the loading spinner is not shown.
In my opinion the reason is URLconnection.execute().get(). But I need the get() because the activity need the result to working with it.
My question is now: What is the best way to do this to achieve my wishes? (By the way it is not important to get a solution with an "AsyncTask solution" because there are maybe better solutions and AsyncTask will be deprecated with SDK version 30)
Thank you very much and stay healthy!
As you said AsyncTask will be deprecated.
So it is better to go for an alternative.
Since you mentioned you are not relying on AsyncTask, I will present to you another approach.
Let me introduce you to coroutines and convince you that they will solve your problem and "get the job done".
When I got to know about coroutines, this video was one of the first example that has demonstrated to me the potential of using coroutines in my app. At that point I was still using 100% Java, probably like you are right now.
The good part is: getting started with Kotlin is really easy! Not only you can call Kotlin functions from Java Code, you can also call Java functions from Kotlin code.
To "do something in background" in Kotlin, all you need to do is to launch a coroutine (on a background thread).
Do you have a ViewModel to fetch your data? If it is an option to transfer this file to kotlin, then starting (and scoping) a coroutine becomes as simple as this.
For fragments or activitities you could use other copes as well. However, using the global scope is usually discouraged.
Executing coroutines is as simple as that:
class MyViewModel: ViewModel() {
fun loadDataInBackgroundAndShowSpinner {
viewModelScope.launch {
// Coroutine that will be canceled when the ViewModel is cleared.
// start your spinning
// do all the heave data work on a background thread
doInBackground()
// end your spinning here
}
}
suspend fun doInBackground(inputURL: String) {
withContext(Dispatchers.IO) {
// Execute all your data fetching here
...
// Assign your data to your viewModel variables, post it to a LiveData object, etc.
}
}
}
You do not need any loops in the main thread or anything. By using withContext on a background thread you can achieve main-safety.
Within a launched coroutine, everything (by default) gets executed in order.
Still you will not block the Main Thread. How did you achieve that?
The key here is that your doInBackground function has the suspend keyword. Therefore your loadDataInBackgroundAndShowSpinner on the main thread will "suspend" your doInBackground function and the main thread is able to do whatever you want (i.e. nothing freezes). Then, once your doInBackground is finished, it will resume execution and you can just dismiss your spinner again on the main thread.
Kotlin coroutines make it so much easier to do something in the background and I really want to encourage you to give it a try! It will definitely solve your problem and I can not think of a more easy way.
Google also tried to make it as easy as possible to get you started when coming from Java.

Update TextView without Freezing Application

I'm reading Sensor Data from Device Sensors(Multiple Sensors) and call a Method to show the data I received from sensors to the designed TextView.
The method I'm calling to update TextView:
private void UpdateDataStream(String _Entry,Boolean isAppend)
{
if(isAppend)
ViewHolder.append("\n("+sensorName+")"+_Entry);
else
ViewHolder.setText("("+sensorName+")"+_Entry);
}
Method called from SensorEventListener's , onSensorChanged Event.
What I couldn't figure out is how to prevent freeze while updating TextView; since sensor data update is intensive(considering it is from multiple sensors simultaneously) updating TextView cause Application to freeze or crash. I don't need to "print" every data I received, like It is enough for me to print for every 1-2 second, lost data can be ignored.
Is there any approach/patern or built-in structure to achieve this ?
(I'm new to programming in Java&Android, yet I'm familiar with multiprogramming, parallel programming concepts, yet I couldn't figure out how to apply them in this environment)
This is fastest solution:
https://github.com/ReactiveX/RxJava
http://reactivex.io/documentation/operators/debounce.html
Or you can:
create stack (for example)
write sensors data stream to stack from thread#1
in another infinite loop thread#2 read last data from stack every N time (don't forget to synchronize them)
clean the stack
write last data to TextView (don't forget to set text in ui thread: textView.post( () -> textView.setText("safe call") );

Execute the method after previous method finishes

I am making an android app in which I am fetching data from internet and storing it in a ArrayList with custom adapter. Fetching data takes time and in that time next function runs on its own. I only want the next function to run when data is completely fetched. What can I do? I think it has to do something with threads kindly explain what threads are and how can we use them?
Let's say there are 2 functions
Function A
Function B
I only want the function B to run when function A has completed its task. is there anyway to do that?
There are lots of resources available online where you can obtain information on Threads in Java.
I highly recommend the official Java Documentation.
This Introduction isn't half bad either.
As for obtaining information in one method and then waiting until it is done to run the next, as #cHao said, just call the methods sequentially like this
A();
B();
Unless you already have multiple threads set up in your code, this should work just fine.

Android application freezing while showing some long text

In my android application in java, I am doing an http async request then I want to print the result in a TextView that is in a ScrollView.
This work fine when the result to print is short. But it can be very long and then the application is freezing for ~3-5 second.
I know this is because to much work is done on the main thread but is there a way to set the text of a TextView on a separeted thread ?
To illustrate this is my code in the onResponse of the httpRequest :
tView2.setText(requestName);
tView3.setText(message1);
tView4.setText(messag2);
tView4.setText(resultBody);
tView5.setText(message3);
If i just remove the line
tView4.setText(resultBody);
(where resultBody contains a long String) The UI does not freeze any more, and the other message are print almost instantly.
But when I let it the UI is freezing even before the print of the previous message so I can't even set a message of information preventing the user that can take some while (what I tried in my code, it's why there is 2 setText on the tView4)..
What I want is the simpliest solution to manage that. So an easy way to print a message of information to prevent the user would be good.
Thank you.

continuous message receiving asynctask

I am making a chat application.The server will send me an update whenever a friend sends me a message.As a result i need a continuous listener from my android client.I have used asynchronous task and in the post execute method, i have called the asynchronous task again.Thus listening continuously.But this is giving me weird errors.
If you could help me i would be really grateful.If you think i should implement the continuous listener in some other way please do suggest me.Thanks.
Proper method should be like when you get connected to server, you should keep listening in a loop. See my answer here
and modify it as needed.
What about using http://quickblox.com/developers/Android library? I am just curious, if it would not be easier :) .
Otherwise I thought about making while cycle in doInBackground() method, instead of calling asyncTask all over again.
Something like -
While(programExit) {
//your code
}

Categories

Resources