Vikrant Arora Vikrant Arora - 6 months ago 30
Android Question

Can you please guide me what's wrong in the code?

The line in MainActivity.java in which WorkoutDetailFragment is casted shows error that it cannot be done. Please tell me why it isn't working. I copied the code from a book.

MainActivity

package gangster.workout;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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


Workout.Java

package gangster.workout;


public class Workout {
private String name;
private String description;

public static final Workout[] workouts = {
new Workout("The Limb Loosener" , " Pta nhi kya ksgdrna hai isme") ,
new Workout("The Timb Loosener" , " Pta nhi kya asdfasasfasasdkrna hai isme") ,
new Workout("The Pimb Loosener" , " Pta nhi kyaasf krna hai isme") ,
new Workout("The Zimb Loosener" , " Pta nhi kyasfasa krna hai isme") ,
};
private Workout(String name , String description){
this.name = name;
this.description = description;
}

public String getDescription(){
return description;
}
public String getName(){
return name;
}
public String toString(){
return this.name;
}
}


WorkoutDetailFragment.java

package gangster.workout;


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


public class WorkoutDetailFragment extends Fragment {
private long workoutId;

public void setWorkout(long id) {

this.workoutId = id;
}

@Override
public void onStart() {
super.onStart();
View view = getView();
if (view != null) {
TextView title = (TextView) view.findViewById(R.id.textTitle);
Workout workout = Workout.workouts[(int) workoutId];
title.setText(workout.getName());
TextView description = (TextView) view.findViewById(R.id.textDescription);
description.setText(workout.getDescription());
}

}

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

}

Answer

use getSupportFragmentManager() instead of getFragmentManager()