我正在開發一款適用於嬰兒的android應用程序,在用戶設置了寶寶的出生日期後,我需要保存它,以便在睡眠和接種疫苗等其他活動中使用它。 我已經使用Shared Preference來保存用戶輸入的數據。 但我還沒有弄清楚如何獲取該數據並在其他類中使用它。你能幫我嗎?如何獲得年齡並將其用於其他活動?
這裏是寶寶數據的代碼需要
public class MainActivity extends Activity {
private Button change;
private ImageView bImage;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
updateDateDisplay();
}
private void updateDateDisplay() {
this.mPickDate.setText(
new StringBuilder()
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" "));
}
public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH) + 1;
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
// the callback received when the user 「sets」 the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDateDisplay();
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
獲取年齡,然後使用意圖在活動之間傳遞數據http://stackoverflow.com/questions/15859445/how-do-you-pass-a-string-from-one-activity-to-another/15859488 #15859488 – Raghunandan 2013-05-07 19:07:24
或打開應用程序的相同共享首選項nd讀取保存在其中的日期.. – Kamal 2013-05-07 19:08:52
爲什麼不通過一個意圖將數據傳遞給其他Activity?似乎它會比使用SharedPrefs一個數據 – 2013-05-07 19:14:49