我正在尝试在我的应用程序中读取大文本文件,我需要使用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();
}
}
答案 0 :(得分:1)
您应该将publishProgress(//your value here)
拨入doInbackground()
这将在内部拨打onProgressUpdate
我已经发布了ShortHand示例...了解方法是如何工作的
希望这可以帮助......