using variables in threading

Go To StackoverFlow.com

1

    new Thread(new Runnable() {
        public void run() {
            String response = null;
            //String res = null;
            try {
                response = CustomHttpClient.executeHttpPost("http://abc.org/fypcps/furqan.php");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                //Toast.makeText(context, e.toString(), 0).show();
                //Log.i("furqan", "ya ALLAH madad");
            }  //Enetr Your remote PHP,ASP, Servlet file link  
            String res = response.toString();  
            // res = res.trim();  
            //res= res.replaceAll("\\s+","");  
            //error.setText(res);  
            //if(res.equals("1"))  
                //Log.i("furqan1", res);
            //else  
                //Log.i("furqan2", "no string is captured");
            response1 = res;
        }
      }).start();

here in my code response1 is a variable that i have declared above the thread and i want to assign a string "res" to "response1" but it is giving me enclosed type error.can any body help me out with this problem.

2012-04-04 21:41
by Furqan Ahmed
Only final variables can be accessed inside anonymous inner classes. Which will create a problem here, since you're trying to assign it--but I'm guessing, because you don't show the rest of the code, instead including a bunch of unrelated commented-out stuff - Dave Newton 2012-04-04 21:45
Paste the relevant code. response1 cannot be accessed because it is not a final variable. And if it were a final variable, it could not be re-assigned. Also please make the title more relevant (e.g. the exact error message) - NoName 2012-04-04 21:45
Okay, -1 for not improving this question. Just more unsearchable junk on SO - NoName 2012-04-04 22:04


4

Another method is to declare your String variable outside of the Thread as a final Array, so you can assign the value you want inside the thread.

  final String [] answer = new String[1];      
  answer[0]="init value";
  System.out.println(answer[0]); // return "init value"
  new Thread(new Runnable() {
      public void run() {

          answer[0]="value assigned from the thread";
      }
    }).start();

  try {
    Thread.currentThread().sleep(1000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  System.out.println(answer[0]); //return "value assigned from the thread"
2012-04-04 22:12
by imanis_tn


0

You cannot assign something to a variable from inside an anonymous class because java requires variables to be final if used in this scenario (to prevent unwanted side-effects).

You could try to solve this by creating a wrapper for your variable:

class StringWrapper {
    public String innerString;
}

final StringWrapper wrapper = new StringWrapper();

new Thread(new Runnable() {
    public void run() {
         ...
         wrapper.innerString = res;
    }
});
2012-04-04 21:45
by Tudor
I think you can call a method that has side effects, though, can't you? (e.g. a setResponse1(String str) method - jpm 2012-04-04 21:47
@jpm: Yes, that is allowed, and could be an alternative solution - Tudor 2012-04-04 21:48
make the innerString as static is not a butter solution, because you can avoid the instantiation of the StringWrapper every time you want to assign values - imanis_tn 2012-04-04 22:31


0

I think you can sent the value of an instance variable from within a thread. Something like

package pro.Project;

import android.app.Activity;
import android.os.Bundle;

public class ProjectActivity extends Activity {
    /** Called when the activity is first created. */
    private String foo = "";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String bar = ""; // Non-final local variable

        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                foo ="bar"; // This would work
                bar ="baz"; // This WOULDN'T. As 'bar' is a non-final local variable
            }
        });
        t.start();
    }
}
2012-04-04 22:03
by Thomas Antony
While this is a solution to the problem, I don't think that adding more global variables is a good idea. You are practically making a method use state that other methods should not see - Tudor 2012-04-04 22:08
Are you sure that is work? because i don't see foo as a final variable - imanis_tn 2012-04-04 22:27
I did try compiling it and running it in the Android emulator and it worked out fine. Even put a breakpoint at that line and checked if the value was being set properly.

@Tudor I must say I didn't think much about convention when I typed that up. But aren't private instance variables supposed to be accessed by any and all instance methods of the class?

Of course, what jpm suggested above is also a solution - Thomas Antony 2012-04-05 08:25

Ads