I’m developing a simple alarm clock app and I use a OnSharedPreferenceChangeListener to display changes while setting up an alarm. Code included below. The problem: the app crashes at this line:
//SharedPreferences etPrefs=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
And I can’t find the reason. Strange is that the whole thing worked at the college but when I open the project at home using the same version of Eclipse it crashes at the mentioned line o_0 Any suggestions?
public class NewAlarm extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
private Button btnCancel, btnSave;
private TimePicker tp;
private TextView txtDate;
private DigitalClock dc;
private SimpleDateFormat sdf = new SimpleDateFormat("EEEE, dd MMM");
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.new_alarm_prefs);
setContentView(R.layout.new_alarm);
setupRefs();
tp.setIs24HourView(true);
dc.setBackgroundColor(Color.parseColor("#14B909"));
dc.setTextColor(Color.parseColor("#FFFFFF"));
txtDate.setText("Today is: " + sdf.format(new Date()));
}
public void setupRefs() {
btnCancel = (Button) findViewById(R.id.btnCancelNewAlarm);
txtDate = (TextView) findViewById(R.id.txtDate);
tp = (TimePicker) findViewById(R.id.tp);
dc = (DigitalClock) findViewById(R.id.dc);
}
@Override
protected void onResume() {
super.onResume();
getPrefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(getPrefs, "Repeat_PREFS");
onSharedPreferenceChanged(getPrefs, "et_PREFS");
btnCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
btnSave = (Button) findViewById(R.id.btnSaveNewAlarm);
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
getPrefs.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences getPrefs, String key) {
Preference pref = findPreference(key);
if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry().toString());
}
if (pref instanceof EditTextPreference) {
EditTextPreference etPref = (EditTextPreference) pref;
pref.setSummary(etPref.getText());
}
}
}
Declare this globally,
And inside your onCreate() do this,
This is because your Context will be initiated in
onCreate()only and before that it would be null and that is what is causing you the problem.