gpt4 book ai didi

java - 通过包从 Activity 向 Fragment 传递数据时获取 null

转载 作者:行者123 更新时间:2023-12-02 10:09:35 25 4
gpt4 key购买 nike

通过 bundle 传递数据时丢失数据,我得到

Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference at String bundlePassData = this.getArguments().getString("tagName");

这是我的代码示例。主要 Activity ->

 tagsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bundle bundle = new Bundle();
TextView textView = (TextView) view.findViewById(R.id.tagName);
String selectedItemName = textView.getText().toString();
bundle.putString("tagName", selectedItemName);

TaskAssignFragment taskAssignFragment = new TaskAssignFragment();
taskAssignFragment.setArguments(bundle);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.commit();

getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new TaskAssignFragment()).addToBackStack(null).commit();

Log.i("ListView", selectedItemName);
}
});

任务分配 fragment ->

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_assign, container, false);
TextView test = view.findViewById(R.id.testerView);

String bundlePassData = this.getArguments().getString("tagName");
test.setText(bundlePassData);

return view;
}

我应该尝试接口(interface)吗?但如果我需要数据作为变量,而不仅仅是在函数中,因为我会在我的 fragment 中的更多地方使用它。

最佳答案

在您的代码中,您在替换时正在创建新 fragment 。

TaskAssignFragment taskAssignFragment = new TaskAssignFragment();
taskAssignFragment.setArguments(bundle);

getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new TaskAssignFragment()).addToBackStack(null).commit();

使用您已创建的 fragment 实例并在其中设置参数

  getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
taskAssignFragment).addToBackStack(null).commit();

关于java - 通过包从 Activity 向 Fragment 传递数据时获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55098595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com