Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

Check if a thread is running from the "mother" class

In my Main Activity, I have a Thread that is doing alot of stuff, including adding some records to a database. In my second activity, which inherit from the Main Activity, I want to do a query to my database. But I need to check if the first thread in the Main Activity is finished, what I've done so far is:

public class History extends Main {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 

    if(!(MainThread.isAlive())) {
            getFromDatabase();
    }
}
}

This is my getFromDatabase() method

    pd = ProgressDialog.show(this, "Please Wait",
                "Getting cases from database", false);

    Thread t = new Thread(this);
    t.start();

which will call this run method:

@Override
public void run() {

    ArrayList<Case> c = db1.getAllCases();
    Message msg = handler.obtainMessage();
    msg.obj = c;
    handler.sendMessage(msg);
}

private Handler handler = new Handler() {

    @SuppressWarnings("unchecked")
    @Override
    public void handleMessage(Message m) {
        pd.dismiss();
        list = (ArrayList<Case>) m.obj;
        tempList = getCaseNumberToTempList(list);
        tempCaseList = createTempList(list);

        lv.setAdapter(new CustomAdapter(History.this, list));
        lv.setTextFilterEnabled(true);
    }
};

But if I do so, the following line of code will crash my application, it will give a NullPointerException:

if(!(MainThread.isAlive())) {
            getFromDatabase();
    }

How can I be sure that that the first thread is finished with all the work before I query the database from my history activity?

Upvotes: 0

Views: 331

Answers (2)

koljaTM
koljaTM

Reputation: 10262

How about simply using a semaphore variable that you modify from the thread once it has reached a certain state?

Upvotes: 1

Adam Monos
Adam Monos

Reputation: 4307

You can make the Thread in the getFromDatabase() method a static class level variable, write a static get method for it in your Activity, and check for isAlive() in your child Activity.

Upvotes: 1

Related Questions