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

在我的代码中 response1 是我在线程上方声明的变量,我想将字符串“res”分配给“response1”,但它给了我封闭的类型错误。任何人都可以帮助我解决这个问题。

4

3 回答 3

4

另一种方法是将 Thread 之外的 String 变量声明为final Array,这样您就可以在线程内分配所需的值。

  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-04T22:12:56.290 回答
0

我认为您可以从线程内发送实例变量的值。就像是

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-04T22:03:05.203 回答
0

您不能从匿名类内部为变量分配某些内容,因为final如果在这种情况下使用 java 需要变量(以防止不必要的副作用)。

您可以尝试通过为变量创建包装器来解决此问题:

class StringWrapper {
    public String innerString;
}

final StringWrapper wrapper = new StringWrapper();

new Thread(new Runnable() {
    public void run() {
         ...
         wrapper.innerString = res;
    }
});
于 2012-04-04T21:45:04.123 回答