简体   繁体   English

Android Intent Bundle 传递返回始终为 null

[英]Android Intent Bundle passing returns always null

I am trying to pass text from a custom dialog to the home activity.我正在尝试将文本从自定义对话框传递到主页活动。 The bundle always comes up as null instead of the value I'm trying to pass and I can't figure out why.捆绑包总是出现 null 而不是我试图传递的值,我不知道为什么。 I've tried looking at similar questions but I have yet to find a solution.我试过查看类似的问题,但我还没有找到解决方案。

Dialog对话

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

     });
}

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

In your home activity, try using getIntent().getStringExtra("Text") , instead of extras.getString("Text");在您的家庭活动中,尝试使用getIntent().getStringExtra("Text") ,而不是extras.getString("Text");

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

Problem could be here问题可能在这里

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

Make sure you've written something in EditText确保你在 EditText 中写了一些东西

It is better using startActivityForResult to start your dialog Activity.最好使用 startActivityForResult 来启动对话框活动。 Check this answer Sending data back to the Main Activity in Android检查这个答案Sending data back to the Main Activity in Android

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM