无法调用notifydatasetchanged

时间:2017-12-20 14:29:28

标签: android arraylist onactivityresult

我有一项活动,其中包括一个开始活动和一个活动结果。在onactivityresult我可以将返回的数据设置为变量,然后将这些变量添加到我的arraylist,我似乎无法做到的是在此之后使用myAdapter.notifydatasetchanged(),只是得到一个无法解析的符号。是因为我在oncreate中创建并声明了数组,并且onactivityresult不在oncreate中?

下面的代码段......

在oncreate中完成

/*create array adapter and set to listview*/
    final ArrayAdapter<String> myadapter = new ArrayAdapter<>(ListView_Activity.this, R.layout.simple_list_item_1, R.id.row_item_text_view, mylistarray);
    final ListView mylistview = findViewById(R.id.mylistview);
    mylistview.setAdapter(myadapter);
    mylistarray.add("Test");
    myadapter.notifyDataSetChanged();

    final FloatingActionButton additembutton = findViewById(R.id.floatingActionButton);
    additembutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent additem = new Intent(ListView_Activity.this, Create_Item_Activity.class);
            startActivityForResult(additem, 1);
        }
    });

然后在oncreate之外检索数据;

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if (requestCode == ADD_NEW_ITEM){
            if (resultCode == Activity.RESULT_OK) {
                tempdescr = data.getStringExtra("tempdescr");
                tempname = data.getStringExtra("tempname");
                mylistarray.add(tempdescr);
                mylistarray.add(tempname);
                myadapter.notifyDataSetChanged();


            }
            if (resultCode == Activity.RESULT_CANCELED) {
                Toast replacewithcode = Toast.makeText(ListView_Activity.this, "replace with code", Toast.LENGTH_SHORT);
                replacewithcode.show();
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

您正在丢失数组引用。将数组创建为全局变量并直接添加元素。 看看这个:ArrayAdapter.NotifyDataSetChanged() is not working?

答案 1 :(得分:0)

确保两件事:

1 ADD_NEW_ITEM等于1

2你在完成它之前setResult(RESULT_OK, intent);(Create_Item_Activity)?