<p>Remove block for else if in that you have used useTor(), it doesnt need at all</p>

CC BY-SA 3.0
2018-03-12T08:54:15.123Z
2018-03-12T08:54:15.123Z
Shubham
<p>I work with a bitcoin wallet app and the UI looks, </p>

<p><a href="https://i.sstatic.net/BRbCu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BRbCu.png" alt="enter image description here"></a></p>

<p>When I select an address from the dropdown menu and would press the <code>balance</code> or the <code>transaction</code> buttons, they should open in the new page and show respective info. </p>

<p><a href="https://i.sstatic.net/Vs9bU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Vs9bU.png" alt="enter image description here"></a> </p>

<p>When I receive the BTC in certain wallet, it should update the <code>balance</code> of the wallet in the active page. However, it doesn't work as expected and I only 0 BTC as always. Previously, it was juts one wallet (no multi-wallet support) and that time the same code just work fine. </p>

<p>The class that setup the wallet, </p>

<pre><code>public class WalletManager {

    public static WalletAppKit bitcoin;

    private static WalletManager walletManager;

    // public static NetworkParameters networkParameters = MainNetParams.get();
    public static NetworkParameters networkParameters = TestNet3Params.get();

    public static final String APP_NAME = "WalletTemplate";

    public static final String WALLET_FILE_NAME = APP_NAME.replaceAll("[^a-zA-Z0-9.-]", "_")
            + networkParameters.getPaymentProtocolId();

    private static final Logger logger = LoggerFactory.getLogger(WalletManager.class);

    private WalletModel model = new WalletModel();

    private List&lt;WalletSetupCompletedListener&gt; setupCompletedListeners = Collections.synchronizedList(new LinkedList&lt;&gt;());

    public static WalletManager setupWallet(final String walletName) {

        logger.info("Setup Wallet");

        walletManager = new WalletManager();

        walletManager.setupWalletKit(walletName);

        try {

            if (walletManager.bitcoin.isChainFileLocked()) {
                return walletManager;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return walletManager;
        }

        walletManager.bitcoin.startAsync();

        return walletManager;
    }

    private WalletManager() {}

    protected File getWalletDirectory(final String walletId) {

        File dir = new File(walletId);

        if (!dir.exists()) {
            dir.mkdir();
        }

        return dir;
    }

    private void setupWalletKit(final String walletId) {

        File directory = getWalletDirectory(walletId);

        // if the seed is not null, that means we are restoring from the backup
        bitcoin = new WalletAppKit(networkParameters, directory, WALLET_FILE_NAME) {

            @Override
            protected void onSetupCompleted() {

                // Don't make the user wait for confirmations
                // they're sending their own money anyway!!
                bitcoin.wallet().allowSpendingUnconfirmedTransactions();

                Wallet wallet = bitcoin.wallet();

                model.setWallet(wallet);

                setupCompletedListeners.forEach(listener -&gt; listener.onSetupCompleted(wallet));
            }
        };

        // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
        // or progress widget to keep the user engaged whilst we initialise, but we don't.
        if (networkParameters == RegTestParams.get()) {
            bitcoin.connectToLocalHost();   // You should run a regtest mode bitcoind locally.
        } else if (networkParameters == TestNet3Params.get()) {
            bitcoin.useTor();
        }

        bitcoin.setDownloadListener(model.getSyncProgressUpdater())
                .setBlockingStartup(false)
                .setUserAgent(APP_NAME, "1.0");
    }

    public WalletAppKit getWalletAppKit() {
        return bitcoin;
    }

    public WalletModel getModel() {
        return model;
    }

    public void addWalletSetupCompletedListener(final WalletSetupCompletedListener listener) {
        setupCompletedListeners.add(listener);
    }
}
</code></pre>

<p>The class responsible for the wallet updating is provided below, </p>

<pre><code>public class WalletModel {

    private List&lt;Transaction&gt; transactions = Collections.synchronizedList(new ArrayList&lt;&gt;());

    private ProgressBarUpdater syncProgressUpdater = new ProgressBarUpdater();

    private static double SYNCHRONISATION_FINISHED = 1.0;

    private double syncProgress = -1.0;

    private Coin balance = Coin.ZERO;

    private Address address;

    private String transaction;

    private int UserId;

    public int getUserId() {
        return UserId;
    }

    public void setUserId(int userId) {
        this.UserId = userId;
    }

    public String getTransaction() {
        return transaction;
    }

    public void setTransaction(String transaction) {
        this.transaction = transaction;
    }

    private List&lt;String&gt; history = new ArrayList&lt;&gt;();

    public List&lt;String&gt; getHistory() {

        for (Transaction t : transactions) {
            history.add(addTransactionHistory(t));
        }

        return history;
    }

    public WalletModel() {
    }

    public WalletModel(Wallet wallet) {

        setWallet(wallet);
    }

    private void update(Wallet wallet) {

        this.balance = wallet.getBalance();

        this.address = wallet.currentReceiveAddress();

        transactions.addAll(wallet.getRecentTransactions(100,
                true));

        this.transaction = Objects.isNull(transactions) || transactions.isEmpty()
                ? "" : String.valueOf(transactions.get(0));
    }

    public boolean setWallet(Wallet wallet) {

        try {
            wallet.addChangeEventListener(new WalletChangeEventListener() {
                @Override
                public void onWalletChanged(Wallet wallet) {
                    update(wallet);
                }
            });
            update(wallet);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    private class ProgressBarUpdater extends DownloadProgressTracker {

        @Override
        protected void progress(double percentage, int blocksSoFar, Date date) {
            super.progress(percentage, blocksSoFar, date);
            syncProgress = percentage / 100.0;
        }

        @Override
        protected void doneDownload() {
            super.doneDownload();
            syncProgress = SYNCHRONISATION_FINISHED;
        }
    }

    public boolean isSyncFinished() {
        return syncProgress == SYNCHRONISATION_FINISHED;
    }

    public Address getAddress() {
        return address;
    }

    /**
     * @param
     * @return the Satoshi coin based on the wallet balance
     */
    public Coin getBalance() {
        return balance;
    }

    /**
     * @return get the BTC amount as float from the wallet balance
     */
    public float getBalanceFloatFormat() {

        float bal = (float) balance.getValue();
        float fac = (float) Math.pow(10, 8);

        float result = bal / fac;
        return result;
    }

    /**
     * @param transaction take the wallet transaction as an input
     * @return the trasaction info of the wallet
     */
    private String addTransactionHistory(Transaction transaction) {

        if (Objects.isNull(transaction)) {
            return "No transaction";
        }

        Coin value = transaction.getValue(WalletManager.bitcoin.wallet());

        if (value.isPositive()) {
            String message = "Incoming payment of " + MonetaryFormat.BTC.format(value);
            return message;
        } else if (value.isNegative()) {
            Address address = transaction.getOutput(0).getAddressFromP2PKHScript(networkParameters);
            String message = "Outbound payment to " + address + " worth of " +
                    (MonetaryFormat.BTC.format(value)).toString().replaceAll("-", "");
            return message;
        }

        String message = "Payment with id " + transaction.getHash();
        return message;
    }

    public double getSyncProgress() {
        return syncProgress;
    }

    public ProgressBarUpdater getSyncProgressUpdater() {
        return syncProgressUpdater;
    }

    public List&lt;Transaction&gt; getTransactions() {
        return transactions;
    }
}




public interface WalletSetupCompletedListener {

    void onSetupCompleted(Wallet wallet);
}
</code></pre>

<p>How do I design the code to support the multiple wallet? I can provide the code snipped if requested. </p>

CC BY-SA 3.0
2017-06-27T07:30:35.197Z
We can't possibly know what is wrong with the code without you posting it here.
Ava Chow
CC BY-SA 3.0
2018-03-13T03:39:59.490Z
I've downvoted this question because it is extremely specific to the askers issue and it seems unlikely to be useful to anyone else.
Murch
CC BY-SA 3.0
2018-03-13T04:08:44.727Z
@Murch the forum is for the personal programming questions too
Arefe
CC BY-SA 3.0
2018-03-14T01:07:59.530Z
You're right. I've removed my downvote and edited the title to clarify what people can expect to see when they click this question. Please feel free to further amend it. Also, if you understand what your answerer was trying to tell you, could you edit his answer to make it clearer? I don't even understand what he's trying to tell you.
Murch
<bitcoinj><java><bitcoin-wallet-app>
I'm working to add multiwallet support to Bitcoin Wallet App, but now the balance is no longer updating
Arefe
# I'm working to add multiwallet support to Bitcoin Wallet App, but now the balance is no longer updating

(Asked by: username_0 on 2017-06-27)

I work with a bitcoin wallet app and the UI looks,

[![enter image description here](https://i.sstatic.net/BRbCu.png)](https://i.sstatic.net/BRbCu.png)

When I select an address from the dropdown menu and would press the `balance` or the `transaction` buttons, they should open in the new page and show respective info.

[![enter image description here](https://i.sstatic.net/Vs9bU.png)](https://i.sstatic.net/Vs9bU.png)

When I receive the BTC in certain wallet, it should update the `balance` of the wallet in the active page. However, it doesn't work as expected and I only 0 BTC as always. Previously, it was juts one wallet (no multi-wallet support) and that time the same code just work fine.

The class that setup the wallet,

```
public class WalletManager {

    public static WalletAppKit bitcoin;

    private static WalletManager walletManager;

    // public static NetworkParameters networkParameters = MainNetParams.get();
    public static NetworkParameters networkParameters = TestNet3Params.get();

    public static final String APP_NAME = "WalletTemplate";

    public static final String WALLET_FILE_NAME = APP_NAME.replaceAll("[^a-zA-Z0-9.-]", "_")
            + networkParameters.getPaymentProtocolId();

    private static final Logger logger = LoggerFactory.getLogger(WalletManager.class);

    private WalletModel model = new WalletModel();

    private List<WalletSetupCompletedListener> setupCompletedListeners = Collections.synchronizedList(new LinkedList<>());

    public static WalletManager setupWallet(final String walletName) {

        logger.info("Setup Wallet");

        walletManager = new WalletManager();

        walletManager.setupWalletKit(walletName);

        try {

            if (walletManager.bitcoin.isChainFileLocked()) {
                return walletManager;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return walletManager;
        }

        walletManager.bitcoin.startAsync();

        return walletManager;
    }

    private WalletManager() {}

    protected File getWalletDirectory(final String walletId) {

        File dir = new File(walletId);

        if (!dir.exists()) {
            dir.mkdir();
        }

        return dir;
    }

    private void setupWalletKit(final String walletId) {

        File directory = getWalletDirectory(walletId);

        // if the seed is not null, that means we are restoring from the backup
        bitcoin = new WalletAppKit(networkParameters, directory, WALLET_FILE_NAME) {

            @Override
            protected void onSetupCompleted() {

                // Don't make the user wait for confirmations
                // they're sending their own money anyway!!
                bitcoin.wallet().allowSpendingUnconfirmedTransactions();

                Wallet wallet = bitcoin.wallet();

                model.setWallet(wallet);

                setupCompletedListeners.forEach(listener -> listener.onSetupCompleted(wallet));
            }
        };

        // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
        // or progress widget to keep the user engaged whilst we initialise, but we don't.
        if (networkParameters == RegTestParams.get()) {
            bitcoin.connectToLocalHost();   // You should run a regtest mode bitcoind locally.
        } else if (networkParameters == TestNet3Params.get()) {
            bitcoin.useTor();
        }

        bitcoin.setDownloadListener(model.getSyncProgressUpdater())
                .setBlockingStartup(false)
                .setUserAgent(APP_NAME, "1.0");
    }

    public WalletAppKit getWalletAppKit() {
        return bitcoin;
    }

    public WalletModel getModel() {
        return model;
    }

    public void addWalletSetupCompletedListener(final WalletSetupCompletedListener listener) {
        setupCompletedListeners.add(listener);
    }
}

```

The class responsible for the wallet updating is provided below,

```
public class WalletModel {

    private List<Transaction> transactions = Collections.synchronizedList(new ArrayList<>());

    private ProgressBarUpdater syncProgressUpdater = new ProgressBarUpdater();

    private static double SYNCHRONISATION_FINISHED = 1.0;

    private double syncProgress = -1.0;

    private Coin balance = Coin.ZERO;

    private Address address;

    private String transaction;

    private int UserId;

    public int getUserId() {
        return UserId;
    }

    public void setUserId(int userId) {
        this.UserId = userId;
    }

    public String getTransaction() {
        return transaction;
    }

    public void setTransaction(String transaction) {
        this.transaction = transaction;
    }

    private List<String> history = new ArrayList<>();

    public List<String> getHistory() {

        for (Transaction t : transactions) {
            history.add(addTransactionHistory(t));
        }

        return history;
    }

    public WalletModel() {
    }

    public WalletModel(Wallet wallet) {

        setWallet(wallet);
    }

    private void update(Wallet wallet) {

        this.balance = wallet.getBalance();

        this.address = wallet.currentReceiveAddress();

        transactions.addAll(wallet.getRecentTransactions(100,
                true));

        this.transaction = Objects.isNull(transactions) || transactions.isEmpty()
                ? "" : String.valueOf(transactions.get(0));
    }

    public boolean setWallet(Wallet wallet) {

        try {
            wallet.addChangeEventListener(new WalletChangeEventListener() {
                @Override
                public void onWalletChanged(Wallet wallet) {
                    update(wallet);
                }
            });
            update(wallet);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    private class ProgressBarUpdater extends DownloadProgressTracker {

        @Override
        protected void progress(double percentage, int blocksSoFar, Date date) {
            super.progress(percentage, blocksSoFar, date);
            syncProgress = percentage / 100.0;
        }

        @Override
        protected void doneDownload() {
            super.doneDownload();
            syncProgress = SYNCHRONISATION_FINISHED;
        }
    }

    public boolean isSyncFinished() {
        return syncProgress == SYNCHRONISATION_FINISHED;
    }

    public Address getAddress() {
        return address;
    }

    /**
     * @param
     * @return the Satoshi coin based on the wallet balance
     */
    public Coin getBalance() {
        return balance;
    }

    /**
     * @return get the BTC amount as float from the wallet balance
     */
    public float getBalanceFloatFormat() {

        float bal = (float) balance.getValue();
        float fac = (float) Math.pow(10, 8);

        float result = bal / fac;
        return result;
    }

    /**
     * @param transaction take the wallet transaction as an input
     * @return the trasaction info of the wallet
     */
    private String addTransactionHistory(Transaction transaction) {

        if (Objects.isNull(transaction)) {
            return "No transaction";
        }

        Coin value = transaction.getValue(WalletManager.bitcoin.wallet());

        if (value.isPositive()) {
            String message = "Incoming payment of " + MonetaryFormat.BTC.format(value);
            return message;
        } else if (value.isNegative()) {
            Address address = transaction.getOutput(0).getAddressFromP2PKHScript(networkParameters);
            String message = "Outbound payment to " + address + " worth of " +
                    (MonetaryFormat.BTC.format(value)).toString().replaceAll("-", "");
            return message;
        }

        String message = "Payment with id " + transaction.getHash();
        return message;
    }

    public double getSyncProgress() {
        return syncProgress;
    }

    public ProgressBarUpdater getSyncProgressUpdater() {
        return syncProgressUpdater;
    }

    public List<Transaction> getTransactions() {
        return transactions;
    }
}

public interface WalletSetupCompletedListener {

    void onSetupCompleted(Wallet wallet);
}

```

How do I design the code to support the multiple wallet? I can provide the code snipped if requested.

**Tags:** bitcoinj, java, bitcoin-wallet-app

> **Comments:**
> **username_1**: We can't possibly know what is wrong with the code without you posting it here.  
> **username_2**: I've downvoted this question because it is extremely specific to the askers issue and it seems unlikely to be useful to anyone else.  
> **username_0**: @username_2 the forum is for the personal programming questions too  
> **username_2**: You're right. I've removed my downvote and edited the title to clarify what people can expect to see when they click this question. Please feel free to further amend it. Also, if you understand what your answerer was trying to tell you, could you edit his answer to make it clearer? I don't even understand what he's trying to tell you.  

---

## 1 answers

### Answer by username_3 on 2018-03-12. Score: 2 | Accepted answer

Remove block for else if in that you have used useTor(), it doesnt need at all


---

