如何使用bundle将数据从Activity传递到Fragment

Fra*_*sco 1 android android-fragments

我对 Android 完全陌生,我必须提交这个应用程序才能结束我的大学学位,但我遇到了这个问题,我的片段使我的整个应用程序崩溃。

\n\n

为了解释我到目前为止所做的事情是,我有一个 LoginActivity,其中我通过 Intent 发送了 userId,并且在我的 DashboardActivity 上有当前用户的 id(并且我可以显示它),但是在 DashboardActivity 中我有一个底部导航到我的 FormFragment 和 DataFragment 的导航栏。

\n\n

现在,我希望将当前用户的 userId 值从 DashboardActivity 传递到我的 DataFragment,以便我可以根据 userId 动态显示用户数据。

\n\n

因此,我发现最好的选择是使用捆绑包,但我现在不知道为什么(因为我对此完全陌生)每次从 FormFragment 切换到 DataFragment 时我的应用程序都会崩溃。

\n\n

你能帮助我吗?我很绝望xD

\n\n

这是我的 DashboardActivity 代码:

\n\n
public class PainelActivity extends AppCompatActivity {\n\n    private Button buttonLogout;\n    private TextView textViewId;\n    private Object DashboardFragment;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_painel);\n        BottomNavigationView navView = findViewById(R.id.nav_view);\n        // Passing each menu ID as a set of Ids because each\n        // menu should be considered as top level destinations.\n        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(\n                R.id.navigation_home, R.id.navigation_dashboard)\n                .build();\n        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);\n        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);\n        NavigationUI.setupWithNavController(navView, navController);\n\n        // gets the id from the Intent\n        Intent get = getIntent();\n        String userId = get.getStringExtra(LoginActivity.EXTRA_ID);\n\n        // Send the id to the Fragments\n        Bundle bundle = new Bundle();\n        bundle.putString("userId", userId);\n        Fragment fragment = new Fragment();\n        fragment.setArguments(bundle);\n        getSupportFragmentManager().beginTransaction()\n                .add(R.id.nav_host_fragment, fragment).commit();\n\n        // see the id on the screen\n        textViewId = findViewById(R.id.textViewId);\n        textViewId.setText(userId);\n\n        // logout\n        buttonLogout = findViewById(R.id.logoutButton);\n        buttonLogout.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                openMainActivity();\n            }\n        });\n    }\n    public void openMainActivity() {\n        Intent HomePage = new Intent(this, MainActivity.class);\n        startActivity(HomePage);\n\n        Toast.makeText(PainelActivity.this, "Terminou a sua sess\xc3\xa3o.",\n                Toast.LENGTH_LONG).show();\n    }\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的 DataFragment 代码:

\n\n
public class DashboardFragment extends Fragment {\n    INodeJS myAPI;\n    private TextView textViewResult;\n\n    public View onCreateView(@NonNull LayoutInflater inflater,\n                             ViewGroup container, Bundle savedInstanceState) {\n        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);\n\n        //Init API\n        Retrofit retrofit = RetrofitClient.getInstance();\n        myAPI = retrofit.create(INodeJS.class);\n        textViewResult = root.findViewById(R.id.text_view_result);\n\n        // gets the id from the activity\n        if (getArguments() != null) {\n            String userId = getArguments().getString("userId");\n            int uid = Integer.parseInt(userId);\n\n            Call<List<DataResult>> call = myAPI.executeGetData(uid);\n\n            call.enqueue(new Callback<List<DataResult>>() {\n                @Override\n                public void onResponse(Call<List<DataResult>> call, Response<List<DataResult>> response) {\n                    if (response.code() == 200) {\n                        List<DataResult> DATA = response.body();\n\n                        for (DataResult data: DATA) {\n                            String content = "";\n                            content += "Data: " +data.getDta() + "\\n";\n                            content += "Hora: " +data.getHora() + "\\n";\n                            content += "Glic\xc3\xa9mia: " +data.getIndiceGlicemia() + "\\n";\n                            content += "Insulina: " +data.getInsulina() + "\\n";\n                            content += "Medica\xc3\xa7\xc3\xa3o: " +data.getMedicacao() + "\\n\\n";\n\n                            textViewResult.append(content);\n                        }\n                    }\n                }\n\n                @Override\n                public void onFailure(Call<List<DataResult>> call, Throwable t) {\n                    textViewResult.setText(t.getMessage());\n                }\n            });\n        }\n\n        return root;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

谢谢你,祝你有美好的一天!

\n\n

(我刚刚编辑了我的代码并更新了我的问题,现在,我的应用程序没有崩溃,但我没有看到数据。)

\n

小智 5

创建捆绑包时:

Bundle bundle = new Bundle();
bundle.putString("userId", userId);
Fragment fragment = new Fragment();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
            .replace(R.id.fragment_placeholder_id, dataFragment, "anyTagName").commit();
Run Code Online (Sandbox Code Playgroud)

要获取片段中的数据:

if (getArguments != null) {
    String userId = getArguments().getString("userId");
}
Run Code Online (Sandbox Code Playgroud)