leopoodle
leopoodle

Reputation: 2482

Android Fragment: "cannot cast android.app.Fragment"

My fragment class has the correct import from support v4. However, I get the error "cannot cast android.app.Fragment" when I use getFragmentManager in MainActivity. Somehow, getFragmentManager is using the old fragment, not the supprt.v4.app.Fragment. Do you know what method I should use?

package example.hfad.fragments_chapter7;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class WorkoutDetailFragment extends Fragment {
    private long workoutId;

    public WorkoutDetailFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_workout_detail, container, false);
    }

    public void setWorkout(long id){
        this.workoutId = id;
    }
}

My MainActicity is this: **the last line

gerFragmentManager().findFragmentById

complains that I cannot cast android.app.Fragment to my custom fragment class defined above.**

package example.hfad.fragments_chapter7;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WorkoutDetailFragment frag = (WorkoutDetailFragment) getFragmentManager().findFragmentById(R.id.detail_frag);
    frag.setWorkout(1);

    }
}

Upvotes: 5

Views: 14545

Answers (3)

Wilmer
Wilmer

Reputation: 512

I changed

//import android.app.Fragment;

by

import androidx.fragment.app.Fragment;

Upvotes: 1

Shiva s
Shiva s

Reputation: 897

Try this code:

import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WorkoutDetailFragment frag = (WorkoutDetailFragment) getSupportFragmentManager().findFragmentById(R.id.detail_frag);
        frag.setWorkout(1);
    }
}

Upvotes: 3

Rohit5k2
Rohit5k2

Reputation: 18112

Your fragment is inherited from android.support.v4.app.Fragment so you should use getSupportFragmentManager(). If is it inherited from android.app.Fragment then only you can use getFragmentManager()

Replace

WorkoutDetailFragment frag = (WorkoutDetailFragment) getFragmentManager().findFragmentById(R.id.detail_frag);

with

WorkoutDetailFragment frag = (WorkoutDetailFragment) getSupportFragmentManager().findFragmentById(R.id.detail_frag);

Upvotes: 14

Related Questions