jeudi 13 août 2015

Android DatePicker's date saving and loading

I'm trying to save a Datepicker's date into a file, and when opening the app read it back from last time and set the date on it accordingly (if it is the first time and no file was saved already, set it to Jan 1 2000). All widgets such as editText, names, gender, etc work correctly, except DatePicker.

For some reasons it doesn't work. Can someone help with that? There is no concern on the file IO part; probably there are some Calendar/Date compatibility issues I guess.

When loading:

Date BD=new Date(2000,0,1);
        // Loading (w/o exception handling code):
        try {
            FileInputStream fis = this.openFileInput(fileName);
            ObjectInputStream is = new ObjectInputStream(fis);
            Object[] formData = (Object[]) is.readObject();
            is.close();
            fis.close();

            // parse data from array
        BD=(Date) formData[0];
//there are other fields as well

    } catch (FileNotFoundException e) {
        // TODO if for the first time- No data file exists
        // sets initial default value
    } 
    catch (IOException e) {
    } 
    catch (ClassNotFoundException e) {
    }

    //set value for BD
    final DatePicker BDDatePicker = (DatePicker) findViewById(R.id.datePickerBD);
    BDDatePicker.updateDate(BD.getYear(), BD.getMonth(), BD.getDate());

And for saving:

    final DatePicker BDdatePicker = (DatePicker) findViewById(R.id.datePickerBD);
    Date BD= getDateFromDatePicker(BDdatePicker);
    Object [] formData=new Object [7];

    formData [0]=BD;


    //Saving (w/o exception handling code):
    FileOutputStream fos;
    try {
        fos = this.openFileOutput(fileName, Context.MODE_PRIVATE);
        try {
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(formData);
            fos.close();
            os.close();
        } catch (IOException e) {
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire