prokopis
prokopis

Reputation: 575

reading from a file is slow in android

i have implement a small code of reading from a file with scanner and save the values on an array. am reading 3-6 files the same time and save the numbers in 3-6 arrays. the files are saved on the sdcard of my phone. my problem is that is slow reading all thoses and it took a long time until it finish. how i can re-write the code in order to be more efficient, or the files should be saved on the poject and when i install the application on the device to install the files and access them from there

the code that am usgin is the below:

try {

 File I= new File(Environment.getExternalStorageDirectory().toString()+"/ECG/test/I.txt");  
 scannerI = new Scanner(I);
 scannerI.useDelimiter(";"); 
 for(int sampleIdx = 0; scannerI.hasNext();){
 timiI[sampleIdx] = scannerI.nextDouble();
 sampleIdx++;

 if(sampleIdx == SAMPLE_SIZE && !Thread.currentThread().isInterrupted()){
 //do something
 sampleIdx = 0;
                    }
                }           
           }
}

as i mention and before am using more than 1 files, and the according arrays

Upvotes: 0

Views: 983

Answers (1)

CjS
CjS

Reputation: 2047

Scanner is slow in Android in my experience.

I improved my application responsiveness by

  1. Moving the parsing code into an AsyncTask (http://developer.android.com/reference/android/os/AsyncTask.html) and running the file reading in a background thread.
  2. Using LineNumberReader and String.split(";") instead of Scanner.

The 2nd hint sped things up in my app by about 10x, but was still too slow to avoid an ANR, hence the background task.

Upvotes: 3

Related Questions