使用片段从另一个类获取值时的NullPointerException

时间:2017-08-10 17:04:06

标签: java android android-fragments nullpointerexception magnetometer

我是android的初学者,在处理NullPointerException时遇到一些问题。我需要将磁力计读取数组中的值从一个类传递到一个片段。 这是磁力计类:

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

这是片段:

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

据我所知,该函数返回一些NULL值。 我得到的错误是&#34;尝试调用虚方法&#39; float [] com.example.ark.ark.Sensors.Magnetometer.getLastReading()&#39;在null对象引用&#34;

1 个答案:

答案 0 :(得分:0)

您从未在MagFragment中创建磁力计实例。

例如:Magnetometer mag = new Magnetometer(this);