android UI got freeze and thread blocked while read data

67 Views Asked by At

I have code reading text line with BufferedReader and realm.io

realm.beginTransaction();
BufferedReader reader;
while ((strLineText = reader.readLine()) != null) {
    lineNumber++;
    LineData managedLineData = realm.copyToRealm(lineData);
    contentDataRealm.chatDataList.add(managedLineData);
    tvProgress.setText(getString(R.string.text_progress, lineNumber * 100 / totalLine));
    pbProgress.setProgress(lineNumber * maxProgress / totalLine);
}

The progress bar still 0 and text view not updated. i tried with ui thread and still have same issue.

realm.beginTransaction();
while ((strLineText = reader.readLine()) != null) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            lineNumber++;
            LineData managedLineData = realm.copyToRealm(lineData);
            contentDataRealm.chatDataList.add(managedLineData);
            tvProgress.setText(getString(R.string.text_progress, lineNumber * 100 / contentSize));
            pbProgress.setProgress(lineNumber * maxProgress / contentSize);
        }
    });
}

also with this

realm.beginTransaction();
while ((strLineText = reader.readLine()) != null) {
    tvProgress.post(new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    lineNumber++;
                    LineData managedLineData = realm.copyToRealm(lineData);
                    contentDataRealm.chatDataList.add(managedLineData);
                    tvProgress.setText(getString(R.string.text_progress, lineNumber * 100 / contentSize));
                    pbProgress.setProgress(lineNumber * maxProgress / contentSize);
                }
            });
        }
    });
}

then i decide to use indeterminate and find out that my loading animation is stop. i tried use postdelayed, loading animation working only before the reading started

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        readContent(); // reading text from BufferedReader
    }
}, 1000);

am i missing something?

1

There are 1 best solutions below

0
On

Try to split your workflow on 2 parts:

  1. read DB -> create text object (using StringBuilder or StringBuffer, try to make a right choice). This part should work in a background task.

  2. update UI. This part should run on the Main thread.

Important note: don't forget about Activity/Fragment lifecycle.