Alaoui Ghita
Alaoui Ghita

Reputation: 1879

java thread synchronization : i get "undefined value"

The following bloc of android code tries to get a return value from a javascript function, and then assign it to a class variable, and after i use this class variable when instantiating another class;

This is my code :

      //class variables
                String innerElementNum = "0";
                private final Object lock = new Object();
                MyAdapter myAdapter;

            synchronized (lock) {
                try {
                    webView.loadUrl("javascript:inner()");
                    while (responseFromJS.equals(""))
                        lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                (!responseFromJS.equals("empty"))
                    innerElementNum = responseFromJS;
                }
                responseFromJS = "";
            }

        myAdapter = new MyAdapter(EditorActivity.this);

And in MyAdapter class, i use the variable "innerElementNum", like that :

public class MyAdapter extends BaseAdapter {

       Context context;

       int itemsNum = Integer.parseInt(innerElementNum); 
       String[] itemsArray = new String[itemsNum];


       MyAdapter(Context c){
           context = c;
           if (itemsNum > 0) {
           for (int i=0 ; i<itemsNum ; i++) {
               int j = i+1; 
               itemsArray[i] = j+"";
           }
           }
       }
       ....... etc
}

My problem is the synchronization : when instantiating MyAdapter class, "innerElementNum" variable have "undefined" value, i mean, when I instantiate the class, the variable has not yet had the right value.

any help is welcome. Thanks in advance

Upvotes: 0

Views: 286

Answers (1)

John Vint
John Vint

Reputation: 40256

Well "undefined" is Javascript specific. You are almost certainly parsing a json that looks like

{
   elementNum: "undefined"
}

This doesn't seem to have anything to do with concurrency.

When you say

"undefined" value, i mean, when I instantiate the class, the variable has not yet had the right value.

String num = "undefined" is technically assigned in Java. I would think you need to fix that Javascript that is building this json.

Also as a side note:

You shouldn't be testing String equivalence by the == operator. This tests reference equivalence and not content. You should use .equals

Upvotes: 1

Related Questions