0

I have created a file with an asynctask. Afterwards scheduled an executor to write information to said file once every second. Once I touch a button the executor is shut down and the file closed but more often than not nothing is written in the file.

Code:

startButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                preferences.edit().putBoolean(GlobalConstants.stopPreference,false).commit();
                loc_thr = new LocationThread(preferences, getApplicationContext());
                loc_thr.run();

                startButton.setVisibility(View.INVISIBLE);
                startButton.setClickable(false);
                stopButton.setVisibility(View.VISIBLE);
                stopButton.setClickable(true);

                currentDateAndTime = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                fileName = getString(R.string.loc_log_path) + currentDateAndTime + ".txt";
                new CreateFileTask(fileName).execute();
                loc_file = new File(fileName);
                try {
                    FOS = new FileOutputStream(loc_file.getAbsolutePath());
                    OSW = new OutputStreamWriter(FOS);
                    OSW.write(GlobalConstants.fileHeader + '\n');
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                scheduledTaskExecutor = Executors.newScheduledThreadPool(5);
                scheduledTaskExecutor.scheduleAtFixedRate(new Runnable() {
                    public void run() {
                        if(loc_thr.getLocationStatus() & loc_thr.newLocation() & !preferences.getBoolean(GlobalConstants.stopPreference,false)){
                            SensorBundle SB = new SensorBundle(loc_thr.getCurrentLocation(),loc_thr.getCurrentGPSStatus());
                            try {
                                OSW.write(new SimpleDateFormat("yyyy/MM/dd;hh:mm:ss").format(new Date()) + ";");
                                OSW.write(SB.getLatitude() + ";");
                                OSW.write(SB.getLongitude() + ";");
                                OSW.write(SB.getAltitude() + ";");
                                OSW.write(SB.getAccuracy() + ";");
                                OSW.write(SB.getProvider() + ";");
                                OSW.write('\n');
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else{
                            if(preferences.getBoolean(GlobalConstants.stopPreference,false)){
                                try {
                                    OSW.close();
                                    FOS.close();

                                    scheduledTaskExecutor.shutdown();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }, 0, 1, TimeUnit.SECONDS);
                }
        });

Whenever the stop button is pressed the SharedPreference queried earlier is set to true.

Moises Jimenez
  • 1,962
  • 3
  • 21
  • 43

1 Answers1

0

I think your problem may be here

   new CreateFileTask(fileName).execute();
   loc_file = new File(fileName);

I assume this task creates the file and you're expecting that when you can new File(fileName) the file is already created. Whether this is true or not is indeterminate. If the AsyncTask CreateFileTask is scheduled to run and completes before the next statement is executed then the file will be there, otherwise it won't be. Are you seeing stack traces in logcat from the IOException or FileNoteFoundExceptions?

cyngus
  • 1,763
  • 13
  • 14
  • How safe is it to do I/O operations on the main activity? Since I just created that asynctask with the sole purpose of avoiding that. I get EBADF, bad file number. – Moises Jimenez Aug 22 '12 at 07:35
  • You definitely shouldn't do I/O on the main thread. Creating the AsyncTask is the right thing to do, but the key thing is, its asynchronous. All the code you have after the call to AsyncTask.execute() should run in AsyncTask.onPostExecute() method. – cyngus Aug 22 '12 at 16:07
  • Would you recommend using ASyncTask instead of the ScheduledTaskExecutor as well? I managed to synchronize everything by implementing callbacks. – Moises Jimenez Aug 23 '12 at 07:59
  • The ScheduledTaskExecutor has the advantage of allowing you to do things periodically, AsyncTasks are one-shot, but you could have one schedule the next, although this seems more brittle, I think the Executor is right for your purposes. – cyngus Aug 23 '12 at 17:01