2

我正在尝试将自定义对话框中的文本传递给家庭活动。捆绑包总是显示为 null 而不是我试图传递的值,我不知道为什么。我试过查看类似的问题,但我还没有找到解决方案。

对话

@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();
            }

     });
}

家庭活动

 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();
        }
    });
}
4

3 回答 3

0

问题可能在这里

`text = editText.getText().toString();`

确保你已经在 EditText 中写了一些东西

于 2020-01-18T11:21:17.410 回答
0

最好使用 startActivityForResult 来启动对话活动。检查这个答案将数据发送回Android中的主要活动

于 2020-01-18T11:30:27.423 回答
0

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

//bundle
text = getIntent().getStringExtra("Text")
于 2020-01-18T10:19:29.770 回答