Getting a CastClassException error in the onListItemClick method of a ListFragment-Collection of common programming errors
I have a class that extends ListFragment and I’m using the Support Library. In the class’s onListItemClick method, I have this line:
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) ((Fragment) getListAdapter().getItem(position)).getString(1);
DetailFrag frag = (DetailFrag) getFragmentManager().findFragmentById(R.id.frag_stitchdetail);
if (frag != null && frag.isInLayout()) {
frag.setText(item);
}
}
where position is a parameter that is passed to the onListItemClick method. Its value at runtime is 0 for the example app I’m building, as there’s only one item in the list. This line throws the following error:
java.lang.CastClassException: android.content.ContentResolver$CursorWrapperInner cannot be cast to java.lang.String
I’ve Googled this and searched on stackoverflow, but I don’t see anything that will give me a hint as to why I can’t cast this to a String. Anyone know? Thanks!
My ContentProvider code for the query:
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(STITCHTABLE_BASEPATH);
int uriType = sURIMatcher.match(uri);
switch (uriType)
{
case STITCHES_ID:
queryBuilder.appendWhere(SQLData.KEY_ROWID + "=" + uri.getLastPathSegment());
break;
case STITCHES:
//no filter
break;
default:
throw new IllegalArgumentException("Unknown URI");
}
Cursor cursor = queryBuilder.query(mDB.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
The code in my ListFragment for the CursorLoader:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Intent myData = getActivity().getIntent();
Bundle info = myData.getExtras();
String[] dataColumns = { "stitchname" };
int[] viewIDs = { R.id.stitchlist1 };
mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.stitchlist, null, dataColumns, viewIDs, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, info, (LoaderCallbacks) this);
}
@Override
public Loader onCreateLoader(int id, Bundle args) {
String selection = "stitchlevel=?";
String[] selectionArgs = new String[] {args.getString("Level")};
return (Loader) new CursorLoader(getActivity(), STITCHES_URI,
PROJECTION, selection, selectionArgs, null);
}
@Override
public void onLoadFinished(Loader loader, Cursor cursor) {
mAdapter.swapCursor((android.database.Cursor) cursor);
}