[英]Pass value from public method to private array
我需要存储从http检索到的大量内容。 我已经创建了一个检索内容的方法。 但是我需要将它存储在一个在外面声明的数组中。 做返回值我遇到了麻烦。
我的问题是:
1)我在哪里发表退货声明?
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()};
}
你有几个选择:
您可以将mStrings []声明为实例变量(put protected String[] mStrings;
在声明适配器的行之后),然后在onCreate方法中初始化它( mStrings = new String[SIZE];
)其中SIZE是数组的大小。 之后,您的searchInfo方法可以只添加项目到mString,而不必返回任何内容(因为实例变量对类的所有成员都是可见的)。
您可以更改searchInfo的签名,以便返回String[]
,然后在该方法中声明一个临时字符串数组,将项添加到它并将其返回给调用者( mStrings = searchInfo();
)
在上述两种情况中,它假定您知道数组的长度(因此您可以初始化它)。 您可以使用ArrayList而不是String数组,因为它们可以动态增长。 然后,您可以使用以下命令将arrayList转换为数组:
yourArrayList.toArray(mStrings);
只要你将mStrings初始化为非null值(即mStrings = new String[1];
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.