ListView不会动态刷新并导致错误

时间:2014-06-01 23:37:02

标签: android listview android-listview

我无法删除ListView中的对象。我一直在尝试从适配器中删除一个对象,然后调用onDataSetChanged();但它似乎从屏幕上删除了该对象。

我可以从数据库中成功删除该对象,但该对象无论如何都会在屏幕上保留。

我相信因为视图没有正确刷新,它允许我继续滑动以关闭列表中的项目并最终导致IndexOutOfBoundsException。

有没有人知道为什么我的ListView无法正确更新?我知道有很多类似于这个的问题,但大多数都将onDataSetChanged()作为一个解决方案,并且它没有'似乎是我的问题。

06-01 19:33:46.734: E/AndroidRuntime(9011): Process: com.example.datetracker, PID: 9011
06-01 19:33:46.734: E/AndroidRuntime(9011): java.lang.IndexOutOfBoundsException:           Invalid index 0, size is 0
06-01 19:33:46.734: E/AndroidRuntime(9011):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
06-01 19:33:46.734: E/AndroidRuntime(9011):     at   java.util.ArrayList.get(ArrayList.java:308)
06-01 19:33:46.734: E/AndroidRuntime(9011):     at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:337)
06-01 19:33:46.734: E/AndroidRuntime(9011):     at com.example.datetracker.MainActivity$1.onDismiss(MainActivity.java:97)
06-01 19:33:46.734: E/AndroidRuntime(9011):     at com.example.datetracker.SwipeDismissListViewTouchListener$3.onAnimationEnd(SwipeDismissListViewTouchListener.java:362)
06-01 19:33:46.734: E/AndroidRuntime(9011):     at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1056)
06-01 19:33:46.734: E/AndroidRuntime(9011):     at android.animation.ValueAnimator.access$400(ValueAnimator.java:50)
06-01 19:33:46.734: E/AndroidRuntime(9011):     at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:644)
06-01 19:33:46.734: E/AndroidRuntime(9011):     at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:660)

MainActivity

public class MainActivity extends FragmentActivity implements OnClickListener {

ListView listView;
int lastIndex = -1;
List<Event> lstEvents = new ArrayList<Event>();

// detail view
TextView tvTitle, tvTime, tvDate;
ImageView ivPic;
View vw_master;

boolean _isBack = true;

ImageButton add;

String title;
String date;
String time;
int resId;

Context context;

static final int PICK_CONTACT_REQUEST = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // // get detail controls
    tvTitle = (TextView) findViewById(R.id.textViewTitle);
    tvDate = (TextView) findViewById(R.id.textViewDate);
    tvTime = (TextView) findViewById(R.id.textViewTime);
    ivPic = (ImageView) findViewById(R.id.imageView1);

    add = (ImageButton) findViewById(R.id.add);
    add.setOnClickListener(this);

    // /////////////////////////////DATABASE/////////////////////////////////////////////
    DatabaseHandler db = new DatabaseHandler(this);
    // /////////////////////////////DATABASE/////////////////////////////////////////////

    // ///////////////////////////////LISTVIEW////////////////////////////////////////
    // Create the adapter to convert the array to views
    EventAdapter adapter = new EventAdapter(this, db.getAllContacts());

    // attach adapter to a list view
    listView = (ListView) findViewById(R.id.listViewFragment);
    listView.setAdapter(adapter);

    context = this;

    SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
            listView,
            new SwipeDismissListViewTouchListener.DismissCallbacks() {

                DatabaseHandler db = new DatabaseHandler(context);
                EventAdapter adapter = new EventAdapter(context,
                        db.getAllContacts());

                @Override
                public boolean canDismiss(int position) {
                    return true;
                }

                @Override
                public void onDismiss(ListView listView,
                        int[] reverseSortedPositions) {
                    for (int position : reverseSortedPositions) {

                        adapter.addAll(db.getAllContacts());
                        db.deleteEvent(adapter.getItem(position));
                        adapter.remove(adapter.getItem(position));
                    }
                    adapter.clear();
                    adapter.notifyDataSetChanged();

                }
            });

    listView.setOnTouchListener(touchListener);
    // Setting this scroll listener is required to ensure that during

    // // ListView scrolling,
    // // we don't look for swipes.
    listView.setOnScrollListener(touchListener.makeScrollListener());

    adapter.addAll(db.getAllContacts());
    adapter.notifyDataSetChanged();

}

