Question

I'm trying to save a serialized timer object, and retrieve it. The timer needs to be restored exactly how it was when it was created.

The timer works beautifully, but when the app is destroyed so is my timer with all its data.

EDIT: debug log says FileNotFoundException: open failed (Read only File system)

  • I have the uses-permission in my manifest
  • I'm not attempting to write to an SD card, I want to create the file on the user's android locally. .......

My timer class implements serialized

And OnCreate My app try to connect to a objectinputstream, and a fileinputstream; retrieve the object, cast it to a Timer and assign it.

The timer is stored every time it's updated.

TIMER CLASS CODE

package com.example.theworkingbutton;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import android.widget.Button;

public class Timer implements Serializable {

    private static final long serialVersionUID = 1L;

    public Timer(int timerState){
        this.timerState = timerState;

    }

    public int timerState = 0;
    public long timerStart = 0;
    public long timerEnd = 0;
    public long timeAccumulated = 0;

    public long totalSeconds = 0;
    public long hours = 0;
    public long minutes = 0;
    public long seconds = 0;

    public String realTimeSeconds = "null";
    public String realTimeMinutes = "null";
    public String realTimeHours = "null";
    public String timeString = "No time avalible";

    Button button;

    public void preform(){

        if(timerState == 0){

            timerStart =  System.nanoTime();        
            timerState = 1;

        } else if (timerState == 1) {

            timerEnd = System.nanoTime();
            timeAccumulated = timerEnd - timerStart + timeAccumulated;

            totalSeconds = TimeUnit.SECONDS.convert(timeAccumulated, TimeUnit.NANOSECONDS);
            hours = (totalSeconds / 3600);
            minutes = (totalSeconds % 3600) / 60;
            seconds = (totalSeconds % 60);

            realTimeHours = Long.toString(hours);
            realTimeSeconds = Long.toString(seconds);
            realTimeMinutes = Long.toString(minutes);
            timeString = "Hours: " + realTimeHours + " Minutes: " + realTimeMinutes + " Seconds: " + realTimeSeconds;

            timerState = 0;
        }
    }
}

End Timer class code

ONCREATE Code

@Override
    protected void onCreate(Bundle savedInstanceState){

        //make screen
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        locManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
            500.0f, locationListener);

       //get buttons / turn them red
        workingButton = (Button) findViewById(R.id.timer_button);
        officeButton = (Button) findViewById(R.id.office_button);
        drivingButton = (Button) findViewById(R.id.drive_button);
        showingButton = (Button) findViewById(R.id.showing_button);
        prospectingButton = (Button) findViewById(R.id.prospect_button);
        listingButton = (Button) findViewById(R.id.listing_button);

        listingButton.getBackground().setColorFilter(0xffffff00, PorterDuff.Mode.MULTIPLY);
        workingButton.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
        drivingButton.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
        officeButton.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
        showingButton.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
        prospectingButton.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);


      //set up our map
        GoogleMap monthlyMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            location.getLatitude();
            location.getLongitude();
        }
        monthlyMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        monthlyMap.setMyLocationEnabled(true);
        monthlyMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()), 15 ));


        try{
        @SuppressWarnings("resource")
        ObjectInputStream is = new ObjectInputStream(new FileInputStream("TheWorkingButtonSaves.txt"));
        Timer timerOne = (Timer) is.readObject();
        workingTimer = timerOne;}
        catch (Exception e){
            e.printStackTrace();
        }
    }

END ON CREATE CODE

How im trying to save

 Timer workingTimer;
    public void startWorking(View view){

        if (workingTimer == null){
            workingTimer = new Timer(working);}

        //Layout Views
        workingButton = (Button) findViewById(R.id.timer_button);
        TextView amountOfTime = (TextView) findViewById(R.id.time_spent);

        if(drivingTimer.timerState == 1){
            drivingSomewhere(findViewById(R.id.drive_button));
        }

        workingTimer.preform();


        // Button Colors
         if (workingTimer.timerState == 0 ){     //(TIMERS OFF)
            workingButton = (Button) findViewById(R.id.timer_button);
            workingButton.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);

         } 
         else {  //(TIMERS ON)
             workingButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
         }

         //save
         try {

            FileOutputStream fs = new FileOutputStream ("TheWorkingButtonSaves.txt");
            ObjectOutputStream os = new ObjectOutputStream(fs);

            os.writeObject(workingTimer);
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
            }

         //Display Time to user
         amountOfTime.setText(workingTimer.timeString);
    }   

END HOW IM TRYING TO SAVE

Was it helpful?

Solution

You can save the value of the timer by using SharedPreferences.

   SharedPreferences saveTimer= getSharedPreferences("saveTimer", Activity.MODE_PRIVATE);
   SharedPreferences.Editor editor= timeSaved.edit();
   // There's also putLong and putFloat
   editor.putInt("saveTimer", INT_NAME_1);
   editor.commit();

You then retrieve it using

    SharedPreferences getTimer = getSharedPreferences("saveTimer", Activity.MODE_PRIVATE);
    int INT_NAME_2 = getTimer.getInt("saveTimer", 0);

Now you have an int (or float or long) value that you can put back and start from where you started. (You can also use this to retrieve the values of whatever you saved in other activities)

OTHER TIPS

See the below link if it helps. In my opinion it's better to let the platform handle the serializaion/deserialization instead of us doing it.

Handling runtime changes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top