这个存储数据在sharedPreferences
中 SharedPreferences prefsDate = getSharedPreferences("Date", MODE_PRIVATE);
SharedPreferences.Editor editor = prefsDate.edit();
editor.putString("Date", textDate.getText().toString());
editor.commit();
SharedPreferences prefsTime = getSharedPreferences("Time", MODE_PRIVATE);
SharedPreferences.Editor edit = prefsTime.edit();
edit.putString("Time", textTime.getText().toString());
edit.commit();
SharedPreferences prefs = getSharedPreferences("Event", MODE_PRIVATE);
SharedPreferences.Editor edt = prefs.edit();
edt.putString("Event", event.getText().toString());
edt.commit();
这里我放了日历,但我怎么能为此获得价值(替换0)?
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH,0);
calendar.set(Calendar.MONTH,0);
calendar.set(Calendar.YEAR,0);
calendar.set(Calendar.HOUR_OF_DAY,0 );
calendar.set(Calendar.MINUTE, 0);
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
答案 0 :(得分:1)
首先,我认为你不需要3个独立的SharedPreferences来存储这3个值。
其次,您不能将值保存为String,然后将其作为Integer检索。将您的代码更改为以下内容:
SharedPreferences prefsDate = getSharedPreferences("Calendar", MODE_PRIVATE);
SharedPreferences.Editor editor = prefsDate.edit();
editor.putInt("Date", Integer.valueOf(textDate.getText().toString()));
// save other values here
editor.commit();
然后检索它们:
SharedPreferences prefsDate = getSharedPreferences("Calendar", MODE_PRIVATE);
int date = prefsDate.getInt("Date", 0);
或者,您可以使用我的SharedPreferences library,这可以为您缓解一切。
答案 1 :(得分:1)
您可以将其保存在单个字符串中,而不是分隔日期,月份和年份:
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR); // get the current year
int month = cal.get(Calendar.MONTH); // month...
int day = cal.get(Calendar.DAY_OF_MONTH); // current day in the month
String myDate=year + "/" + month + "/" + day;
现在您可以将整个String myDate保存在sharedPrefrence中并在您的应用中使用它:
保存字符串写入:
SharedPreferences prefsDate = getSharedPreferences("MyCalendar", MODE_PRIVATE);
SharedPreferences.Editor editor = prefsDate.edit();
editor.putString("Date",myDate);
editor.commit();
现在,要获取日期字符串,您应该写:
SharedPreferences prefsDate = getSharedPreferences("MyCalendar", MODE_PRIVATE);
private String dateFromSharedPrefences=prefsDate.getString("Date","");