// @Override
// protected void onResume() {
// // TODO Auto-generated method stub
// super.onResume();
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
// DatabaseHandler db = new DatabaseHandler(this);
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
//
// super.onResume();
// adapter.swapItems(db.getAllContacts());
// }

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.add:
        Intent intent = new Intent(this, CreateActivity.class);
        startActivityForResult(intent, 100);
        break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // /////////////////////////////DATABASE/////////////////////////////////////////////
    DatabaseHandler db = new DatabaseHandler(this);
    // /////////////////////////////DATABASE/////////////////////////////////////////////

    // Create the adapter to convert the array to views
    EventAdapter adapter = new EventAdapter(this, db.getAllContacts());

    // attach adapter to a list view
    listView = (ListView) findViewById(R.id.listViewFragment);
    listView.setAdapter(adapter);

    if (requestCode == 100) {
        if (resultCode == RESULT_OK) {
            Bundle b = data.getExtras();
            title = b.getString("TITLE");
            time = b.getString("TIME");
            date = b.getString("DATE");

            Bitmap bitmap = b.getParcelable("BITMAP");

            // ///CONVERTING A BITMAP TO A BYTE[]
            byte[] image = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            image = bos.toByteArray();
            // ///////

            // /////////////////////////////DATABASE/////////////////////////////////////////////
            /**
             * CRUD OPERATIONS
             */

            Log.e("Insert: ", "Inserting ..");
            db.addEvent(new Event((int) Math.floor(Math.random() * 101),
                    title, time, date, image));

            // Reading all contacts
            Log.e("Reading: ", "Reading all contacts..");

            adapter.addAll(db.getAllContacts());
            adapter.notifyDataSetChanged();

            // logging all events

            for (Event ev : db.getAllContacts()) {
                String log = "Id: " + ev.get_Id() + " ,Title: "
                        + ev.get_title() + " ,Date: " + ev.get_date()
                        + " ,RESOURCEID: " + ev.get_image();
                // Writing Contacts to log
                Log.e("Name: ", log);

            }

            // /////////////////////////////DATABASE/////////////////////////////////////////////
        }

    }
}
}

EventAdapter

public class EventAdapter extends ArrayAdapter<Event> {

private List<Event> events;

// View lookup cache
private static class ViewHolder {
    //adding drawable to imageview
    ImageView img;
    TextView title;
    TextView time;
    TextView date;
}

public EventAdapter(Context context, List<Event> objects) {
    super(context, R.layout.date_detail);
    this.events = events;

    // TODO Auto-generated constructor stub
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
    Event event = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.date_detail, null);
        viewHolder.title = (TextView) convertView
                .findViewById(R.id.textViewTitle);
        viewHolder.time = (TextView) convertView
                .findViewById(R.id.textViewTime);
        viewHolder.date = (TextView) convertView
                .findViewById(R.id.textViewDate);

        //adding drawable to imageview
        viewHolder.img = (ImageView) convertView
                .findViewById(R.id.imageView1);


        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    // Populate the data into the template view using the data object
    viewHolder.title.setText(event._title);
    viewHolder.time.setText(event._time);
    viewHolder.date.setText(event._date);

    //convert from byte array to bitmap               
    Bitmap bitmap = convertByteArrayToBitmap(event._image);
    // CONVERT BITMAP TO DRAWABLE
    viewHolder.img.setImageBitmap(bitmap);
    // Return the completed view to render on screen
    return convertView;
}

public static Bitmap convertByteArrayToBitmap(
        byte[] byteArrayToBeCOnvertedIntoBitMap)
    {
        Bitmap bitmap = BitmapFactory.decodeByteArray(
            byteArrayToBeCOnvertedIntoBitMap, 0,
            byteArrayToBeCOnvertedIntoBitMap.length);
        return bitmap;
    }

public void swapItems(List<Event> events) {
    this.events = events;
    notifyDataSetChanged();
}
}

1 个答案:

答案 0 :(得分:0)

通过在swipeDismissViewListener和OnActivityResult中删除以下代码行来解决问题。

DatabaseHandler db = new DatabaseHandler(context); EventAdapter adapter = new EventAdapter(context, db.getAllContacts());