2012-03-29 42 views
-1

我寫了這樣的方法......如何在完全不同的方法中使用局部方法變量?

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

請求(響應)是如何變量? – 2012-03-29 05:06:54

+0

你的snip中的'request(response)' - 它不是一個變量。什麼是你試圖實現的各種選項存在,但可能有線程安全等問題。 – radimpe 2012-03-29 05:08:16

+0

正如aij和radimpe指出的那樣,請求(響應)不是一個變量。無論如何,如果你想從其他方法引用一個變量,那麼你將該變量作爲一個實例變量,就像在任何塊之外的類中聲明它。 – 2012-03-29 05:11:26

回答

1

增加響應和請求變量的範圍,我的意思是在類級別聲明這些變量而不是方法級別。

+1

代碼片斷 - 它表明OP想要在多線程環境中運行它。不會將類似'request'的東西保存到類變量中會導致問題? – radimpe 2012-03-29 05:25:57

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 = new A(); 
//now you can call a.request or a.response 

但請記住,變量訪問說明符應允許您執行此操作。

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和preferrably在私有實例變量使用存取,而而不是直接進行保護和分配,但您希望得到的一點是,您需要一個實例變量來保存方法調用request(response)的值。

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. 
    } 
}