java.lang.ClassCastException: Activity cannot be cast to Adapter while trying to convert Activity to Fragment
Thanks to what Mike M. and Reza.Abedini said among answers and comments I was able to understand what was happening and to overcome this issue.
The problem was in the Adapter
that was prepared to get Context
from Activity
so I had to convert the parameter to Fragment
and it ended up working like this:
public NotesAdapter(List<Note> list, RoomMarkdownActivity fragment) {
this.layoutInflater = LayoutInflater.from(fragment.getActivity());
this.list = list;
this.fragment = fragment;
this.onNoteItemClick = fragment;
}
And the Fragment
like:
public class RoomMarkdownActivity extends Fragment implements NotesAdapter.OnNoteItemClick {
public static RoomMarkdownActivity newInstance() {
return new RoomMarkdownActivity();
}
RecyclerView recyclerView;
TextView textViewMsg;
NoteDatabase noteDatabase;
List<Note> notes;
NotesAdapter notesAdapter;
int pos;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.room_markdown_activity, container, false);
textViewMsg = view.findViewById(R.id.textview_empty);
FloatingActionButton fab = view.findViewById(R.id.fab);
fab.setOnClickListener(listener);
recyclerView = view.findViewById(R.id.recycler_view);
initializeViews();
displayList();
return view;
}
private void displayList() {
noteDatabase = NoteDatabase.getInstance(getActivity());
new RetrieveTask(this).execute();
}
private static class RetrieveTask extends AsyncTask<Void, Void, List<Note>> {
private WeakReference<RoomMarkdownActivity> activityReference;
RetrieveTask(RoomMarkdownActivity context) {
activityReference = new WeakReference<>(context);
}
@Override
protected List<Note> doInBackground(Void... voids) {
if (activityReference.get() != null)
return activityReference.get().noteDatabase.getNoteDao().getNotes();
else
return null;
}
@Override
protected void onPostExecute(List<Note> notes) {
if (notes != null && notes.size() > 0) {
activityReference.get().notes.clear();
activityReference.get().notes.addAll(notes);
activityReference.get().textViewMsg.setVisibility(View.GONE);
activityReference.get().notesAdapter.notifyDataSetChanged();
}
}
}
public void initializeViews() {
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
notes = new ArrayList<>();
notesAdapter = new NotesAdapter(notes, this);
recyclerView.setAdapter(notesAdapter);
}
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(getActivity(), RoomMarkdownAddNoteActivity.class), 100);
}
};
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode > 0) {
if (resultCode == 1) {
notes.add((Note) data.getSerializableExtra("note"));
} else if (resultCode == 2) {
notes.set(pos, (Note) data.getSerializableExtra("note"));
}
listVisibility();
}
}
@Override
public void onNoteClick(final int pos) {
new AlertDialog.Builder(getActivity())
.setTitle("Select:")
.setItems(new String[]{"Read", "Update", "Delete"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0:
RoomMarkdownActivity.this.pos = pos;
startActivityForResult(
new Intent(getActivity(),
RoomMarkdownViewNoteActivity.class).putExtra(
"note", notes.get(pos)), 100);
break;
case 1:
RoomMarkdownActivity.this.pos = pos;
startActivityForResult(
new Intent(getActivity(),
RoomMarkdownAddNoteActivity.class).putExtra(
"note", notes.get(pos)), 100);
break;
case 2:
noteDatabase.getNoteDao().deleteNote(notes.get(pos));
notes.remove(pos);
listVisibility();
break;
}
}
}).show();
}
public void listVisibility() {
int emptyMsgVisibility = View.GONE;
if (notes.size() == 0) {
if (textViewMsg.getVisibility() == View.GONE)
emptyMsgVisibility = View.VISIBLE;
}
textViewMsg.setVisibility(emptyMsgVisibility);
notesAdapter.notifyDataSetChanged();
}
@Override
public void onDestroy() {
noteDatabase.cleanUp();
super.onDestroy();
}
}
Thank you very much for the help and I hope this question/answer helps others as well!
ClassCastException: MainActivity cannot be cast to Listener
One thing is the context
and another is the WifiScanner.Listener
. Your ScanCollector
needs both so pass both of them:
public ScanCollector(Context context, WifiScanner.Listener listener) {
if (context == null)
throw new NullPointerException();
this.context = context;
this.listener = listener
}
And when you create it:
sc = new ScanCollector(getActivity(), this);
Android Activity to Fragment: Replacing this with getActivity() throws error: ClassCastException
It's because you're expecting TaskRowListener
inside your TaskAdapter
class:
class TaskAdapter(context: Context, taskList: MutableList<Task>) : BaseAdapter() {
..
// here you're expecting a TaskRowListener
var _rowListener: TaskRowListener = context as TaskRowListener
.........
}
but you're activity isn't a TaskRowListener
. So, you need to modify your activity to implement TaskRowListener
with something like this:
class ToDoActivity : FragmentActivity(), TaskRowListener {
...
}
Although I think that you should not use activity at all to keep the Adapter handled only by the TodoFragment
and keep using:
_adapter = TaskAdapter(this, _taskList!!)
java.lang.ClassCastException: com.example.readdoang.ui.login_regist_activity.LoginRegistActivity cannot be cast to com
in your class RegisterFragment,override the onCreateView(), in this method you can pass your view(fragment) to presenter like this :
presenter = RegisterPresenter(this)
and your presenter should like this :
class RegisterPresenter(internal val view: RegisterView.View) : RegisterView.Presenter
SimpleCursorAdapter ClassCastException in fragment
myAdapter = (MyAdapter) new
SimpleCursorAdapter(getActivity(),R.layout.carerrow , cursor, from,
to);
Just replace SimpleCursorAdapter
with MyAdapter
...
Also, you could use support v4 library to get loaders on pre-honeycomb devices.
Related Topics
Android: How to Open a Specific Folder Via Intent and Show Its Content in a File Browser
How to Retrieve Current Fragment in Navhostfragment
App Crashes (Sometimes) With Fatal Signal 11 (Sigsegv), Code 1
How to Transfer from One Fragment to Another in Android
Illegalstateexception: Link Does Not Have a Navcontroller Set
Reactnative Metro Bundler Not Starting Automatically
How to Get the Timezone Offset in Gmt(Like Gmt+7:00) from Android Device
Android Scrollview Not Scrolling Down After Keyboard Opens
Resolving Problems With Android Studio Freezing Constantly
How to Stop Refreshing Recyclerview Data Scroll to Top Position Android Everytime
How to Auto Fit Recyclerview Items to the Width of Screen Android
Apk Installation Failed: [Install_Failed_Verification_Failure]
How to Add a Newline to a Textview in Android
Android Prevent Back Button from Closing the App
How to Load New Values of Json After Every 10 Seconds
How to Use Sharedpreferences in Android to Store, Fetch and Edit Values
Can't Create Handler Inside Thread That Has Not Called Looper.Prepare()