java - Android Intent Bundle 传递始终返回 null

标签 java android string list bundle

我正在尝试将文本从自定义对话框传递到家庭 Activity 。 bundle 总是显示为空,而不是我试图传递的值,我不明白为什么。我尝试过查看类似的问题,但尚未找到解决方案。

对话框

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_ingredients_dialog);

    Button addButton = findViewById(R.id.addButton);
    addButton.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(AddIngredientsDialog.this,
                            android.R.layout.select_dialog_item, fruits);
                    editText.setAdapter(arrayAdapter);
                    text = editText.getText().toString();

                    Intent intent = new Intent(AddIngredientsDialog.this, AddIngredientsActivity.class);
                    intent.putExtra("Text", text);
                    startActivity(intent);
                    dialog.dismiss();
            }

     });
}

首页 Activity

 ingredientList = findViewById(R.id.listView);
 ArrayList<String> ingredients = new ArrayList<>();
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_ingredients);

    //bundle
    Bundle extras = getIntent().getExtras();
    text = extras.getString("Text");

    button = findViewById(R.id.add);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            ingredients.add(text);
            adapter = new ArrayAdapter<>(AddIngredientsActivity.this, android.R.layout.simple_list_item_1, ingredients);
            ingredientList.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    });
}

最佳答案

在您的家庭 Activity 中,尝试使用 getIntent().getStringExtra("Text"),而不是 extras.getString("Text");

//bundle
text = getIntent().getStringExtra("Text")

关于java - Android Intent Bundle 传递始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59799477/

相关文章:

java - java中的通配符和类型参数边界

java - 最小生成树抛出 NullPointerException

java - 我有一个 ConnectException 由于某种原因没有被捕获

android - 带有条件的 JSON 文件的自动完成列表

c - 节点创建 C

c - 在c中打印char数组的元素

java - 2D Raytracer 算法

java - Tika - 从文档中检索主要内容

java - 无法实例化 Activity ComponentInfo 无法实例化类

java - 当 AccountNo 大于 15 位或 X 位时删除尾随零