Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit dad6836f authored by Stefan Niedermann's avatar Stefan Niedermann
Browse files

Use ExecutorServices for running threaded tasks

parent a2bbff4f
Loading
Loading
Loading
Loading
+12 −11
Original line number Diff line number Diff line
@@ -33,6 +33,8 @@ import com.nextcloud.android.sso.model.SingleSignOnAccount;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import it.niedermann.android.util.ColorUtil;
import it.niedermann.owncloud.notes.R;
@@ -62,6 +64,7 @@ import static java.lang.Boolean.TRUE;
public abstract class BaseNoteFragment extends BrandedFragment implements CategoryDialogListener, EditTitleListener {

    private static final String TAG = BaseNoteFragment.class.getSimpleName();
    protected final ExecutorService executor = Executors.newCachedThreadPool();

    protected static final int MENU_ID_PIN = -1;
    public static final String PARAM_NOTE_ID = "noteId";
@@ -98,7 +101,7 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new Thread(() -> {
        executor.submit(() -> {
            try {
                SingleSignOnAccount ssoAccount = SingleAccountHelper.getCurrentSingleSignOnAccount(requireContext().getApplicationContext());
                this.localAccount = repo.getAccountByName(ssoAccount.name);
@@ -143,7 +146,7 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
            } catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
                e.printStackTrace();
            }
        }).start();
        });
        setHasOptionsMenu(true);
    }

@@ -214,13 +217,13 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.menu_cancel) {
            new Thread(() -> {
            executor.submit(() -> {
                if (originalNote == null) {
                    repo.deleteNoteAndSync(localAccount, note.getId());
                } else {
                    repo.updateNoteAndSync(localAccount, originalNote, null, null, null);
                }
            }).start();
            });
            listener.close();
            return true;
        } else if (itemId == R.id.menu_delete) {
@@ -239,11 +242,9 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
            showEditTitleDialog();
            return true;
        } else if (itemId == R.id.menu_move) {
            new Thread(() -> {
                AccountPickerDialogFragment
            executor.submit(() -> AccountPickerDialogFragment
                    .newInstance(new ArrayList<>(repo.getAccounts()), note.getAccountId())
                        .show(requireActivity().getSupportFragmentManager(), BaseNoteFragment.class.getSimpleName());
            }).start();
                    .show(requireActivity().getSupportFragmentManager(), BaseNoteFragment.class.getSimpleName()));
            return true;
        } else if (itemId == R.id.menu_share) {
            ShareUtil.openShareDialog(requireContext(), note.getTitle(), note.getContent());
@@ -366,10 +367,10 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
    public void onTitleEdited(String newTitle) {
        titleModified = true;
        note.setTitle(newTitle);
        new Thread(() -> {
        executor.submit(() -> {
            note = repo.updateNoteAndSync(localAccount, note, note.getContent(), newTitle, null);
            requireActivity().runOnUiThread(() -> listener.onNoteUpdated(note));
        }).start();
        });
    }

    public void moveNote(Account account) {
+4 −4
Original line number Diff line number Diff line
@@ -155,22 +155,22 @@ public class NotePreviewFragment extends SearchableBaseNoteFragment implements O
    public void onRefresh() {
        if (noteLoaded && repo.isSyncPossible() && SSOUtil.isConfigured(getContext())) {
            binding.swiperefreshlayout.setRefreshing(true);
            new Thread(() -> {
            executor.submit(() -> {
                try {
                    final Account account = repo.getAccountByName(SingleAccountHelper.getCurrentSingleSignOnAccount(requireContext()).name);
                    repo.addCallbackPull(account, () -> new Thread(() -> {
                    repo.addCallbackPull(account, () -> executor.submit(() -> {
                        note = repo.getNoteById(note.getId());
                        changedText = note.getContent();
                        requireActivity().runOnUiThread(() -> {
                            binding.singleNoteContent.setMarkdownString(note.getContent());
                            binding.swiperefreshlayout.setRefreshing(false);
                        });
                    }).start());
                    }));
                    repo.scheduleSync(account, false);
                } catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
                    e.printStackTrace();
                }
            }).start();
            });
        } else {
            binding.swiperefreshlayout.setRefreshing(false);
            Toast.makeText(requireContext(), getString(R.string.error_sync, getString(R.string.error_no_network)), Toast.LENGTH_LONG).show();
+6 −2
Original line number Diff line number Diff line
@@ -21,6 +21,8 @@ import com.nextcloud.android.sso.helper.SingleAccountHelper;
import com.nextcloud.android.sso.ui.UiExceptionManager;

import java.net.HttpURLConnection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import it.niedermann.owncloud.notes.R;
import it.niedermann.owncloud.notes.branding.BrandingUtil;
@@ -39,6 +41,8 @@ public class ImportAccountActivity extends AppCompatActivity {
    private static final String TAG = ImportAccountActivity.class.getSimpleName();
    public static final int REQUEST_CODE_IMPORT_ACCOUNT = 1;

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    private ImportAccountViewModel importAccountViewModel;
    private ActivityImportAccountBinding binding;

@@ -86,7 +90,7 @@ public class ImportAccountActivity extends AppCompatActivity {
                runOnUiThread(() -> binding.progressCircular.setVisibility(View.VISIBLE));

                SingleAccountHelper.setCurrentAccount(getApplicationContext(), ssoAccount.name);
                new Thread(() -> {
                executor.submit(() -> {
                    Log.i(TAG, "Added account: " + "name:" + ssoAccount.name + ", " + ssoAccount.url + ", userId" + ssoAccount.userId);
                    try {
                        Log.i(TAG, "Loading capabilities for " + ssoAccount.name);
@@ -140,7 +144,7 @@ public class ImportAccountActivity extends AppCompatActivity {
                            }
                        });
                    }
                }).start();
                });
            });
        } catch (AccountImportCancelledException e) {
            restoreCleanState();
+10 −6
Original line number Diff line number Diff line
@@ -49,6 +49,8 @@ import com.nextcloud.android.sso.helper.SingleAccountHelper;
import java.net.HttpURLConnection;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import it.niedermann.owncloud.notes.LockedActivity;
import it.niedermann.owncloud.notes.R;
@@ -104,6 +106,8 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A

    private static final String TAG = MainActivity.class.getSimpleName();

    protected final ExecutorService executor = Executors.newCachedThreadPool();

    protected MainViewModel mainViewModel;
    private CategoryViewModel categoryViewModel;

@@ -164,14 +168,14 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
            if (count == 0) {
                startActivityForResult(new Intent(this, ImportAccountActivity.class), ImportAccountActivity.REQUEST_CODE_IMPORT_ACCOUNT);
            } else {
                new Thread(() -> {
                executor.submit(() -> {
                    try {
                        final Account account = mainViewModel.getLocalAccountByAccountName(SingleAccountHelper.getCurrentSingleSignOnAccount(getApplicationContext()).name);
                        runOnUiThread(() -> mainViewModel.postCurrentAccount(account));
                    } catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
                        runOnUiThread(() -> ExceptionDialogFragment.newInstance(e).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
                    }
                }).start();
                });
            }
        });

