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);
    }
}
                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);
                        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);
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With