Как получить и сохранить дату с помощью общих настроек

Исходное сообщение:

В следующем примере:

Как сохранить и получить дату в 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));
    }

}

person NoobDev954    schedule 17.06.2013    source источник
comment
Вы можете проверить это: stackoverflow.com/questions/6610284/   -  person MorZa    schedule 16.10.2014


Ответы (1)


PreferenceManager.getDefaultSharedPreferences(context);

Контекст может быть getApplicationContext().

person Stephane Mathis    schedule 17.06.2013
comment
Я получаю сообщение об ошибке: Несоответствие типа: невозможно преобразовать из long в SharedPreferences в строке SharedPreferences prefs = millis ; и я получаю сообщение об ошибке Несоответствие типа: невозможно преобразовать из SharedPreferences в SharedPreferences.Editor в строке: SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); - person NoobDev954; 18.06.2013
comment
Редактор SharedPreferences.Editor = PreferenceManager.getDefaultSharedPreferences(this); (что обычно работает, когда я ищу контекст, тоже не работает) - person NoobDev954; 18.06.2013
comment
Просто напиши это: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); - person Stephane Mathis; 18.06.2013
comment
Единственный способ, которым это компилируется без ошибок, — это закомментировать следующие строки (после добавления той, которую вы предложили выше): //SharedPreferences prefs = millis; // SharedPreferences.Editor editor = PreferenceManager // .getDefaultSharedPreferences(getApplicationContext()); // editor.putLong(время, date.getTime()); // редактор.commit(); Это должно быть сделано таким образом? - person NoobDev954; 18.06.2013