Android ArrayList未按预期添加项目

huangapple go评论83阅读模式
英文:

android ArrayList not adding items as expected

问题

代码部分已翻译如下:

 public class NavigationDrawer extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, Communicator {
    .
    .
    .
    
     public void sendToBill(Items items) {
            HomeFragment homeFragment = new HomeFragment();
            homeFragment.addToBill(items);
        }
    
    
    }
    
    
    public class HomeFragment extends Fragment {
    private ArrayList<Items> billList = new ArrayList<>();
    .
    .
    .
    
     public void addToBill(Items item) {
            billList.add(item);
    
        }
    }

and from here am calling it
  
    final Communicator communicator = (Communicator) getActivity();
      communicator.sendToBill(item);

and i can see the log but it is always one item

Logs : 

    2020-10-16 06:53:56.363 16662-16662/com.example.iszo_dev D/counting: White wine dry 
英文:

Code :
public class NavigationDrawer extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, Communicator {
.
.
.

 public void sendToBill(Items items) {
        HomeFragment homeFragment = new HomeFragment();
        homeFragment.addToBill(items);
    }


}



public class HomeFragment extends Fragment {
private ArrayList&lt;Items&gt; billList = new ArrayList&lt;&gt;();
.
.
.

 public void addToBill(Items item) {
        billList.add(item);

    }
}

and from here am calling it

final Communicator communicator = (Communicator) getActivity();
  communicator.sendToBill(item);

and i can see the log but it is always one item

Logs :

2020-10-16 06:53:56.363 16662-16662/com.example.iszo_dev D/counting: White wine dry 

答案1

得分: 1

你实际上每次调用sendToBill(item)函数时都在创建一个新的HomeFragment对象引用,这最终会导致每次初始化HomeFragment,并在初始化HomeFragment的billsList时,结果每次调用sendToBill函数后只会有一个最新的项目。

你需要在NavActivity中创建一个单一的全局HomeFragment引用,而不是每次都创建一个新的引用。

英文:

You're actually creating a new object reference of HomeFragment every time you call the sendToBill(item) function which eventually initialize your HomeFragment every time and initializes your HomeFragment's billsList also in result there will be only one latest item every time after calling the sendToBill function.

You have to make a single global reference of HomeFragment in your NavActivity rather than creating a new reference each time.

huangapple
  • 本文由 发表于 2020年10月16日 21:58:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64390648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定