essbek
essbek

Reputation: 59

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();
}
}

Upvotes: 2

Views: 658

Answers (2)

Matt Taylor
Matt Taylor

Reputation: 3408

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

Upvotes: 1

Milos Cuculovic
Milos Cuculovic

Reputation: 20223

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.

Upvotes: 0

Related Questions