Fragment causing NPE upon starting service with on

2019-09-17 10:01发布

问题:

I have an activity which displays fragments dynamically. The default fragment has a switch that, if enabled, starts a service.

What's happening however, is that whenever I toggle the switch I get a nullpointerexception. The errorlog is here

What can I do to fix this? Should I perhaps throw the code for the button over onto the main activity instead of the fragment? This wouldn't be a problem, but I'd really like to have it in the fragment.

My Fragment:

public class DefaultScreen extends Fragment {

SharedPreferences.Editor edit_status;
private SharedPreferences service_status;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    /** Inflating the layout for this fragment **/
    View v = inflater.inflate(R.layout.fragment_default, null);

    Switch sEnable = (Switch) v.findViewById(R.id.switch_service);
    Switch sRoot = (Switch) v.findViewById(R.id.switch_root);

    sEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {

            Toast.makeText(getActivity(), "Service Switch State = " +isChecked, Toast.LENGTH_SHORT).show();
            Context ctx = (Context)DefaultScreen.this.getActivity();
            if(isChecked)
            {
            edit_status.putBoolean("ServiceMode", true).commit();
            ctx.startService(new Intent(getActivity(), SensorService.class));

            } else {
                edit_status.putBoolean("ServiceMode", false).commit();
                ctx.stopService(new Intent(getActivity(), SensorService.class));
            }
        }
    });

    sRoot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            Toast.makeText(getActivity(), "Root Switch State = " +isChecked, Toast.LENGTH_SHORT).show();
        }
    });

    return v;
}

private boolean proximityService(Context context) {
    @SuppressWarnings("rawtypes")
    Iterator iterator = ((ActivityManager) context.getSystemService("activity")).getRunningServices(Integer.MAX_VALUE).iterator();


    while (iterator.hasNext()) {
        ActivityManager.RunningServiceInfo runningServiceInfo = (ActivityManager.RunningServiceInfo) iterator
                .next();
        if (SensorService.class.getName().equals(
                runningServiceInfo.service.getClassName())) {
            return true;
        }
    }

    return false;
}

}

回答1:

Not initialized your: edit_status

before using it in:

edit_status.putBoolean("ServiceMode", true).commit();