之前得到一個真正的答案,我想展現給你的代碼的一些改進。 首先,創建一個Intent(或者當你需要在一般情況下),從活動中沒有必要調用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()
你最終會在第一Activitys 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()
- 方法與項目,如上所述。
你在onResume()方法中有代碼嗎?通常onResume將被調用來進行後續的活動調用。 – kosa
不,加載列表的動作是在onCreate()方法中。 – AuTi
嘗試在onResume()中添加同樣的東西並查看。 – kosa