2011-11-27 30 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

相关问题