shruti
shruti

Reputation: 117

I am getting this strange error on in onAttach(Context)

In onAttach function eclipse shows error stating

The method onAttach(Activity) in the type Fragment is not applicable for the arguments (Context)

although it is clearly Context type variable passed

import android.content.Context;

public class MyListFragment extends Fragment{
    private OnItemSelectedListener listener;

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_rsslist_overview,
            container, false);
        Button button = (Button) view.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            updateDetail("fake");
          }
        });
        return view;
      }

      public interface OnItemSelectedListener {
        public void onRssItemSelected(String link);
      }

      @Override
      public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnItemSelectedListener) {
          listener = (OnItemSelectedListener) context;
        } else {
          throw new ClassCastException(context.toString()
              + " must implemenet MyListFragment.OnItemSelectedListener");
        }
      }

      @Override
      public void onDetach() {
        super.onDetach();
        listener = null;
      }

      // may also be triggered from the Activity
      public void updateDetail(String uri) {
        // create a string just for testing
        String newTime = String.valueOf(System.currentTimeMillis());

        // inform the Activity about the change based
        // interface defintion
        listener.onRssItemSelected(newTime);
      }
}

Upvotes: 3

Views: 406

Answers (2)

Kristiyan Varbanov
Kristiyan Varbanov

Reputation: 2509

I had same problem can you try to pass Activity in your onAtach method like this:

   @Override
      public void onAttach(Activity activity) {
        super.onAttach(context);
        if (context instanceof OnItemSelectedListener) {
          listener = (OnItemSelectedListener) activity;
        } else {
          throw new ClassCastException(context.toString()
              + " must implemenet MyListFragment.OnItemSelectedListener");
        }
      }

and tell me if it works or not. Hope to help!

Upvotes: 1

Rohit5k2
Rohit5k2

Reputation: 18112

If you are using API < 23 then

public void onAttach(Context context) {

should be

public void onAttach(Activity context) {

See official docs

Note:

onAttach(Context context) was added in api 23. See this

Upvotes: 2

Related Questions