从活动

时间:2017-10-28 18:47:10

标签: java android arraylist android-fragmentactivity

我正在尝试通过创建一个可以删除项目的简单购物清单来了解现在在Fragments with Activities之间来回传递数据。杂货店ArrayList将与活动一起存在于删除按钮中,Fragment将显示ArrayList。当应用程序启动并加载所有内容时,用户将能够从Fragment中的列表中选择一个项目。当用户点击Delete时,ArrayList中的所选项目将被删除,Fragment将重新加载更新的列表。

我可以启动应用程序,所有内容都正确加载,直到我删除一个项目。该项删除(我有一个要检查的日志),但我需要找到一种方法来更新片段中的ArrayList。当我再次尝试删除其他项目时,应用程序崩溃。

这是我的logcat:

java.lang.IllegalStateException: The content of the adapter has 
changed but ListView did not receive a notification. Make sure 
the content of your adapter is not modified from a background 
thread, but only from the UI thread. Make sure your adapter calls 
notifyDataSetChanged() when its content changes. [in ListView(2131427424,
class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]

这是我的主要活动:

public class MainActivity extends AppCompatActivity implements Tab1.OnDataPass {

public SectionsPageAdapater mSectionsPageAdapter;
ViewPager mViewPager;

ArrayList<String> valuesArray = new ArrayList<String>();

int index = -1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSectionsPageAdapter = new SectionsPageAdapater(getSupportFragmentManager());
    mViewPager = (ViewPager) findViewById(R.id.viewContainer);

    valuesArray.add("apple");
    valuesArray.add("banana");
    valuesArray.add("cherry");
    valuesArray.add("dragon fruit");
    valuesArray.add("eggplant");

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    setupViewPager(mViewPager);
}

@Override
public void onDataPass(Integer indexNum) {
    index = indexNum;
}

public void onClickDelete (View v) {

    if (index >= 0) {
        valuesArray.remove(index);
    }

    index = -1;
}

private void setupViewPager(ViewPager viewPager) {
    SectionsPageAdapater adapter = new SectionsPageAdapater(getSupportFragmentManager());
    adapter.addFragment(new Tab1(), "TAB1");
    viewPager.setAdapter(adapter);
}

public ArrayList<String> getDataLog() {
    return valuesArray;
}
}

我的片段:

public class Tab1 extends Fragment {
Button btnPass, btnPass2;
ListView listview;
ArrayList<String> valuesArray = new ArrayList<String>();

int index = -1;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_tab1,container,false);

    btnPass = view.findViewById(R.id.btnPass);
    btnPass2 = view.findViewById(R.id.btnPass2);

    listview = view.findViewById (R.id.listview);

    MainActivity activity = (MainActivity) getActivity();
    valuesArray = activity.getDataLog();


    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
            android.R.layout.simple_list_item_1, valuesArray);
    listview.setAdapter(adapter);

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
            index = (int) id;
            passData((index));
        }
    });

    return view;
}



OnDataPass dataPasser;

public interface OnDataPass {
    void onDataPass(Integer index);
}

@Override
public void onAttach(Context a) {
    super.onAttach(a);
    dataPasser = (OnDataPass) a;
}

public void passData(Integer index) {
    dataPasser.onDataPass(index);
}
}

我的适配器:

public class SectionsPageAdapater extends FragmentPagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}

public SectionsPageAdapater(FragmentManager fm) {
    super(fm);
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}
}

2 个答案:

答案 0 :(得分:1)

在Android中,每个ListView对象都有一个对应的Adapter对象,该对象实际上保存数据并将View传递给ListView以显示它。需要注意的是每次数据,适配器保持更改时,您必须明确调用适配器的notifyDatasetChanged方法,以确保您的ListView对象得到通知更改并处理相应的UI更新。

因此,在您的情况下,您应该将您的ArrayAdapter对象存储在Activity类中,并将其传递给Fragment而不是保存数据的实际ArrayList。每当用户按下删除按钮时,将调用onClickDelete方法。在该方法中,在改变实际的ArrayList之后,应该调用适配器的notifyDatasetChanged方法。

答案 1 :(得分:0)

设置Fragment / Activity关系,以便:

  • 当您致电passData时,您会传递position而不是id值:。

    public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
        passData(position);
    }
    /* Activity */
    @Override
    public void onDataPass(int index) {
        this.indexToDelete = index;   
    }
    
  • 当您致电onClickDelete时,请移除该元素,然后在适用于您notifyDataSetChanged()的适配器上拨打ListView。要做到这一点,你需要引用你的Fragment(如果使用ViewPager,这比使用起来有点棘手),或者你需要使用像EventBus这样的替代机制。在这里,您只需存储对Tab1的引用:

    //Instance variable
    Tab1 tab1;
    //...
    
    private void setupViewPager(ViewPager viewPager) {
        SectionsPageAdapater adapter = new SectionsPageAdapater(getSupportFragmentManager());
        tab1 = new Tab1();
        adapter.addFragment(tab1, "TAB1");
        viewPager.setAdapter(adapter);
    }
    

然后......

public void onClickDelete (View v) {
      if(indexToDelete < 0 || indexToDelete >= valuesArray.size()) {
          return; //invalid index
      }
      valuesArray.remove(indexToDelete);
      tab1.listView.getAdapter().notifyDataSetChanged();
}