I want TextViews
to display the sensors readings in a Fragment
. When trying to initialize the SensorManager
the getSystemServices
is undefined in the Fragment
, eclipse says.Why and how to fix it.
Fragment
public class FragSensors extends Fragment {
private TextView accXTv, accYTv, accZTv;
private SensorManager sensorManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.frag_sensors, container, false);
accXTv = (TextView) v.findViewById(R.id.accXValue);
accYTv = (TextView) v.findViewById(R.id.accYValue);
accZTv = (TextView) v.findViewById(R.id.accZValue);
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
private final SensorEventListener mSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
}
the getSystemService () method that provides access to system services comes from Context. An Activity extends Context, a Fragment does not. Hence, you first need to get a reference to the Activity in which the Fragment is contained and then magically retrieve the system service you want.
It's cause the metod getSystemService belongs to the class Context, so you have to run it on a context but you're running it from an activity.
You can get the activity that contains the fragment with getActivity (). Therefore getActivity ().getApplicationContext () would work. getActivity ().findViewById (int) would also work.
Just one more method call:
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
Why that one extra method call?
the getSystemService()
method that provides access to system services comes from Context
. An Activity
extends Context
, a Fragment
does not. Hence, you first need to get a reference to the Activity
in which the Fragment
is contained and then magically retrieve the system service you want.
Use:
getActivity().getSystemService(name)
On Kotlin use:
this.sensorManager = activity!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensorManager = (SensorManager) getActivity().getSystemService(Context.NAMEOF_SERVICE);
Fragments cannot directly call System Services , You have to use Activity with which these Fragment is Attached
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