]> git.ktnx.net Git - mobile-ledger.git/commitdiff
rework background progress to use MutableLiveData and observers
authorDamyan Ivanov <dam+mobileledger@ktnx.net>
Sat, 15 Aug 2020 11:57:51 +0000 (11:57 +0000)
committerDamyan Ivanov <dam+mobileledger@ktnx.net>
Sat, 15 Aug 2020 12:48:13 +0000 (12:48 +0000)
app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
app/src/main/java/net/ktnx/mobileledger/model/Data.java
app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java

index 5360cd006e694acef276612afed88724e56d14c6..371013005173c211a32644999aed851ff0a3af8a 100644 (file)
@@ -116,10 +116,7 @@ public class RetrieveTransactionsTask
     @Override
     protected void onProgressUpdate(Progress... values) {
         super.onProgressUpdate(values);
-        MainActivity context = getContext();
-        if (context == null)
-            return;
-        context.onRetrieveProgress(values[0]);
+        Data.backgroundTaskProgress.postValue(values[0]);
     }
     @Override
     protected void onPreExecute() {
@@ -132,22 +129,22 @@ public class RetrieveTransactionsTask
     @Override
     protected void onPostExecute(String error) {
         super.onPostExecute(error);
-        MainActivity context = getContext();
-        if (context == null)
-            return;
-        context.onRetrieveDone(error);
+        Progress progress = new Progress();
+        progress.setState(ProgressState.FINISHED);
+        progress.setError(error);
+        onProgressUpdate(progress);
     }
     @Override
     protected void onCancelled() {
         super.onCancelled();
-        MainActivity context = getContext();
-        if (context == null)
-            return;
-        context.onRetrieveDone(null);
+        Progress progress = new Progress();
+        progress.setState(ProgressState.FINISHED);
+        onProgressUpdate(progress);
     }
     private String retrieveTransactionListLegacy() throws IOException, HTTPException {
-        Progress progress = new Progress();
-        int maxTransactionId = Progress.INDETERMINATE;
+        Progress progress = Progress.indeterminate();
+        progress.setState(ProgressState.RUNNING);
+        int maxTransactionId = -1;
         ArrayList<LedgerAccount> list = new ArrayList<>();
         HashMap<String, LedgerAccount> map = new HashMap<>();
         ArrayList<LedgerAccount> displayed = new ArrayList<>();
@@ -279,8 +276,7 @@ public class RetrieveTransactionsTask
                             progress.setProgress(++processedTransactionCount);
                             if (maxTransactionId < transactionId)
                                 maxTransactionId = transactionId;
-                            if ((progress.getTotal() == Progress.INDETERMINATE) ||
-                                (progress.getTotal() < transactionId))
+                            if ((progress.isIndeterminate()) || (progress.getTotal() < transactionId))
                                 progress.setTotal(transactionId);
                             publishProgress(progress);
                         }
@@ -387,8 +383,6 @@ public class RetrieveTransactionsTask
         return acc;
     }
     private boolean retrieveAccountList() throws IOException, HTTPException {
-        Progress progress = new Progress();
-
         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
         http.setAllowUserInteraction(false);
         switch (http.getResponseCode()) {
@@ -399,7 +393,7 @@ public class RetrieveTransactionsTask
             default:
                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
         }
-        publishProgress(progress);
+        publishProgress(Progress.indeterminate());
         SQLiteDatabase db = App.getDatabase();
         ArrayList<LedgerAccount> list = new ArrayList<>();
         HashMap<String, LedgerAccount> map = new HashMap<>();
@@ -566,28 +560,71 @@ public class RetrieveTransactionsTask
         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
     }
 
+    public enum ProgressState {STARTING, RUNNING, FINISHED}
+
     public static class Progress {
-        public static final int INDETERMINATE = -1;
         private int progress;
         private int total;
+        private ProgressState state = ProgressState.RUNNING;
+        private String error = null;
+        private boolean indeterminate;
         Progress() {
-            this(INDETERMINATE, INDETERMINATE);
+            indeterminate = true;
         }
         Progress(int progress, int total) {
+            this.indeterminate = false;
             this.progress = progress;
             this.total = total;
         }
+        public static Progress indeterminate() {
+            return new Progress();
+        }
+        public static Progress finished(String error) {
+            Progress p = new Progress();
+            p.setState(ProgressState.FINISHED);
+            p.setError(error);
+            return p;
+        }
         public int getProgress() {
+            ensureState(ProgressState.RUNNING);
             return progress;
         }
         protected void setProgress(int progress) {
             this.progress = progress;
+            this.state = ProgressState.RUNNING;
         }
         public int getTotal() {
+            ensureState(ProgressState.RUNNING);
             return total;
         }
         protected void setTotal(int total) {
             this.total = total;
+            state = ProgressState.RUNNING;
+        }
+        private void ensureState(ProgressState wanted) {
+            if (state != wanted)
+                throw new IllegalStateException(
+                        String.format("Bad state: %s, expected %s", state, wanted));
+        }
+        public ProgressState getState() {
+            return state;
+        }
+        public void setState(ProgressState state) {
+            this.state = state;
+        }
+        public String getError() {
+            ensureState(ProgressState.FINISHED);
+            return error;
+        }
+        public void setError(String error) {
+            this.error = error;
+            state = ProgressState.FINISHED;
+        }
+        public boolean isIndeterminate() {
+            return indeterminate;
+        }
+        public void setIndeterminate(boolean indeterminate) {
+            this.indeterminate = indeterminate;
         }
     }
 
