Reputation: 599
I need to store a load of content which I retrieved from http. I have created a method to do the retrieving of contents. But I need to store it in an array which is declared outside. I am having troubles doing return value.
My question is:
1)Where do I place my return statement?
2)How do I store the contents from searchInfo into the array mStrings[]?
This is my code.
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()};
}
Upvotes: 0
Views: 1185
Reputation: 23181
You have a few options:
You can declare mStrings[] as an instance variable (put protected String[] mStrings;
right after the line where you declare the Adapter) and then initialize it in your onCreate method (mStrings = new String[SIZE];
) where SIZE is the size for your array. After that, your searchInfo method can just add items to mString and doesn't have to return anything (since a instance variable is visible to all members fo the class).
You can change searchInfo's signature so it returns String[]
and then declare a temp string array inside that method, add the items to it and return it to the caller ( mStrings = searchInfo();
)
In both the cases above, it assumes you know the length of the array (so you can initialize it). You could use an ArrayList instead of a String array since those can grow dynamically. You can then convert the arrayList to an array with:
yourArrayList.toArray(mStrings);
as long as you've initialize mStrings to something non-null (i.e. mStrings = new String[1];
)
Upvotes: 2