From 12f135bb1401d3eeba227880acc02520c5fef9b6 Mon Sep 17 00:00:00 2001 From: m2049r Date: Sun, 14 Mar 2021 21:21:36 +0100 Subject: [PATCH] refactoring --- .../com/m2049r/xmrwallet/ReceiveFragment.java | 117 +++---- .../com/m2049r/xmrwallet/WalletActivity.java | 299 +++++++----------- .../com/m2049r/xmrwallet/WalletFragment.java | 30 +- .../xmrwallet/fragment/send/SendFragment.java | 7 +- 4 files changed, 180 insertions(+), 273 deletions(-) diff --git a/app/src/main/java/com/m2049r/xmrwallet/ReceiveFragment.java b/app/src/main/java/com/m2049r/xmrwallet/ReceiveFragment.java index 684f30aa..f533a0c2 100644 --- a/app/src/main/java/com/m2049r/xmrwallet/ReceiveFragment.java +++ b/app/src/main/java/com/m2049r/xmrwallet/ReceiveFragment.java @@ -16,6 +16,7 @@ package com.m2049r.xmrwallet; +import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; @@ -43,6 +44,7 @@ import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.ShareActionProvider; import androidx.core.content.FileProvider; @@ -57,7 +59,6 @@ import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; -import com.m2049r.xmrwallet.BuildConfig; import com.m2049r.xmrwallet.data.BarcodeData; import com.m2049r.xmrwallet.data.Crypto; import com.m2049r.xmrwallet.ledger.LedgerProgressDialog; @@ -74,6 +75,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import timber.log.Timber; @@ -86,7 +88,6 @@ public class ReceiveFragment extends Fragment { private ExchangeView evAmount; private TextView tvQrCode; private ImageView ivQrCode; - private View cvQrCode; private ImageView ivQrCodeFull; private EditText etDummy; private ImageButton bCopyAddress; @@ -114,7 +115,6 @@ public class ReceiveFragment extends Fragment { tvAddress = view.findViewById(R.id.tvAddress); etNotes = view.findViewById(R.id.etNotes); evAmount = view.findViewById(R.id.evAmount); - cvQrCode = view.findViewById(R.id.cvQrCode); ivQrCode = view.findViewById(R.id.qrCode); tvQrCode = view.findViewById(R.id.tvQrCode); ivQrCodeFull = view.findViewById(R.id.qrCodeFull); @@ -128,40 +128,31 @@ public class ReceiveFragment extends Fragment { enableCopyAddress(false); enableSubaddressButton(false); - evAmount.setOnNewAmountListener(new ExchangeView.OnNewAmountListener() { - @Override - public void onNewAmount(String xmr) { - Timber.d("new amount = %s", xmr); - generateQr(); - } + evAmount.setOnNewAmountListener(xmr -> { + Timber.d("new amount = %s", xmr); + generateQr(); }); - evAmount.setOnFailedExchangeListener(new ExchangeView.OnFailedExchangeListener() { - @Override - public void onFailedExchange() { - if (isAdded()) { - clearQR(); - Toast.makeText(getActivity(), getString(R.string.message_exchange_failed), Toast.LENGTH_LONG).show(); - } + evAmount.setOnFailedExchangeListener(() -> { + if (isAdded()) { + clearQR(); + Toast.makeText(getActivity(), getString(R.string.message_exchange_failed), Toast.LENGTH_LONG).show(); } }); final EditText notesEdit = etNotes.getEditText(); notesEdit.setRawInputType(InputType.TYPE_CLASS_TEXT); - notesEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) - || (actionId == EditorInfo.IME_ACTION_DONE)) { - generateQr(); - return true; - } - return false; + notesEdit.setOnEditorActionListener((v, actionId, event) -> { + if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) + || (actionId == EditorInfo.IME_ACTION_DONE)) { + generateQr(); + return true; } + return false; }); notesEdit.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } @Override @@ -171,47 +162,33 @@ public class ReceiveFragment extends Fragment { @Override public void afterTextChanged(Editable s) { - } }); - bSubaddress.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - enableSubaddressButton(false); - enableCopyAddress(false); + bSubaddress.setOnClickListener(v -> { + enableSubaddressButton(false); + enableCopyAddress(false); - final Runnable newAddress = new Runnable() { - public void run() { - getNewSubaddress(); - } - }; + final Runnable newAddress = this::getNewSubaddress; - tvAddress.animate().alpha(0).setDuration(250) - .withEndAction(newAddress).start(); + tvAddress.animate().alpha(0).setDuration(250) + .withEndAction(newAddress).start(); + }); + + view.findViewById(R.id.cvQrCode).setOnClickListener(v -> { + Helper.hideKeyboard(getActivity()); + etDummy.requestFocus(); + if (qrValid) { + ivQrCodeFull.setImageBitmap(((BitmapDrawable) ivQrCode.getDrawable()).getBitmap()); + ivQrCodeFull.setVisibility(View.VISIBLE); + } else { + evAmount.doExchange(); } }); - cvQrCode.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Helper.hideKeyboard(getActivity()); - etDummy.requestFocus(); - if (qrValid) { - ivQrCodeFull.setImageBitmap(((BitmapDrawable) ivQrCode.getDrawable()).getBitmap()); - ivQrCodeFull.setVisibility(View.VISIBLE); - } else { - evAmount.doExchange(); - } - } - }); - - ivQrCodeFull.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - ivQrCodeFull.setImageBitmap(null); - ivQrCodeFull.setVisibility(View.GONE); - } + ivQrCodeFull.setOnClickListener(v -> { + ivQrCodeFull.setImageBitmap(null); + ivQrCodeFull.setVisibility(View.GONE); }); showProgress(); @@ -249,14 +226,14 @@ public class ReceiveFragment extends Fragment { final MaterialContainerTransform transform = new MaterialContainerTransform(); transform.setDrawingViewId(R.id.fragment_container); transform.setDuration(getResources().getInteger(R.integer.tx_item_transition_duration)); - transform.setAllContainerColors(ThemeHelper.getThemedColor(getContext(), R.attr.colorSurface)); + transform.setAllContainerColors(ThemeHelper.getThemedColor(Objects.requireNonNull(getContext()), R.attr.colorSurface)); setSharedElementEnterTransition(transform); } private ShareActionProvider shareActionProvider; @Override - public void onCreateOptionsMenu(Menu menu, final MenuInflater inflater) { + public void onCreateOptionsMenu(@NonNull Menu menu, final MenuInflater inflater) { inflater.inflate(R.menu.receive_menu, menu); super.onCreateOptionsMenu(menu, inflater); @@ -327,7 +304,7 @@ public class ReceiveFragment extends Fragment { } void copyAddress() { - Helper.clipBoardCopy(getActivity(), getString(R.string.label_copy_address), tvAddress.getText().toString()); + Helper.clipBoardCopy(Objects.requireNonNull(getActivity()), getString(R.string.label_copy_address), tvAddress.getText().toString()); Toast.makeText(getActivity(), getString(R.string.message_copy_address), Toast.LENGTH_SHORT).show(); } @@ -388,6 +365,7 @@ public class ReceiveFragment extends Fragment { GenerateReviewFragment.ProgressListener progressCallback = null; + @SuppressLint("StaticFieldLeak") private class AsyncShow extends AsyncTask { final private String walletPath; final private String password; @@ -441,8 +419,8 @@ public class ReceiveFragment extends Fragment { new AsyncStore().executeOnExecutor(MoneroThreadPoolExecutor.MONERO_THREAD_POOL_EXECUTOR); } + @SuppressLint("StaticFieldLeak") private class AsyncStore extends AsyncTask { - @Override protected Boolean doInBackground(String... params) { if (params.length != 0) return false; @@ -527,12 +505,12 @@ public class ReceiveFragment extends Fragment { canvas.save(); // figure out how to scale the logo float scaleSize = 1.0f; - while ((logoWidth / scaleSize) > (qrWidth / 5) || (logoHeight / scaleSize) > (qrHeight / 5)) { + while ((logoWidth / scaleSize) > (qrWidth / 5.) || (logoHeight / scaleSize) > (qrHeight / 5.)) { scaleSize *= 2; } float sx = 1.0f / scaleSize; - canvas.scale(sx, sx, qrWidth / 2, qrHeight / 2); - canvas.drawBitmap(logo, (qrWidth - logoWidth) / 2, (qrHeight - logoHeight) / 2, null); + canvas.scale(sx, sx, qrWidth / 2f, qrHeight / 2f); + canvas.drawBitmap(logo, (qrWidth - logoWidth) / 2f, (qrHeight - logoHeight) / 2f, null); canvas.restore(); return logoBitmap; } @@ -557,7 +535,7 @@ public class ReceiveFragment extends Fragment { Listener listenerCallback = null; @Override - public void onAttach(Context context) { + public void onAttach(@NonNull Context context) { super.onAttach(context); if (context instanceof Listener) { this.listenerCallback = (Listener) context; @@ -592,6 +570,7 @@ public class ReceiveFragment extends Fragment { new AsyncSubaddress().executeOnExecutor(MoneroThreadPoolExecutor.MONERO_THREAD_POOL_EXECUTOR); } + @SuppressLint("StaticFieldLeak") private class AsyncSubaddress extends AsyncTask { private String newSubaddress; @@ -626,11 +605,7 @@ public class ReceiveFragment extends Fragment { wallet.getNumSubaddresses() - 1)); generateQr(); enableCopyAddress(true); - final Runnable resetSize = new Runnable() { - public void run() { - tvAddress.animate().setDuration(125).scaleX(1).scaleY(1).start(); - } - }; + final Runnable resetSize = () -> tvAddress.animate().setDuration(125).scaleX(1).scaleY(1).start(); tvAddress.animate().alpha(1).setDuration(125) .scaleX(1.2f).scaleY(1.2f) .withEndAction(resetSize).start(); diff --git a/app/src/main/java/com/m2049r/xmrwallet/WalletActivity.java b/app/src/main/java/com/m2049r/xmrwallet/WalletActivity.java index 49325217..2e862e1f 100644 --- a/app/src/main/java/com/m2049r/xmrwallet/WalletActivity.java +++ b/app/src/main/java/com/m2049r/xmrwallet/WalletActivity.java @@ -16,6 +16,7 @@ package com.m2049r.xmrwallet; +import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; @@ -205,7 +206,6 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste connectWalletService(walletId, password); } else { finish(); - //throw new IllegalStateException("No extras passed! Panic!"); } } @@ -270,47 +270,36 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste @Override public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.action_rescan: - onWalletRescan(); - return true; - case R.id.action_info: - onWalletDetails(); - return true; - case R.id.action_credits: - CreditsFragment.display(getSupportFragmentManager()); - return true; - case R.id.action_share: - onShareTxInfo(); - return true; - case R.id.action_help_tx_info: - HelpFragment.display(getSupportFragmentManager(), R.string.help_tx_details); - return true; - case R.id.action_help_wallet: - HelpFragment.display(getSupportFragmentManager(), R.string.help_wallet); - return true; - case R.id.action_details_help: - HelpFragment.display(getSupportFragmentManager(), R.string.help_details); - return true; - case R.id.action_details_changepw: - onWalletChangePassword(); - return true; - case R.id.action_help_send: - HelpFragment.display(getSupportFragmentManager(), R.string.help_send); - return true; - case R.id.action_rename: - onAccountRename(); - return true; - case R.id.action_streetmode: - if (isStreetMode()) { // disable streetmode - onDisableStreetMode(); - } else { - onEnableStreetMode(); - } - return true; - default: - return super.onOptionsItemSelected(item); - } + final int itemId = item.getItemId(); + if (itemId == R.id.action_rescan) { + onWalletRescan(); + } else if (itemId == R.id.action_info) { + onWalletDetails(); + } else if (itemId == R.id.action_credits) { + CreditsFragment.display(getSupportFragmentManager()); + } else if (itemId == R.id.action_share) { + onShareTxInfo(); + } else if (itemId == R.id.action_help_tx_info) { + HelpFragment.display(getSupportFragmentManager(), R.string.help_tx_details); + } else if (itemId == R.id.action_help_wallet) { + HelpFragment.display(getSupportFragmentManager(), R.string.help_wallet); + } else if (itemId == R.id.action_details_help) { + HelpFragment.display(getSupportFragmentManager(), R.string.help_details); + } else if (itemId == R.id.action_details_changepw) { + onWalletChangePassword(); + } else if (itemId == R.id.action_help_send) { + HelpFragment.display(getSupportFragmentManager(), R.string.help_send); + } else if (itemId == R.id.action_rename) { + onAccountRename(); + } else if (itemId == R.id.action_streetmode) { + if (isStreetMode()) { // disable streetmode + onDisableStreetMode(); + } else { + onEnableStreetMode(); + } + } else + return super.onOptionsItemSelected(item); + return true; } private void updateStreetMode() { @@ -326,12 +315,9 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste Helper.promptPassword(WalletActivity.this, getWallet().getName(), false, new Helper.PasswordAction() { @Override public void act(String walletName, String password, boolean fingerprintUsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - enableStreetMode(false); - updateStreetMode(); - } + runOnUiThread(() -> { + enableStreetMode(false); + updateStreetMode(); }); } @@ -422,10 +408,8 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste case NetworkType_Mainnet: toolbar.setBackgroundResource(R.drawable.backgound_toolbar_mainnet); break; - case NetworkType_Testnet: - toolbar.setBackgroundResource(ThemeHelper.getThemedResourceId(this, R.attr.colorPrimaryDark)); - break; case NetworkType_Stagenet: + case NetworkType_Testnet: toolbar.setBackgroundResource(ThemeHelper.getThemedResourceId(this, R.attr.colorPrimaryDark)); break; default: @@ -442,7 +426,7 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste private WalletService mBoundService = null; private boolean mIsBound = false; - private ServiceConnection mConnection = new ServiceConnection() { + private final ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to @@ -590,18 +574,10 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste onProgress(-1); saveWallet(); // save on first sync synced = true; - runOnUiThread(new Runnable() { - public void run() { - walletFragment.onSynced(); - } - }); + runOnUiThread(walletFragment::onSynced); } } - runOnUiThread(new Runnable() { - public void run() { - walletFragment.onRefreshed(wallet, full); - } - }); + runOnUiThread(() -> walletFragment.onRefreshed(wallet, full)); return true; } catch (ClassCastException ex) { // not in wallet fragment (probably send monero) @@ -613,13 +589,11 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste @Override public void onWalletStored(final boolean success) { - runOnUiThread(new Runnable() { - public void run() { - if (success) { - Toast.makeText(WalletActivity.this, getString(R.string.status_wallet_unloaded), Toast.LENGTH_SHORT).show(); - } else { - Toast.makeText(WalletActivity.this, getString(R.string.status_wallet_unload_failed), Toast.LENGTH_LONG).show(); - } + runOnUiThread(() -> { + if (success) { + Toast.makeText(WalletActivity.this, getString(R.string.status_wallet_unloaded), Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(WalletActivity.this, getString(R.string.status_wallet_unload_failed), Toast.LENGTH_LONG).show(); } }); } @@ -628,30 +602,23 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste @Override public void onWalletOpen(final Wallet.Device device) { - switch (device) { - case Device_Ledger: - runOnUiThread(new Runnable() { - public void run() { - showLedgerProgressDialog(LedgerProgressDialog.TYPE_RESTORE); - } - }); + if (device == Wallet.Device.Device_Ledger) { + runOnUiThread(() -> showLedgerProgressDialog(LedgerProgressDialog.TYPE_RESTORE)); } } @Override public void onWalletStarted(final Wallet.Status walletStatus) { - runOnUiThread(new Runnable() { - public void run() { - dismissProgressDialog(); - if (walletStatus == null) { - // guess what went wrong - Toast.makeText(WalletActivity.this, getString(R.string.status_wallet_connect_failed), Toast.LENGTH_LONG).show(); - } else { - if (Wallet.ConnectionStatus.ConnectionStatus_WrongVersion == walletStatus.getConnectionStatus()) - Toast.makeText(WalletActivity.this, getString(R.string.status_wallet_connect_wrongversion), Toast.LENGTH_LONG).show(); - else if (!walletStatus.isOk()) - Toast.makeText(WalletActivity.this, walletStatus.getErrorString(), Toast.LENGTH_LONG).show(); - } + runOnUiThread(() -> { + dismissProgressDialog(); + if (walletStatus == null) { + // guess what went wrong + Toast.makeText(WalletActivity.this, getString(R.string.status_wallet_connect_failed), Toast.LENGTH_LONG).show(); + } else { + if (Wallet.ConnectionStatus.ConnectionStatus_WrongVersion == walletStatus.getConnectionStatus()) + Toast.makeText(WalletActivity.this, getString(R.string.status_wallet_connect_wrongversion), Toast.LENGTH_LONG).show(); + else if (!walletStatus.isOk()) + Toast.makeText(WalletActivity.this, walletStatus.getErrorString(), Toast.LENGTH_LONG).show(); } }); if ((walletStatus == null) || (Wallet.ConnectionStatus.ConnectionStatus_Connected != walletStatus.getConnectionStatus())) { @@ -664,12 +631,10 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste final WalletFragment walletFragment = (WalletFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container); - runOnUiThread(new Runnable() { - public void run() { - updateAccountsHeader(); - if (walletFragment != null) { - walletFragment.onLoaded(); - } + runOnUiThread(() -> { + updateAccountsHeader(); + if (walletFragment != null) { + walletFragment.onLoaded(); } }); } @@ -680,17 +645,15 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste try { final SendFragment sendFragment = (SendFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container); - runOnUiThread(new Runnable() { - public void run() { - dismissProgressDialog(); - PendingTransaction.Status status = pendingTransaction.getStatus(); - if (status != PendingTransaction.Status.Status_Ok) { - String errorText = pendingTransaction.getErrorString(); - getWallet().disposePendingTransaction(); - sendFragment.onCreateTransactionFailed(errorText); - } else { - sendFragment.onTransactionCreated(txTag, pendingTransaction); - } + runOnUiThread(() -> { + dismissProgressDialog(); + PendingTransaction.Status status = pendingTransaction.getStatus(); + if (status != PendingTransaction.Status.Status_Ok) { + String errorText = pendingTransaction.getErrorString(); + getWallet().disposePendingTransaction(); + sendFragment.onCreateTransactionFailed(errorText); + } else { + sendFragment.onTransactionCreated(txTag, pendingTransaction); } }); } catch (ClassCastException ex) { @@ -706,11 +669,7 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste try { final SendFragment sendFragment = (SendFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container); - runOnUiThread(new Runnable() { - public void run() { - sendFragment.onSendTransactionFailed(error); - } - }); + runOnUiThread(() -> sendFragment.onSendTransactionFailed(error)); } catch (ClassCastException ex) { // not in spend fragment Timber.d(ex.getLocalizedMessage()); @@ -722,11 +681,7 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste try { final SendFragment sendFragment = (SendFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container); - runOnUiThread(new Runnable() { - public void run() { - sendFragment.onTransactionSent(txId); - } - }); + runOnUiThread(() -> sendFragment.onTransactionSent(txId)); } catch (ClassCastException ex) { // not in spend fragment Timber.d(ex.getLocalizedMessage()); @@ -752,18 +707,16 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste @Override public void onProgress(final int n) { - runOnUiThread(new Runnable() { - public void run() { - try { - WalletFragment walletFragment = (WalletFragment) - getSupportFragmentManager().findFragmentByTag(WalletFragment.class.getName()); - if (walletFragment != null) - walletFragment.setProgress(n); - } catch (ClassCastException ex) { - // not in wallet fragment (probably send monero) - Timber.d(ex.getLocalizedMessage()); - // keep calm and carry on - } + runOnUiThread(() -> { + try { + WalletFragment walletFragment = (WalletFragment) + getSupportFragmentManager().findFragmentByTag(WalletFragment.class.getName()); + if (walletFragment != null) + walletFragment.setProgress(n); + } catch (ClassCastException ex) { + // not in wallet fragment (probably send monero) + Timber.d(ex.getLocalizedMessage()); + // keep calm and carry on } }); } @@ -973,22 +926,17 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], - @NonNull int[] grantResults) { + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { Timber.d("onRequestPermissionsResult()"); - switch (requestCode) { - case Helper.PERMISSIONS_REQUEST_CAMERA: - // If request is cancelled, the result arrays are empty. - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - startScanFragment = true; - } else { - String msg = getString(R.string.message_camera_not_permitted); - Timber.e(msg); - Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); - } - break; - default: + if (requestCode == Helper.PERMISSIONS_REQUEST_CAMERA) { // If request is cancelled, the result arrays are empty. + if (grantResults.length > 0 + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + startScanFragment = true; + } else { + String msg = getString(R.string.message_camera_not_permitted); + Timber.e(msg); + Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); + } } } @@ -1034,7 +982,7 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste return getPreferences(Context.MODE_PRIVATE); } - private List accountIds = new ArrayList<>(); + private final List accountIds = new ArrayList<>(); // generate and cache unique ids for use in accounts list private int getAccountId(int accountIndex) { @@ -1115,39 +1063,33 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste alertDialogBuilder .setCancelable(false) .setPositiveButton(getString(R.string.label_ok), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - Helper.hideKeyboardAlways(WalletActivity.this); - String newName = etRename.getText().toString(); - wallet.setAccountLabel(newName); - updateAccountName(); - } + (dialog, id) -> { + Helper.hideKeyboardAlways(WalletActivity.this); + String newName = etRename.getText().toString(); + wallet.setAccountLabel(newName); + updateAccountName(); }) .setNegativeButton(getString(R.string.label_cancel), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - Helper.hideKeyboardAlways(WalletActivity.this); - dialog.cancel(); - } + (dialog, id) -> { + Helper.hideKeyboardAlways(WalletActivity.this); + dialog.cancel(); }); final AlertDialog dialog = alertDialogBuilder.create(); Helper.showKeyboard(dialog); // accept keyboard "ok" - etRename.setOnEditorActionListener(new TextView.OnEditorActionListener() { - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) - || (actionId == EditorInfo.IME_ACTION_DONE)) { - Helper.hideKeyboardAlways(WalletActivity.this); - String newName = etRename.getText().toString(); - dialog.cancel(); - wallet.setAccountLabel(newName); - updateAccountName(); - return false; - } + etRename.setOnEditorActionListener((v, actionId, event) -> { + if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) + || (actionId == EditorInfo.IME_ACTION_DONE)) { + Helper.hideKeyboardAlways(WalletActivity.this); + String newName = etRename.getText().toString(); + dialog.cancel(); + wallet.setAccountLabel(newName); + updateAccountName(); return false; } + return false; }); dialog.show(); @@ -1156,19 +1098,17 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste @Override public boolean onNavigationItemSelected(MenuItem item) { final int id = item.getItemId(); - switch (id) { - case R.id.account_new: - addAccount(); - break; - default: - Timber.d("NavigationDrawer ID=%d", id); - int accountIdx = accountIds.indexOf(id); - if (accountIdx >= 0) { - Timber.d("found @%d", accountIdx); - getWallet().setAccountIndex(accountIdx); - } - forceUpdate(); - drawer.closeDrawer(GravityCompat.START); + if (id == R.id.account_new) { + addAccount(); + } else { + Timber.d("NavigationDrawer ID=%d", id); + int accountIdx = accountIds.indexOf(id); + if (accountIdx >= 0) { + Timber.d("found @%d", accountIdx); + getWallet().setAccountIndex(accountIdx); + } + forceUpdate(); + drawer.closeDrawer(GravityCompat.START); } return true; } @@ -1177,6 +1117,7 @@ public class WalletActivity extends BaseActivity implements WalletFragment.Liste new AsyncAddAccount().executeOnExecutor(MoneroThreadPoolExecutor.MONERO_THREAD_POOL_EXECUTOR); } + @SuppressLint("StaticFieldLeak") private class AsyncAddAccount extends AsyncTask { boolean dialogOpened = false; diff --git a/app/src/main/java/com/m2049r/xmrwallet/WalletFragment.java b/app/src/main/java/com/m2049r/xmrwallet/WalletFragment.java index 16ea23a6..60e0f46d 100644 --- a/app/src/main/java/com/m2049r/xmrwallet/WalletFragment.java +++ b/app/src/main/java/com/m2049r/xmrwallet/WalletFragment.java @@ -58,13 +58,14 @@ import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; import timber.log.Timber; public class WalletFragment extends Fragment implements TransactionInfoAdapter.OnInteractionListener { private TransactionInfoAdapter adapter; - private NumberFormat formatter = NumberFormat.getInstance(); + private final NumberFormat formatter = NumberFormat.getInstance(); private TextView tvStreetView; private LinearLayout llBalance; @@ -81,7 +82,7 @@ public class WalletFragment extends Fragment private Spinner sCurrency; - private List dismissedTransactions = new ArrayList<>(); + private final List dismissedTransactions = new ArrayList<>(); public void resetDismissedTransactions() { dismissedTransactions.clear(); @@ -94,7 +95,7 @@ public class WalletFragment extends Fragment } @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { if (activityCallback.hasWallet()) inflater.inflate(R.menu.wallet_menu, menu); super.onCreateOptionsMenu(menu, inflater); @@ -132,7 +133,7 @@ public class WalletFragment extends Fragment List currencies = new ArrayList<>(); currencies.add(Helper.BASE_CRYPTO); currencies.addAll(Arrays.asList(getResources().getStringArray(R.array.currency))); - ArrayAdapter spinnerAdapter = new ArrayAdapter<>(getContext(), R.layout.item_spinner_balance, currencies); + ArrayAdapter spinnerAdapter = new ArrayAdapter<>(Objects.requireNonNull(getContext()), R.layout.item_spinner_balance, currencies); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sCurrency.setAdapter(spinnerAdapter); @@ -268,24 +269,14 @@ public class WalletFragment extends Fragment @Override public void onSuccess(final ExchangeRate exchangeRate) { if (isAdded()) - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - exchange(exchangeRate); - } - }); + new Handler(Looper.getMainLooper()).post(() -> exchange(exchangeRate)); } @Override public void onError(final Exception e) { Timber.e(e.getLocalizedMessage()); if (isAdded()) - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - exchangeFailed(); - } - }); + new Handler(Looper.getMainLooper()).post(() -> exchangeFailed()); } }); } else { @@ -426,7 +417,6 @@ public class WalletFragment extends Fragment void setActivityTitle(Wallet wallet) { if (wallet == null) return; walletTitle = wallet.getName(); - String watchOnly = (wallet.isWatchOnly() ? getString(R.string.label_watchonly) : ""); walletSubtitle = wallet.getAccountLabel(); activityCallback.setTitle(walletTitle, walletSubtitle); Timber.d("wallet title is %s", walletTitle); @@ -450,7 +440,7 @@ public class WalletFragment extends Fragment balance = wallet.getBalance(); unlockedBalance = wallet.getUnlockedBalance(); refreshBalance(); - String sync = ""; + String sync; if (!activityCallback.hasBoundService()) throw new IllegalStateException("WalletService not bound."); Wallet.ConnectionStatus daemonConnected = activityCallback.getConnectionStatus(); @@ -519,7 +509,7 @@ public class WalletFragment extends Fragment } @Override - public void onAttach(Context context) { + public void onAttach(@NonNull Context context) { super.onAttach(context); if (context instanceof Listener) { this.activityCallback = (Listener) context; @@ -562,7 +552,7 @@ public class WalletFragment extends Fragment //TODO figure out why gunther disappears on return from send although he is still set if (enable) { if (streetGunther == null) - streetGunther = ContextCompat.getDrawable(getContext(), R.drawable.ic_gunther_streetmode); + streetGunther = ContextCompat.getDrawable(Objects.requireNonNull(getContext()), R.drawable.ic_gunther_streetmode); ivStreetGunther.setImageDrawable(streetGunther); } else ivStreetGunther.setImageDrawable(null); diff --git a/app/src/main/java/com/m2049r/xmrwallet/fragment/send/SendFragment.java b/app/src/main/java/com/m2049r/xmrwallet/fragment/send/SendFragment.java index 6e6539b2..d480cc74 100644 --- a/app/src/main/java/com/m2049r/xmrwallet/fragment/send/SendFragment.java +++ b/app/src/main/java/com/m2049r/xmrwallet/fragment/send/SendFragment.java @@ -55,6 +55,7 @@ import com.m2049r.xmrwallet.widget.DotBar; import com.m2049r.xmrwallet.widget.Toolbar; import java.lang.ref.WeakReference; +import java.util.Objects; import timber.log.Timber; @@ -311,7 +312,7 @@ public class SendFragment extends Fragment SparseArray> myFragments = new SparseArray<>(); public SpendPagerAdapter(FragmentManager fm) { - super(fm); + super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); } public void addSuccess() { @@ -546,12 +547,12 @@ public class SendFragment extends Fragment final MaterialContainerTransform transform = new MaterialContainerTransform(); transform.setDrawingViewId(R.id.fragment_container); transform.setDuration(getResources().getInteger(R.integer.tx_item_transition_duration)); - transform.setAllContainerColors(ThemeHelper.getThemedColor(getContext(), R.attr.colorSurface)); + transform.setAllContainerColors(ThemeHelper.getThemedColor(Objects.requireNonNull(getContext()), R.attr.colorSurface)); setSharedElementEnterTransition(transform); } @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.send_menu, menu); super.onCreateOptionsMenu(menu, inflater); }