Assignment for internship interview using Android Studio. The task was to pass an array from one activity to another. In the first activity, have a button which loads the second activity and displays a list of the array data passed from the first.
Here is how I approached this problem:
- Create a string array called
interns
and populate it with data. - Create a new activity called
ListActivity
which will display the array data in a ListView. - Make a ListView in
activity_list.xml
and give it the idinternList
. - Pass array
interns
fromMainActivity
toListActivity
using an IntentintentListActivity
and theputExtra()
intent method. - Add attribute
android:onClick="openListActivity"
to ButtonView onMainActivity
so that the methodopenListActivity
runs and opensListActivity
when tapped. - In
ListActivity
, collectinterns
array fromMainActivity
withgetIntent().getStringArrayExtra("interns")
and store in local string array calledinterns
. - Next, find a ListView to attach
interns
data to by usingfindViewById()
method and setting tointernListView
. - Create array adapter
internsAdapter
to map array data to ListView. - Set
internsAdapter
tointernListView
withsetAdapter()
method.
Originally, when I first made/committed this code, it did not display the array data in the ListActivity
. In fact, the application crashed upon running it.
After submission, I found that this was because I used the incorrect method to extract the data passed from the MainActivity
.
Instead of using getStringArrayExtra("interns")
, I mistakenly used getStringArrayListExtra("interns")
, which caused a null-object
error in Android Studio.
This was not compatible with the putExtra()
method on the intentListActivity
intent I created in MainActivity
. Another option might
have been to use putStringArrayListExtra()
on the intent instead to pass the data to ListActivity
.