Исходное сообщение:
В следующем примере:
Как сохранить и получить дату в SharedPreferences
Что я должен искать, чтобы заменить ... с?
Save:
SharedPreferences prefs = ...;
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("time", date.getTime());
editor.commit()
Я пытаюсь использовать что-то вроде:
SharedPreferences.Editor editor = getSharedPreferences(DATE_PREF, MODE_PRIVATE);
но я получаю сообщение об ошибке, указывающее, что DATE_PREF не может быть преобразован в переменную.
MY SOURCE:
//get the current date
Date date = new Date(System.currentTimeMillis());
// convert the date to milliseconds
long millis = date.getTime();
// save the date to shared preferences
SharedPreferences prefs = millis ;
SharedPreferences.Editor editor = getSharedPreferences(DATE_PREF, MODE_PRIVATE);
editor.putLong("time", date.getTime());
editor.commit();
Обновление после первого ответа: (помощь все еще нужна)
После удаления строк:
// SharedPreferences prefs = millis;
// SharedPreferences.Editor editor = PreferenceManager
// .getDefaultSharedPreferences(getApplicationContext())
Я получаю две ошибки о том, что «редактор не может быть разрешен» по адресу:
editor.putLong("time", date.getTime());
editor.commit();
из-за того, что я удалил строки, которые ссылались на редактор, мой вопрос: будут ли мои настройки по-прежнему сохранены, как показано ниже? (Мне нужно, чтобы это значение сохранялось после перезагрузки.)
Я пробовал использовать:
SharedPreferences.putLong("время", date.getTime()); Общие настройки.commit();
так же как:
putLong("время", date.getTime()); совершить();
Однако оба метода вызывают ошибки, и я просто хочу убедиться, что значения будут сохранены после перезагрузки.
public class WifiMonitor extends Activity {
Button sendButton;
EditText msgTextField;
private PendingIntent pendingIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView infoView = (TextView) findViewById(R.id.traffic_info);
// get traffic info
double totalBytes = (double) TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes()
+ TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;
NumberFormat nf = new DecimalFormat("#.##");
String totalStr = nf.format(totalBytes);
String mobileStr = nf.format(mobileBytes);
String info = String.format(
"Wifi Data Usage: %s MB\tMobile Data Usage: %s MB", totalStr,
mobileStr);
infoView.setText(info);
// send traffic info via sms
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("7862611848", null, info, null, null);
String alarm = Context.ALARM_SERVICE;
// get the current date
Date date = new Date(System.currentTimeMillis());
// convert the date to milliseconds
long millis = date.getTime();
// save the date to shared preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
// SharedPreferences prefs = millis;
// SharedPreferences.Editor editor = PreferenceManager
// .getDefaultSharedPreferences(getApplicationContext());
editor.putLong("time", date.getTime());
editor.commit();
// get the saved date
Date myDate = new Date(prefs.getLong("time", 0));
}
// set the alarm to expire 30 days from the date stored in sharePreferences
public void invokeAlarm(long invokeTime, long rowId) {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, Alarm.class);
i.putExtra("rowId", String.valueOf(rowId));
am.set(AlarmManager.RTC_WAKEUP, invokeTime, PendingIntent.getService(
this, (int) System.currentTimeMillis(), i, 0));
}
}