NullPointerException when using a fragment to get values from another class : <p>I am a beginner in android and having some problem in handling NullPointerException.I need to pass the magnetometer reading values in an array from one class to a fragment.
Here is the magnetometer class:</p>

<pre><code>public class Magnetometer implements SensorEventListener {
private Sensor mag;
private SensorManager magman;
private boolean magAvailable;
private float[] magValue;

public  Magnetometer(MagFragment context){
    magman=(SensorManager)context.getActivity().getSystemService(Context.SENSOR_SERVICE);
    magAvailable=magman.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)!=null;
    if(isMagAvailable()){
        magValue=new float[3];
        mag=magman.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        magman.registerListener(this,mag,SensorManager.SENSOR_DELAY_NORMAL);
    }
}

@Override
public void onSensorChanged(SensorEvent event) {
    for(int i=0;i&lt;3;i++)
        magValue[i]=event.values[i];
}
public float[] getLastReading(){
    return this.magValue;
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {

}
public boolean isMagAvailable(){
    return this.magAvailable;
}
public void unregister(){
    if(isMagAvailable())
        magman.unregisterListener(this,mag);
}
}
</code></pre>

<p>Here is the fragment:</p>

<pre><code>ublic class MagFragment extends Fragment {
private Magnetometer mag;
private TextView x,y,z;
private float[] magValues;
public MagFragment() {
    // Required empty public constructor
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //returning our layout file
    //change R.layout.yourlayoutfilename for each of your fragments
    View rootView = inflater.inflate(R.layout.fragment_mag, container, false);
    x=(TextView) rootView.findViewById(R.id.mx);
    y=(TextView) rootView.findViewById(R.id.my);
    z=(TextView) rootView.findViewById(R.id.mz);
    magValues=new float[3];
    getData(this);
    return rootView;
}


@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //you can set the title for your toolbar here for different fragments different titles
    getActivity().setTitle("Magnetometer");
}
public void getData(MagFragment context)
{
    magValues=mag.getLastReading();
    displayData(magValues);
}
public void displayData(float [] magV)
{
    x.setText(String.valueOf(magV[0]));
    y.setText(String.valueOf(magV[1]));
    z.setText(String.valueOf(magV[2]));
}
}
</code></pre>

<p>I understand,that the function returns some NULL values.
The error I get is "Attempt to invoke virtual method 'float[] com.example.ark.ark.Sensors.Magnetometer.getLastReading()' on a null object reference"</p>
