无法调用notifydatasetchanged

问题描述 投票:-1回答:2

我有一项活动是开始活动的结果和一个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();
            }
        }
    }
android arraylist onactivityresult
2个回答
1
投票

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


0
投票

确保两件事:

1 ADD_NEW_ITEM等于1

你完成它之前有没有setResult(RESULT_OK, intent);(Create_Item_Activity)?

© www.soinside.com 2019 - 2024. All rights reserved.