javaandroid-activitycallbackmetaio

How to extend Activity in a Java class already extended


I'm developing an AR Android App using Metaio. I need to show some data when a real object has been tracked. To do this I register a callback, this is the best way that I have found.

Unfortunately to use correctly getFragmentManager(), I need to import Activity properties but i can't extend the class (already extended).

I think that getContext is the right way, but I do not know how to implement it.

This is the callback register in main activity:

metaioSDK.registerCallback(new ProvaTracking());

This is the Tracking class:

package com.metaio.Example;

import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;

import com.metaio.sdk.jni.IMetaioSDKCallback;
import com.metaio.sdk.jni.TrackingValues;
import com.metaio.sdk.jni.TrackingValuesVector;

public class ProvaTracking extends IMetaioSDKCallback {

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onTrackingEvent(TrackingValuesVector trackingValuesVector) {
        super.onTrackingEvent(trackingValuesVector);

        for (int i=0; i<trackingValuesVector.size(); i++)
        {
            final TrackingValues v = trackingValuesVector.get(i);
            if (v.isTrackingState())
            {
                TestFragment trendsFragment = new TestFragment();
                getFragmentManager().beginTransaction().add(android.R.id.content, trendsFragment).commit();

                Log.d("Alessandro", "Works!!");

            }
        }

    }

}

Solution

  • Add a constructor that takes in Context (Note that you want the Activity context, not the application context)

    so you would change your class to be:

    public class ProvaTracking extends IMetaioSDKCallback {
        private Contect mCtx;    
    
        public ProvaTracking(Context context) {
            mCtx = context;
        }
    
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        public void onTrackingEvent(TrackingValuesVector trackingValuesVector) {
            super.onTrackingEvent(trackingValuesVector);
    
            for (int i=0; i<trackingValuesVector.size(); i++)
            {
                final TrackingValues v = trackingValuesVector.get(i);
                if (v.isTrackingState())
                {
                    TestFragment trendsFragment = new TestFragment();
    
                    if (mCtx instanceof Activity)
                        ((Activity) mCtx).getFragmentManager().beginTransaction().add(android.R.id.content, trendsFragment).commit();
    
                    Log.d("Alessandro", "Works!!");
    
                }
            }
    
        }
    
    }
    

    then call it with metaioSDK.registerCallback(new ProvaTracking(getContext()));