2011-11-27 70 views
0

我需要存儲從http檢索到的內容負載。我創建了一個方法來執行內容檢索。但我需要將它存儲在一個聲明爲外部的數組中。我有麻煩做返回值。從公共方法向私有數組傳遞值

我的問題是:

1)我在哪裏把我return語句?

2)如何將searchInfo中的內容存儲到數組mStrings []中?

這是我的代碼。

public class MainActivity extends Activity 
{ 
ListView list; 
Adapter adapter; 

private static final String targetURL ="http://www.google.com/images"; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    list=(ListView)findViewById(R.id.list); 
    adapter=new Adapter(this, mStrings); 
    list.setAdapter(adapter); 
    } 

    public String searchInfo() 
{ 
    try { 
     // Get the URL from text box and make the URL object 

     URL url = new URL(targetURL); 

     // Make the connection 
     URLConnection conn = url.openConnection(); 
     BufferedReader reader = new BufferedReader(
     new InputStreamReader(conn.getInputStream())); 

     // Read the contents line by line (assume it is text), 
     // storing it all into one string 
     String content =""; 
     String line = reader.readLine(); 
     Pattern sChar = Pattern.compile("&.*?;"); 
     Matcher msChar = sChar.matcher(content); 
     while (msChar.find()) content = msChar.replaceAll(""); 

     while (line != null) { 

      if(line.contains("../../")) 
      {     
       content += xyz; 
       line = reader.readLine();     
      } 

      else if (line.contains("../../") == false) 
      { 
       line = reader.readLine(); 
      } 

     } 

     // Close the reader 
     reader.close(); 

    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 

} 

private String[] mStrings={searchImage()}; 

} 

回答

2

您有幾種選擇:

  1. 你可以聲明mStrings []作爲一個實例變量(把protected String[] mStrings;行之後,你聲明適配器),然後在你的onCreate初始化方法(mStrings = new String[SIZE];)其中SIZE是您陣列的大小。之後,您的searchInfo方法可以將項添加到mString中,並且不必返回任何內容(因爲實例變量對類的所有成員均可見)。

  2. 您可以更改searchInfo的簽名,以便它返回String[]然後聲明方法內的臨時字符串數組,添加項目,並將其返回給調用者(mStrings = searchInfo();

在這兩種情況下,上面,它假定你知道數組的長度(所以你可以初始化它)。您可以使用ArrayList而不是String數組,因爲它們可以動態增長。只要你已經初始化mStrings的東西非空(即mStrings = new String[1];

+0

感謝

yourArrayList.toArray(mStrings); 

:您可以ArrayList然後轉換成一個陣列。我想我堅持使用字符串數組。因爲它來自我得到的一個例子。我如何將字符串存儲到字符串數組中?我有一個String []數組;必須將String xyz存儲到數組中。並返回值的錯誤。但是,如果我想更改爲ArrayList,其他類文件中的代碼是否會有任何更改? – Hend