【发布时间】:2013-11-30 05:14:55
【问题描述】:
我正在尝试在我的应用程序中读取大型文本文件,为此我需要使用 AsyncTask。我调整了我拥有的代码(完美运行)来读取小文件以在 AsyncTask 中工作。我遇到的问题是更新 ProgressBar。
我正在尝试使其与问题的答案一起工作:android update progress bar while reading records from a text file,内容如下:
“如何使用文件大小并计算每次读取的字节数?”
int sizeInBytes = file.length();
int currentBytes = 0;
//READ A LINE
currentBytes += line.length();
updateProgress((currentBytes/sizeInBytes)*100);
我尝试在我的应用程序中使用它,但我无法让它工作。 这是我的代码:
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();
}
}
【问题讨论】:
标签: android android-asynctask android-progressbar