-4

I found this Call an activity method from a fragment but it didn't help. I am getting typecasting error. New to fragments. Please help.

This is my fragment where i want to call that method on click of a button

   public class Fragment1 extends Fragment {
    View view;
    public CardView stepEnableUi, enablewaterui, stepCountingUi, countingwaterUI;


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

    public void initialization() {
        final Button enablestep = view.findViewById ( R.id.stepsenable );
        final Button enablewater = view.findViewById ( R.id.waterenable );
        stepEnableUi = view.findViewById ( R.id.stepenableui );
        enablewaterui = view.findViewById ( R.id.waterenableui );
        stepCountingUi = view.findViewById ( R.id.stepcountingUI );
        countingwaterUI = view.findViewById ( R.id.watercountingUI );

        enablestep.setOnClickListener ( new View.OnClickListener ( ) {
            @Override
            public void onClick(View v) {
               ((StepCounter)getActivity ()).connectGoogle ( );
            }
        } );

This is my method in my activity

public class StepCounter extends AppCompatActivity implements OnDataPointListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_OAUTH = 1;
private static final String AUTH_PENDING = "auth_state_pending";
private boolean authInProgress = false;
Button historyView;
private GoogleApiClient mApiClient;
TextView stepsonbar, steps, min, km, cal;
private ResultCallback<Status> mSubscribeResultCallback;
private ResultCallback<Status> mCancelSubscriptionResultCallback;
private ResultCallback<ListSubscriptionsResult> mListSubscriptionsResultCallback;
FragmentManager fm = getSupportFragmentManager();
FitChart fitChart;



  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_step_counter);
        initialize();

    if (savedInstanceState != null) {
        authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
    }
    initCallbacks();

    mApiClient = new GoogleApiClient.Builder(this)
            .addApi(Fitness.SENSORS_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
            .addApi(Fitness.RECORDING_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .enableAutoManage(this, 0, this)
            .build();

}
public void initialize(){
    steps=findViewById(R.id.steps);
    stepsonbar=findViewById(R.id.stepsonbar);
    min = findViewById(R.id.min);
    km = findViewById(R.id.km);
    cal = findViewById(R.id.cal);
    fitChart=findViewById ( R.id.fitchart );
    fitChart.setMinValue ( 0f );
    fitChart.setMaxValue ( 50000f );
    historyView=findViewById ( R.id.buttonweekdata );
    historyView.setOnClickListener ( new View.OnClickListener ( ) {
        @Override
        public void onClick(View v) {
            Intent i=new Intent ( StepCounter.this,HistoryWalking.class );
            startActivity ( i );
        }
    } );
}

@Override
protected void onStart() {
    super.onStart();
}

public void connectGoogle(){
    mApiClient.connect();
}
@Override
public void onActivityResult(int requestCode,int resultCode, Intent data) {
    if( requestCode == REQUEST_OAUTH ) {

        authInProgress = false;
        if( resultCode == RESULT_OK ) {

            if( !mApiClient.isConnecting() && !mApiClient.isConnected() ) {
                mApiClient.connect();
                Fragment1 fragment = (Fragment1) fm.findFragmentById(R.id.homescreen);
                fragment.showStepCounter();

            }
        } else if( resultCode == RESULT_CANCELED ) {
            Log.e( "GoogleFit", "RESULT_CANCELED" );
        }
    } else {
        Log.e("GoogleFit", "requestCode NOT request_oauth");
    }
}

Here is my logcat

03-14 13:45:49.259 29247-29247/com.satyajit.priceiq3 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.satyajit.priceiq3, PID: 29247
                                                                       java.lang.ClassCastException: com.satyajit.priceiq3.MainActivity cannot be cast to com.satyajit.priceiq3.Activities.StepCounter
                                                                           at com.satyajit.priceiq3.Fragments.Fragment1$1.onClick(Fragment1.java:46)
                                                                           at android.view.View.performClick(View.java:6303)
                                                                           at android.view.View$PerformClick.run(View.java:24828)
                                                                           at android.os.Handler.handleCallback(Handler.java:789)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                           at android.os.Looper.loop(Looper.java:164)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6809)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
03-14 13:45:49.261 29247-29247/com.satyajit.priceiq3 D/AppTracker: App Event: crash

2 Answers2

0
  1. First You need to commit your fragment in Activity with Tag.

    getSupportFragmentManager()
                .beginTransaction()   
                .replace(frame, fragment, "YOUR FRAGMENT NAME")
                .commit(); 
    
  2. Now you will able to find your fragment by Tag.

    Fragment fragment = getSupportFragmentManager().findFragmentByTag("YOUR FRAGMENT NAME");
    
  3. Cast your fragment

    if(fragment instanceof YourFragment) {
    
       YoutFragment yourFragment = (YoutFragment)fragment;
    
       yourFragemtn.yourMethod();
    
    }
    
Mike Holt
  • 4,292
  • 1
  • 15
  • 23
Aziz
  • 1
  • 1
  • 1
    Can you clarify a little bit? it will be more helpful. I am currently using view pager for showing my fragments. – satyajit das Mar 14 '18 at 09:12
  • Ok if you use viewpager the you can add ViewPager.SimpleOnPageChangeListener for tracking current position. – Aziz Mar 14 '18 at 17:39
0

Since StepCounter class is not the parent Activity for the fragment Fragment1,try the following

StepCounter mStepCounter=new StepCounter();
mStepCounter.connectGoogle();

Make sure to initialize the values inside those method properly

kIN
  • 14
  • 3