I'm building a ListActivity with a list of activities (each item on the list is an activity of my app). When one of the items in the list is clicked I want to get it's info. It's mostly done, however I'm getting an error when trying to retrieve the item data onclick.
This is what I'm doing:
private class ActivityItem {
private CharSequence title;
private Class activityClass; // I didn't limit it to Activities because I might use it for Fragments
public ActivityItem(int titleResId, Class activityClass) {
this.title = getResources().getString(titleResId);
this.activityClass = activityClass;
}
@Override
public String toString() {
return title.toString();
}
}
private static ActivityItem[] mItems;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_items_not_added);
// Instantiate the list of samples.
ActivityItem[] mItems = new ActivityItem[]{
new ActivityItem(R.string.dialer, Example1.class),
new ActivityItem(R.string.clock, Example2.class),
};
setListAdapter(new ArrayAdapter<ActivityItem>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mItems));
}
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
Log.d("Title:", mItems[position].toString()); // This returns error
}
Log:
03-15 17:45:30.302 18134-18134/com.example.android.launcher E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.android.launcher, PID: 18134
java.lang.NullPointerException
at com.example.android.launcher.ItemsNotAdded.onListItemClick(ItemsNotAdded.java:92)
What am I doing wrong?
Item
is additionally, locally declared in onCreate()
- you can't access this instance. Just use
mItems = new ActivityItem[]{
new ActivityItem(R.string.dialer, Dialer.class),
new ActivityItem(R.string.clock, Clock.class),
new ActivityItem(R.string.flashlight, Flashlight.class),
new ActivityItem(R.string.contact_list, ContactList.class),
};
in onCreate()
and the static ActivityItem[] mItems
will be assigned instead. Otherwise it will be null
.
ps as I see you use an ListActivity
. In this case you could call getListView().getAdapter() getItem(int position)
in onListItemClick
as well. So no static member is required. Check ListActivities
API.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.