Nicholas Muir Nicholas Muir - 1 year ago 109
Android Question

Appcompat activity required as argument for function used in fragment

I am using an external library in my app. The first argument used in the example is "this". Which refers to an appcompat activity. However I am using this in a fragment shich obviously doesn't extend appcompat activity.

This is the library:

I am not sure whether there is anything I can do. Can I extend the fragment to something compatible (right now it just extends fragment).

Below is a screenshot of the issue:

enter image description here


This is what I extend in my MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

The Fragment that is called innside Main activity is extended like this:

public class AddAlarmFragment extends Fragment {

And I am trying to create the data source in the oncreate method of the fragment like this:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add_alarm, container, false);

WeekdaysDataSource wds = new WeekdaysDataSource(,

new WeekdaysDataSource.Callback() {
public void onWeekdaysItemClicked(int attachId,WeekdaysDataItem item) {
// Do something if today is selected?
Calendar calendar = Calendar.getInstance();
Toast.makeText(getActivity(),"Carpe diem",Toast.LENGTH_SHORT).show();

public void onWeekdaysSelected(int attachId,ArrayList<WeekdaysDataItem> items) {
//Filter on the attached id if there is multiple weekdays data sources
// Do something on week 4?


Thanks in advance for your help.

Answer Source

Have you tried casting getActivity()?

((AppCompatActivity) getActivity(), 

Read the Android API, you can see AppCompatActivity does extend FragmentActivity and getActivity() does return a FragmentActivity, not an AppCompatActivity, as expected by your library.

I do find it odd that a AppCompatActivity is even the defined parameter rather than a Context

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download