0
我想另一項活動後更新ListView
finish()
「與結果上課。初始化(正常工作):的Android ArrayAdapter爲ListView的方法.notifyDataSetChanged()問題
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new DatabaseHelper(this);
objects = databaseHelper.selectObjects();
objectsListView = (ListView) findViewById(R.id.LIST_VIEW_OBJECTS);
objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, objects);
objectsListView.setAdapter(objectArrayAdapter);
}
問題只發生時我試着更新ListView
:
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if(requestCode == SECOND_ACTIVITY_REQUEST) {
if (resultCode == RESULT_OK) {
objects = databaseHelper.selectObjects();
objectArrayAdapter.notifyDataSetChanged();
}
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.TOAST_ERROR_RESULT_CANCELED), Toast.LENGTH_LONG).show();
}
}
}
但此代碼的工作就好了:
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if(requestCode == SECOND_ACTIVITY_REQUEST) {
if (resultCode == RESULT_OK) {
objects.add(newObject);
objectArrayAdapter.notifyDataSetChanged();
}
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.TOAST_ERROR_RESULT_CANCELED), Toast.LENGTH_LONG).show();
}
}
}
此代碼也能正常工作:
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if(requestCode == SECOND_ACTIVITY_REQUEST) {
if (resultCode == RESULT_OK) {
objects = databaseHelper.selectObjects();
objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, objects);
objectsListView.setAdapter(objectArrayAdapter);
}
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.TOAST_ERROR_RESULT_CANCELED), Toast.LENGTH_LONG).show();
}
}
}
我的問題是:爲什麼第一種方法不能按預期工作?第二個和第三個似乎是一個工作輪不是嗎?
,我真的很抱歉!我試圖簡化這個問題的代碼。 '問卷'='對象'。 '兩個例子中的ArrayList'都是相同的(現在更新)。對不起... – 2014-11-04 21:10:44
哦好吧,我不知道,但我認爲obectsListView本身需要在調用onNotifyDataSetChanged之前進行操作。例如:objectsListView.clear,.add等 – Lukos 2014-11-04 21:51:16
嗯...我真的不這麼認爲,因爲我之前成功地完成了類似的功能。不同之處在於我將數據添加到數組中,如下所示:'objects.add(newObject);'。這裏'objectsListView'也不會被操縱,不是嗎? – 2014-11-05 05:31:28