我正在为婴儿开发一个Android应用程序,在用户设置婴儿的出生日期后,我需要保存它,以便我可以在睡眠和接种等其他活动中使用它。 我使用共享首选项来保存用户输入的数据。 但我还没弄清楚如何获取这些数据并在其他类中使用它。你可以帮我吗?
这里是所需婴儿数据的代码
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;
}
答案 0 :(得分:0)
由于我没有在您的代码中看到您创建SharedPreference
的位置,因此我将从Docs
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // get it here using the name
boolean silent = settings.getBoolean("silentMode", false); get a value using the key
setSilent(silent);
}
您只需使用保存时创建的首选项的名称。此示例检索boolean
但您可以轻松将其更改为integer
或String
或您需要的任何内容
答案 1 :(得分:0)
访问Shared Prefs-&gt;
用于在prefs中保存String
数据 - &gt;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor e = prefs.edit();
e.putString(key, val); //Key - Name with which you want to save pref, val - value to save
e.commit();
从prefs获取String
数据 - &gt;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String s = prefs.getString(key, def); // Key - Name of prefs, def - default value if prefs with specified key so not exists
您可以在首选项中保存String
,Float
,Long
,Int
,Boolean
等。