我有一个像这样写的方法......
public void getRequest(String Url) {
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
Toast.makeText(MenuUtama.this, request(response) ,Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
我需要能够在另一种方法中访问本地变量request
,以便我可以调用request.response
。我怎么能从一个完全不同的方法访问这个本地方法?
答案 0 :(得分:1)
增加响应和请求变量的范围,我的意思是在类级别声明这些变量而不是方法级别。
答案 1 :(得分:0)
你不能在任何函数中调用任何变量声明为局部变量。你可以用以下方式做到这一点
public class A{
HttpGet request;
HttpResponse response;
void methodA(){
request = //........
response = //...........
}
void methodB{
//here you can refer to request and response as they are the instance variables of the class.
}
}
如果你想访问课外的那些,你必须创建一个 A类的对象,然后调用如下
A a = new A();
//now you can call a.request or a.response
但请记住,变量访问说明符应该允许你这样做。
答案 2 :(得分:0)
我认为你正在寻找的东西是这样的:
protected Object myRequest;
public void getRequest(String Url) {
runOnUiThread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
myRequest = request(response);
Toast.makeText(MenuUtama.this, myRequest, Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
显然将Object
更改为任何类request(response)
,重命名myRequest
,并且最好在私有实例变量上使用访问器,而不是直接对其进行保护和分配,但是希望你需要一个实例变量来保存方法调用request(response)
的值。
答案 3 :(得分:0)
您应该在类级别范围内声明您的response
变量。这是你的代码。
public class YourClass{
//Declare your request varible in a class-level scope
//so it can be accessed by any method
HttpGet request;
public void getRequest(String Url) {
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
response = client.execute(request);
Toast.makeText(MenuUtama.this, request(response) ,Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public void otherMthod(){
System.out.println(request); //request variable is accessible in this scope.
}
}