Невозможно обновить список с помощью notifydatasetchanged при удалении элемента из массива

У меня возникла проблема с обновлением моего списка при удалении элементов при длинном щелчке. Похоже, что элементы из списка массивов удаляются, но адаптер не обновляется сразу, хотя я вызываю adapter.notifydatasetchanged. Не могу понять, почему адаптер не устанавливает новые значения. Любая помощь очень ценится.

public class MySongBookActivity extends ActionBarActivity {
ArrayList<String> test;
ListView list;
private static final String TAG = "MySongBookActivity";
CustomAdapter adapter;


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

    try {
        DataBaseHandler db = new DataBaseHandler(this);
        final ListView list = (ListView) findViewById(R.id.mySongBookListView);
        list.setDivider(null);
        TinyDB tinydb = new TinyDB(getBaseContext());
        final ArrayList<String> test = tinydb.getList("hello");

        String[] values = test.toArray(new String[0]);

        final CustomAdapter adapter = new CustomAdapter(this,
                R.layout.list_item_row, values);

        list.setAdapter(adapter);

        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                String data = (String) list.getItemAtPosition(position);
                data.toString();
                int hej = list.getCheckedItemPosition();

                Intent i = new Intent(MySongBookActivity.this,
                        SBLyricsActivity.class);
                i.putExtra("titelName", data);
                i.putExtra("pos", position);

                startActivity(i);

            }

        });
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> av, View view,
                    int position, long id) {
                return onLongListItemClick(view, position, id);
            }

            protected boolean onLongListItemClick(View view, int position,
                    long id) {
                Log.i(TAG, "onLongListItemClick id=" + position);
                test.remove(position);
                list.setAdapter(adapter);
                adapter.notifyDataSetChanged();

                Log.i("test.size()", "" + test.size());
                return true;
            }

        });



    } catch (Exception ex) {
        ex.printStackTrace();
    }

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my_song_book, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_my_song_book,
                container, false);
        return rootView;
    }
}

}

Мой класс адаптера:

public class CustomAdapter extends BaseAdapter {

private String[] data;
private Context context;

public CustomAdapter(Context context,int resourceId, String[] data1) {
    super();
    this.data = data1;

    this.context = context;
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int position) {
    return data[position];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = LayoutInflater.from(context).
            inflate(R.layout.list_item_row, parent, false);

    TextView text1 = (TextView) rowView.findViewById(R.id.txtTitle);


    text1.setText(data[position]);


    return rowView;
}

}


person jiggybotz    schedule 26.08.2014    source источник


Ответы (1)


Ваш adapter привязан к String[] values = test.toArray(new String[0]);, это копия test. Поэтому, когда вы меняете test, values не меняется, как и содержимое файла list.

Что вы можете сделать, так это привязать адаптер к самому ArrayList:

public CustomAdapter(Context context,int resourceId, ArrayList<String> data1) {
    this.data = data1; // this.data should be List<String>
    this.context = context;
}

// change other methods accordingly

Итак, чтобы инициализировать адаптер, вы делаете:

final ArrayList<String> test = tinydb.getList("hello");

final CustomAdapter adapter = new CustomAdapter(this,
        R.layout.list_item_row, test);

Также не обязательно звонить list.setAdapter(adapter); в onLongListItemClick() (думаю, вы это сделали от безысходности)

person Anton Savin    schedule 26.08.2014
comment
Спасибо! Совершенно очевидно теперь, оглядываясь назад. - person jiggybotz; 26.08.2014