Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

    }
}
like image 632
leopoodle Avatar asked Dec 04 '22 00:12

leopoodle


2 Answers

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);
like image 74
Rohit5k2 Avatar answered Jan 20 '23 07:01

Rohit5k2


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);
    }
}
like image 24
Shiva s Avatar answered Jan 20 '23 05:01

Shiva s