Home > Mobile >  How to send data to antoher class
How to send data to antoher class

Time:06-17

How can I change textview in another class with storageCointainer method? I want to get data from storageCointainer method to change textview in HomeFragment class.

public void getSavedMoney() {
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String money = ds.child("saveMoney").getValue().toString();
                moneyStringList.add(money);
            }
            moneyNumList = Lists.transform(moneyStringList, Double::parseDouble);
            savedMoney = moneyNumList.stream().mapToDouble(Double::doubleValue).sum();
            storageContainer(savedMoney);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

public void storageContainer(double savedMoney) {
    this.savedMoney = savedMoney;
}

CodePudding user response:

You can pass the value by using Bundle. You can refer to this link https://stackoverflow.com/a/9245510/9346054

For you case, you can create the instance like below.

public static HomeFragment newInstance(final Double savedMoney) {
    final HomeFragment homeFragment = new HomeFragment();
    final Bundle args = new Bundle();
    args.putDouble("savedMoney", savedMoney);
    homeFragment.setArguments(args);
    return homeFragment;
}

Next, implement it at the storageContainer method like this.

public void storageContainer(double savedMoney) {
    this.savedMoney = savedMoney;
    newInstance(savedMoney);
}

At the HomeFragment, you can get the value at onCreate. Example as below

final Double savedMoney = getArguments().getDouble("savedMoney", 0);
//Display at the textView
tvSavedMoney.setText("Total: "   savedMoney);

CodePudding user response:

If you want to send the value savedMoney to another activity, you should consider sending it only when it's ready. A typical way of sending the data would be through an Intent. So in code should look like this:

public void getSavedMoney() {
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String money = ds.child("saveMoney").getValue().toString();
                moneyStringList.add(money);
            }
            moneyNumList = Lists.transform(moneyStringList, Double::parseDouble);
            savedMoney = moneyNumList.stream().mapToDouble(Double::doubleValue).sum();
            //storageContainer(savedMoney); //           
  • Related