英文:
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<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
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论