Прежде чем получить реальный ответ, я хотел бы показать некоторые улучшения в вашем коде.Во-первых, при создании Намерения (или когда вам нужен контекст в целом) из Деятельности нет необходимости вызывать getBaseContext()
, вы можете просто использовать this
:
intent = new Intent(this, NewTestActivity.class);
Во-вторых, Android - этохорошо справляется с заданиями, вам не нужно закрывать первое действие вручную с помощью finish()
.Android автоматически приостановит или остановит ваше первое действие и вернет его, когда вы вернетесь к нему.
В-третьих, в вашем случае вы можете использовать startActivityForResult()
вместо startActivity()
по причинам, которые я объясню ниже.
Это сделает ваш код похожим на следующее:
private static final int MY_REQUEST_CODE = 33487689; //put this at the top of your Activity-class, with any unique value.
intent = new Intent(this, NewTestActivity.class);
startActivityForResult(intent, MY_REQUEST_CODE);
Теперь startActivityForResult()
запускает действие и ожидает результата от этого нового действия.Когда вы позвоните finsih()
в новом действии, вы окажетесь в первом методе действий onActivityResult()
с данными, предоставленными из нового Activty, который сейчас закрыт:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != MY_REQUEST_CODE) return; //We got a result from another request, so for this example we can return.
if(resultCode != RESULT_OK) return; //The user aborted the action, so we won't get any data.
//After the above if-statements we know that the activity that gives us a result was requested with the correct request code, and it's action was successful, we can begin extracting the data, which is in the data-intent:
Item item = (Item) data.getSerializableExtra("customData"); //casts the data object to the custom Item-class. This can be any class, as long as it is serializable. There are many other kinds of data that can be put into an intent, but for this example a serializable was used.
itemList.add(item); //This is the list that was specified in onCreate()
//If you use an Adapter, this is the place to call notifyDataSetChanged();
}
Чтобы все это работалонам нужно сделать некоторые вещи во втором упражнении: когда элемент создан, мы должны установить результат:
//We begin by packing our item in an Intent (the Item class is an example that is expected to implement Serializable)
Item theCreatedItem; //This is what was created in the activity
Intent data = new Intent();
data.putSerializable(theCreatedItem);
setResult(RESULT_OK, data);
finish();
Это должно вернуться к первому методу Activitys onActivityResult()
с элементом,как объяснено выше.