Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread not terminating correctly, I think

public String newUser = "false";
public double lat = 0.0, lon = 0.0;

I have the following function in my android app (called when a Button is clicked) which starts a thread:

public void SignUpFunction(View view) {
    assignValues();
    String filledAll = checkIfFilled();
    if (filledAll.equals("true")) {
    Log.d("LIFECYCLE", "calling thread..");

    //my thread
    new validateThread().start();

    Log.d("After thread start","This log call does not occur");

    if (newUser.equals("true")) {
        Toast.makeText(this, "Please wait as we obtain your location", Toast.LENGTH_SHORT).show();
        getMyLocationFunction();
        } else {
            return;
        }
    }
}

validateThread:

class validateThread extends Thread {
    public void run() {
        Log.d("LIFECYCLE", "validateThread entered...");
        try {
                        newUser = "true";
                        Log.d("validateThread", "Validated and found new user");
        } catch (Exception e) {
            Log.d("validateThread", "Exception in validateThread: " + e.getMessage());
        }
    }
}

The thread runs correctly...but after the last line, it does not go back to its point of start. I don't understand why this is happening because I've used threads before and they all work correctly.

I know I can just give the getMyLocation function inside the thread but I really need it this way.

I've searched for similar questions but none helped.. What am I doing wrong here? Thanks in advance.

like image 590
aashima Avatar asked Jun 24 '26 19:06

aashima


1 Answers

It's a race. SignUpFunction should wait until validateThread decides whether or not to set newUser = "true". Even with the race your code may work sometimes, but that is by accident.

like image 168
user1110743 Avatar answered Jul 01 '26 10:07

user1110743



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!