android - 如何将数据从 Activity 传递到已创建的 Fragment?
问题描述
最近我被卡住了!我有一个 Activity(不是我的 MainActivity,我的意思是,它不是我创建这个 Fragment 的地方),我需要传递一些数据。我已经尝试使用 Bundle,使用 getter 传递,但出现了同样的问题:“尝试在空对象上调用虚拟方法 {...}。” 在我在 Fragment 中调用 Bundle 的那一行。我是新手,所以如果这是一个简单的问题并且我不明白,我很抱歉。在我的代码的相关部分下方:
在活动(不是主要活动):
public void save(){
myGoal = spinnerGoals.getSelectedItem().toString();
Bundle bundle = new Bundle();
bundle.putString("goal", myGoal);
GoalFragment goalFragment = new GoalFragment();
goalFragment.setArguments(bundle);
}
在片段上(我想把这个“目标”放在哪里)
private TextView goal;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate( R.layout.fragment_goal, container, false);
goal = view.findViewById(R.id.myGoalText);
Bundle bundle = getArguments();
if (bundle != null) {
final String myGoal = bundle.getString("goal");
goal.setText(myGoal);
}
return view;
}
在 MainActivity(我创建片段的地方):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment() )
.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_goal:
selectedFragment = new GoalFragment();
break;
case R.id.nav_info:
selectedFragment = new InfoFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment)
.commit();
return true;
}
};
拜托,我已经浪费了很多时间试图自己解决这个问题哈哈哈。如果有人可以帮助我,我将不胜感激!
解决方案
如果活动(不是主要活动)是从您的片段创建的,您可以使用
startActivityForResult()
活动结束后接收数据的方法,在这里阅读更多
如果不是这种情况,您需要使用Preferences
或持久化数据(在存储中)Room Database
推荐阅读
- android - Flutter App在打开相机时崩溃模拟器
- c# - Dotnet 核心 SmtpClient - 在 SendCompletedEventHandler 上的数据库中插入数据
- python - 使用 ALBERT (huggingface-transformers) 运行 SQuAD 脚本
- android - Firebase Firestore 查询帮助 android stuido java
- java - 使用 StAX 验证 XML 时尝试从自定义错误处理程序抛出自定义异常时出现问题
- file - 有没有办法与 ssh 云终端共享文件?
- wordpress - wordpress 用户注册表格或联系表格 7
- go - 从 url 获取空参数
- r - 层次聚类 - 查找每个组中的观察值
- python-3.6 - ParseError:第 5 行的错误输入