I'm trying to read large text files in my Application, for which I need to use AsyncTask. I adapt the code I had (which works perfectly) to read small files to work in AsyncTask. The problem that I have is to update the ProgressBar.
I'm trying to make it work with the answer to the question: android update progress bar while reading records from a text file, which reads as follows:
"What about using the file size and counting the number of bytes you read each time?"
int sizeInBytes = file.length();
int currentBytes = 0;
//READ A LINE
currentBytes += line.length();
updateProgress((currentBytes/sizeInBytes)*100);
I try to use that in my application but I can not make it work. This is my code:
private class MiTarea extends AsyncTask<String, Float, String > {
protected void onPreExecute() {
dialog.setProgress(0);
dialog.setMax(100);
dialog.show(); //Mostramos el diálogo antes de comenzar
}
protected String doInBackground(String... urls) {
if (carpeta_para_leer == "Textos"){
sdcard = new File( Environment.getExternalStorageDirectory().toString()+"/" + carpeta_para_leer + "/");
}else{
sdcard = new File( Environment.getExternalStorageDirectory().toString()+"/Textos/" + carpeta_para_leer + "/");
}
//Get the text file
File file = new File(sdcard, nombre_texto + ".txt");
sizeInBytes = file.length();
currentBytes = 0;
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1252"));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
currentBytes += (long)line.length(); //HERE I TRY TO UPDATE THE PROGRESSBAR
}
}
catch (IOException e) {
}
String nuevoTexto = text.toString().replaceAll("\t", " ");
String nuevoTextoA = nuevoTexto.replaceAll("\n", " ");
Holmes1 = nuevoTextoA;
delimitadores = " ";
tokenHolmes1 = new StringTokenizer(Holmes1, " ");
arrayHolmes1 = Holmes1.split(delimitadores);
return Holmes1;
}
protected void onProgressUpdate (Float... valores) {
dialog.setProgress((int)(currentBytes/sizeInBytes)*100);
}
protected void onPostExecute(Integer bytes) {
dialog.dismiss();
}
}