index a379f2bce8adadbc68eefb25bd808f0d51950e8f..a278a1b6318cd361143cf5d9ae7ef5c5c1b3ead6 100644 (file)
@@ -21,7 +21,11 @@ import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.AsyncTask;
 
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.lifecycle.LifecycleOwner;
 import androidx.lifecycle.MutableLiveData;
+import androidx.lifecycle.Observer;
 
 import net.ktnx.mobileledger.App;
 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
@@ -39,6 +43,7 @@ import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 import java.util.Locale;
+import java.util.Objects;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import static net.ktnx.mobileledger.utils.Logger.debug;
@@ -52,6 +57,8 @@ public final class Data {
             new MutableLiveData<>(null);
     public static final MutableLiveData<Boolean> backgroundTasksRunning =
             new MutableLiveData<>(false);
+    public static final MutableLiveData<RetrieveTransactionsTask.Progress> backgroundTaskProgress =
+            new MutableLiveData<>();
     public static final MutableLiveData<Date> lastUpdateDate = new MutableLiveData<>();
     public static final MutableLiveData<ArrayList<MobileLedgerProfile>> profiles =
             new MutableLiveData<>(null);
index 72ace25ba1077159a79df6a64ceafe21d7ddc7df..25fb12a2faf4b59423e1913ecb4bc3855480661c 100644 (file)
@@ -61,7 +61,6 @@ import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
 import net.ktnx.mobileledger.utils.Colors;
-import net.ktnx.mobileledger.utils.GetOptCallback;
 import net.ktnx.mobileledger.utils.Logger;
 import net.ktnx.mobileledger.utils.MLDB;
 
@@ -174,6 +173,7 @@ public class MainActivity extends ProfileThemedActivity {
         Data.observeProfile(this, this::onProfileChanged);
 
         Data.profiles.observe(this, this::onProfileListChanged);
+        Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
 
         if (barDrawerToggle == null) {
             barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
@@ -492,17 +492,6 @@ public class MainActivity extends ProfileThemedActivity {
         intent.putExtras(args);
         startActivity(intent, args);
     }
-    private void setupProfile() {
-        MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback() {
-            @Override
-            protected void onResult(String profileUUID) {
-                MobileLedgerProfile startupProfile;
-
-                startupProfile = Data.getProfile(profileUUID);
-                Data.setCurrentProfile(startupProfile);
-            }
-        });
-    }
     public void fabNewTransactionClicked(View view) {
         Intent intent = new Intent(this, NewTransactionActivity.class);
         startActivity(intent);
@@ -581,20 +570,6 @@ public class MainActivity extends ProfileThemedActivity {
         Data.stopTransactionsRetrieval();
         bTransactionListCancelDownload.setEnabled(false);
     }
-    public void onRetrieveDone(String error) {
-        Data.transactionRetrievalDone();
-        findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
-
-        if (error == null) {
-            updateLastUpdateTextFromDB();
-
-            new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
-            TransactionListViewModel.scheduleTransactionListReload();
-        }
-        else
-            Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
-                    .show();
-    }
     public void onRetrieveStart() {
         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
         bTransactionListCancelDownload.setEnabled(true);
@@ -610,9 +585,38 @@ public class MainActivity extends ProfileThemedActivity {
     }
     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
-        if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
-            (progress.getTotal() == 0))
-        {
+
+        if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
+            findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
+
+            Data.transactionRetrievalDone();
+
+            if (progress.getError() != null) {
+                Snackbar.make(mViewPager, progress.getError(), Snackbar.LENGTH_LONG)
+                        .show();
+                return;
+            }
+
+            updateLastUpdateTextFromDB();
+
+            new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
+            TransactionListViewModel.scheduleTransactionListReload();
+
+            return;
+        }
+
+
+        bTransactionListCancelDownload.setEnabled(true);
+        ColorStateList csl = Colors.getColorStateList();
+        progressBar.setIndeterminateTintList(csl);
+        progressBar.setProgressTintList(csl);
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
+            progressBar.setProgress(0, false);
+        else
+            progressBar.setProgress(0);
+        findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
+
+        if (progress.isIndeterminate() || (progress.getTotal() == 0)) {
             progressBar.setIndeterminate(true);
         }
         else {