[英]Android Intent Bundle passing returns always null
我正在嘗試將文本從自定義對話框傳遞到主頁活動。 捆綁包總是出現 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();
}
});
}
在您的家庭活動中,嘗試使用getIntent().getStringExtra("Text")
,而不是extras.getString("Text");
//bundle
text = getIntent().getStringExtra("Text")
問題可能在這里
`text = editText.getText().toString();`
確保你在 EditText 中寫了一些東西
最好使用 startActivityForResult 來啟動對話框活動。 檢查這個答案Sending data back to the Main Activity in Android
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.