Reputation: 1
I am new to Android development. I am unable to pass an ArrayList from a class to my main activity. The following code snippet retrieves the elements from an RSS feed and stores them to an ArrayList. I would like to access this ArrayList in my activity in order to display the titles. I am working from the Android tutorial on ListViews.
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("http://sports.espn.go.com/espn/rss/news");
Document doc = builder.parse(u.openStream());
NodeList nodes = doc.getElementsByTagName("item");
ArrayList<String> titles = new ArrayList<String>();
for(int i=0;i<nodes.getLength();i++)
{
Element element = (Element)nodes.item(i);
titles.add(getElementValue(element,"title"));
}
Bundle value = new Bundle();
value.putStringArrayList("titles", titles);
The above code works and stores the titles into an ArrayList. However, I am unable to access the list by using a Bundle in the following code from the Activity.
public class ExampleActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, titles));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
String[] titles = Bundle.getStringArray("titles");
}
Upvotes: 0
Views: 756
Reputation: 499
Did you consider to store your array in singleton class? I usually implement singleton pattern in my apps to share data between activities. This is not answer on your question but consider it as suggestion about handling data between more activities.
Upvotes: 0
Reputation: 9908
You seem to be calling getStringArray
statically in the receiving activity. Try using
Bundle extras = getIntent().getExtras();
to get the bundle instance that contains the values you want to pass in.
You also are putting an ArrayList into the bundle and getting an array out. Try matching your types, so use
ArrayList<String> titles = extras.getStringArrayList("titles");
Upvotes: 1