Tasks.await() is not returning when expected - android

I am trying to save data into a Firebase RealtimeDatabase.
The process of saving is fine and works just well, but I was curious about an idea I had: To force the .setValue operation into a synchronous structure. I know, that that way isn't the best one, but I wanted to try it regardless of that fact.
So I came up with this code:
Thread t1 = new Thread(){
public void run(){
try {
Tasks.await(databaseReference.child("someChild").setValue(someObject));
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("finished");
}
In theory, that code snippet is intended to first set the value in the Database, then wait for the completion of that (through the Tasks.await()), and then print out **after that* the line "finished".
I wrapped the Tasks.await()-command in a second thread because when I don't, I get an exception which says something like "Tasks.await() must not be called in the main application thread".
But when I run the whole thing, it just gets stuck at t1.join();.
When I delete the t1.join();-statement, everything works just fine, but the second Thread (t1) isn't finished before the "finished"-output is there. I know why this is like that, but I am nontheless interested in a solution to that problem.

Related

Android live server connection status

Wondering if its possible to monitor constantly some wifi connection to a server (some ip and port) and display the status of the connection, that is if the server is accessible/responsive or not.
By displaying the status i mean updating some textview displaying either "server up" or "server down".
(something similar to the wifi icon next to the battery indication at the top right..)
the answer is to make a thread class, which will constantly call (with a while loop) an asynctask. The asynctask will (try to) connect to the mysql server. the connection will be successful or not and accordingly a textview or something will be updated in the UIthread (using runOnUiThread)
an example of the code for the thread:
class servlookthread extends Thread {
#Override
public void run() {
while (keeplookingserver){
lookforserver lserv = new lookforserver(); // this is the asynctask thread
try {lserv.execute().get();} catch (ExecutionException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} //! .get() it waits until the asynctask finishes
try {Thread.sleep(4000);} catch (InterruptedException e) {e.printStackTrace();} // some delay, 4 seconds
}
return;
}
}
the keeplookingserver is a boolean, "global" variable used to control the execution of the thread.
hope this helps someone! although i think its not elegant, its working for me

How the flow of code in while loop going in android?

I am new in Android (Java) coding . I have a small game program downloaded. In that to terminate the thread , have the code
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
thread.setRunning(false);
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
retry = false;
}
}
Here the code author says if catch the exception , the code will go to try part not to the statement retry = false;
I could not believe that. please advise the flow is correct.
Please advise
Thanks
Anes
The loop will be run once. No matter if an Exception is thrown since retry will always be set to false after the first run. If you wanted the loop to continue until no Exception is thrown, you could place the retry = false; directly after the thread.join(); in the try block so it's only being called when you don't get to the catch block.

How do i add a delay to program before running selection query to avoid bind value being null?

I keep getting an illegal argument exception when running my app. However, this happens prior to the Toast messages coming up and that's why I think I need a delay.
Prior to adding on the DatabaseHelper class, my app was running and the proper value was coming up on both Toast messages, the one in the MainActivity and the one showing the intent value passed in the DisplayResult activity.
I'm not sure what to do at this point.
Just do a thread sleep in a runnable.
int timeYouWantToSleep = 60000;
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(timeYouWantToSleep);
//do your work here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
If this doesn't work, you know it's not a delay that you need.

What may prevent the UI in android to be updated on time?

I'm developing an Android app that has to update it's UI depending on receiving and processing some server responses, I'm using runOnUiThread for that. I have like five activities in that app, all is working very well but one requires me to relaunch the Activity(like going to another one and then returning to it) or interacting with it in order to that update takes place, and that is the way i'm using with all the Activities including the infected one:
runOnUiThread(new Runnable() {
public void run() {
try {
response_received(response);
} catch (Exception e) {
e.printStackTrace(); // never catch any Exceptions
}
}
});
private static void response_received(JSONObject response) throws Exception{
try {
int volume_setted = response.getInt(volume);
Normal_Activity.volume_value.setText(String.valueOf(volume_setted)); // the Volume TextView updated efficiently
Infected_Activity.volume_value.setText(String.valueOf(volume_setted)); // has the problem mentioned above
} catch (JSONException ex) {
}
}
I'm pretty sure the problem is not in the TextView as all the Activity UI has this problem but i just posted an example.
Do not directly set values in a Activity from another Activity. If you want to pass data to Another activity always use Intents. check the below link
pass data from intent to an other intent
If you want to start another activity and get result back check the below link
http://developer.android.com/training/basics/intents/result.html

Android thread sometimes does not start

I must use Thread in an Android project. Sometimes, it works corectly, however sometimes does not; it does not start (does not call SendToServer() method)or it starts but return to another function suddenly (return updated; line)before the thread does not finish.
Note: affected value is bigger than 0, it gives condition and it goes to if statement.
Here is the my code sample;
public static Boolean MyUpdateFunction(MyObject myobject){
Boolean updated=false;
//Code for updating local database
int affected= SqliteDb.update(....);
if(affected>0)
{
//Send updated data to server
//For this I must use Thread(I can't use AsyncThread)
updated=true;
SendToServer();
}
return updated;
}
public static void SendToServer()
{
try{
;
Thread th=new Thread(new Runnable() {
public void run() {
try {
//Create data and send it to server
//.......
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
th.start();
th.join();
}
catch(SQLException e)
{
Toast.makeText(myContext,"ERROR: "+e.getMessage(), Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Other people are correct in that an AsyncTask is the way forward, but the direct problem due to what you're experiencing is this (and as such, I would recommend reading up on how Threading works):
When you start the thread, it begins a new process. The UI thread (which is generally where the majority of your code is) continues. So your code will fire the thread with SendToServer(), and then by definition will immediately return updated, as the UI thread immediately goes to the next line.
What you need is a callback from your Thread, which is handled in the onPostExecute() method of an AsyncTask. There's a good tutorial on how to use them and what they do here
Edit:
I've just seen from a comment above that you can't use Asynctasks, fair enough, but you still need a callback/event fired from your Thread to return any results
Instead of using threads and your variables (updated and affected), you can use AsyncTasks: see: http://developer.android.com/reference/android/os/AsyncTask.html
With AsyncTask, you have some methods which are doing exactly what you want:
onPreExecute
doInBackground
onPostExecute
So, what you can do is to check your condition in onPreExecute, then do your SendToServer in the doInBackground and onPostExecute do what you need.

Categories

Resources