我有一个动态显示片段的活动。默认片段有一个开关,如果启用,则启动服务。
然而,正在发生的事情是,每当我切换开关时,我都会得到一个nullpointerexception。错误日志为here我该怎么做才能解决这个问题?我是否应该将按钮的代码抛出到主活动而不是片段?这不会是一个问题,但我真的很想把它放在片段中。
我的片段:
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;
}
}
答案 0 :(得分:0)
未初始化您的:edit_status
在使用它之前:
edit_status.putBoolean("ServiceMode", true).commit();