我想显示正在读取文件并放入数组列表的进度。这样,在应用程序以列表视图的形式向用户显示数组列表之前,我想展示通过AsyncTask读取了多少文件。当前,白屏短暂显示。正在读取的文件大约有20000行。
AsyncTask(MyTask
)是通过onCreate()
方法执行的,如下所示:
private class MyAsync extends AsyncTask<Void, Integer, ArrayList<Movie>> {
ProgressDialog mProgressDialog;
ArrayList<Movie> movies;
@Override
protected void onPreExecute() {
super.onPreExecute();
//Show progress to user
mProgressDialog = new ProgressDialog(MovieRatingsActivity.this);
mProgressDialog.setTitle("Reading file");
mProgressDialog.setMessage("Reading file, Please Wait!");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
@Override
protected ArrayList<Movie> doInBackground(Void... voids) {
try {
InputStream inputStream = getResources().openRawResource(R.raw.ratings);
int count = inputStream.available();
// onProgressUpdate( (amount read by inputstream / size of file )* 100 );
movies = Movie.loadFromFile(inputStream);
return movies;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(ArrayList<Movie> movies) {
super.onPostExecute(movies);
mProgressDialog.dismiss();
mInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
setListAdapter(new RowIconAdapter(getApplicationContext(), R.layout.listrow, R.id.row_label, movies));
}
}
函数Movie.loadFromFile(inputStream)
-将数据放入数组列表的位置
/** Loads movie information from a raw resource file */
public static ArrayList<Movie> loadFromFile(InputStream inputStream) {
ArrayList<Movie> movies = new ArrayList<Movie>(20000);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = br.readLine()) != null) {
String lRatings = line.substring(0,3).trim();
String lVotes = line.substring(4,12).trim();
String lName = line.substring(13).trim();
movies.add(new Movie(lName, lRatings, lVotes));
}
} catch (IOException iox) { } // pure evil at work
return movies;
}
答案 0 :(得分:0)
在doInBackground()
内部调用publishProgress(value)
,其中value是一个整数,代表完成的工作百分比。
这将触发onProgressUpdate()
,您将在progress[0]
中获得先前传递的值,然后可以相应地更新进度条。
编辑只能在while
的{{1}}循环中计算完成的工作百分比。因此,在这种情况下,更容易删除loadFromFile()
并将其所有代码放入loadFromFile()
中。然后像这样修改循环:
doInBackground()
值int counter = 0;
while ((line = br.readLine()) != null) {
String lRatings = line.substring(0,3).trim();
String lVotes = line.substring(4,12).trim();
String lName = line.substring(13).trim();
movies.add(new Movie(lName, lRatings, lVotes));
counter++;
if ((counter % 200) == 0)
publishProgress(counter / 200)
}
将占完成工作的1%,但您可以在耗时的情况下进行更改