@@ -649,7 +653,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
                try {
                    AccountImporter.onActivityResult(requestCode, resultCode, data, this, (ssoAccount) -> {
                        CapabilitiesWorker.update(this);
                        new Thread(() -> {
                        executor.submit(() -> {
                            Log.i(TAG, "Added account: " + "name:" + ssoAccount.name + ", " + ssoAccount.url + ", userId" + ssoAccount.userId);
                            try {
                                Log.i(TAG, "Refreshing capabilities for " + ssoAccount.name);
@@ -658,11 +662,11 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
                                mainViewModel.addAccount(ssoAccount.url, ssoAccount.userId, ssoAccount.name, capabilities, displayName, new IResponseCallback<Account>() {
                                    @Override
                                    public void onSuccess(Account result) {
                                        new Thread(() -> {
                                        executor.submit(() -> {
                                            Log.i(TAG, capabilities.toString());
                                            final Account a = mainViewModel.getLocalAccountByAccountName(ssoAccount.name);
                                            runOnUiThread(() -> mainViewModel.postCurrentAccount(a));
                                        }).start();
                                        });
                                    }

                                    @Override
@@ -691,7 +695,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
                                    });
                                }
                            }
                        }).start();
                        });
                    });
                } catch (AccountImportCancelledException e) {
                    Log.i(TAG, "AccountImport has been cancelled.");
+10 −6
Original line number Diff line number Diff line
@@ -26,6 +26,8 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import it.niedermann.owncloud.notes.BuildConfig;
@@ -67,6 +69,8 @@ public class MainViewModel extends AndroidViewModel {

    private static final String TAG = MainViewModel.class.getSimpleName();

    private final ExecutorService executor = Executors.newCachedThreadPool();

    private final SavedStateHandle state;

    private static final String KEY_CURRENT_ACCOUNT = "currentAccount";
@@ -391,7 +395,7 @@ public class MainViewModel extends AndroidViewModel {
     * Updates the network status if necessary and pulls the latest {@link Capabilities} of the given {@param localAccount}
     */
    public void synchronizeCapabilities(@NonNull Account localAccount, @NonNull IResponseCallback<Void> callback) {
        new Thread(() -> {
        executor.submit(() -> {
            if (!repo.isSyncPossible()) {
                repo.updateNetworkStatus();
            }
@@ -428,14 +432,14 @@ public class MainViewModel extends AndroidViewModel {
                    callback.onError(new NetworkErrorException("Sync is not possible, because network is not connected."));
                }
            }
        }, "SYNC_CAPABILITIES").start();
        }, "SYNC_CAPABILITIES");
    }

    /**
     * Updates the network status if necessary and pulls the latest notes of the given {@param localAccount}
     */
    public void synchronizeNotes(@NonNull Account currentAccount, @NonNull IResponseCallback<Void> callback) {
        new Thread(() -> {
        executor.submit(() -> {
            Log.v(TAG, "[synchronize] - currentAccount: " + currentAccount.getAccountName());
            if (!repo.isSyncPossible()) {
                repo.updateNetworkStatus();
@@ -450,7 +454,7 @@ public class MainViewModel extends AndroidViewModel {
                    callback.onError(new NetworkErrorException("Sync is not possible, because network is not connected."));
                }
            }
        }, "SYNC_NOTES").start();
        }, "SYNC_NOTES");
    }

    public LiveData<Boolean> getSyncStatus() {
@@ -554,12 +558,12 @@ public class MainViewModel extends AndroidViewModel {
            } else {
                Log.v(TAG, "[getNote] - currentAccount: " + currentAccount.getAccountName());
                final MutableLiveData<List<Note>> notes = new MutableLiveData<>();
                new Thread(() -> notes.postValue(
                executor.submit(() -> notes.postValue(
                        ids
                                .stream()
                                .map(repo::getNoteById)
                                .collect(Collectors.toList())
                )).start();
                ));
                return notes;
            }
        });
Loading