简体   繁体   English

删除项目后,Android Listview不更新

[英]Android Listview not updating after delete item

I am working with sqllite. 我正在使用sqllite。 I have successfully create a database and I can input some values in my database. 我已经成功创建了数据库,并且可以在数据库中输入一些值。 I can also show all values in listview and also i can remove item by listview's onitemclicklistener.i have one problem. 我也可以在listview中显示所有值,也可以通过listview的onitemclicklistener删除项目。我有一个问题。 when i delete item listview not updated,but this item is deleted in database.how i can solve this problem ? 当我删除未更新的项目列表视图时,但此项目已在database。删除时,我该如何解决此问题?

DatabaseHandler .java code DatabaseHandler .java代码

public class DatabaseHandler extends SQLiteOpenHelper {


private static final int DATABASE_VERSION = 1;


private static final String DATABASE_NAME = "lvstone_2";


private static final String TABLE_CONTACTS = "CardTable1";


private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";

private static final String KEY_Counter = "counter";

private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"

            + KEY_Description + " TEXT,"

            + KEY_Price + " TEXT,"

            + KEY_Counter + " TEXT,"

            + KEY_Image + " TEXT"

            + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

// Adding new contact
public void Add_Contact(Contact contact) {
    db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    if (!somethingExists(contact.getTitle())) {

        values.put(KEY_Tittle, contact.getTitle()); // Contact title
        values.put(KEY_Description, contact.getDescription()); // Contact//
                                                                // description

        values.put(KEY_Price, contact.getPrice()); // Contact price

        values.put(KEY_Counter, contact.getCounter()); // Contact image
        values.put(KEY_Image, contact.getImage()); // Contact image

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);

        Log.e("Table Result isss", String.valueOf(values));
        db.close(); // Closing database connection

    }

}


public void deleteUser(String userName)
{
    db = this.getWritableDatabase();
    try
    {
        db.delete(TABLE_CONTACTS, "name = ?", new String[] { userName });
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        db.close();
    }
}

// Getting single contact
Contact Get_Contact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS,
            new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
                    KEY_Counter, KEY_Image }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
            cursor.getString(2), cursor.getString(4), cursor.getString(5));
    // return contact
    cursor.close();
    db.close();

    return contact;
}

public boolean somethingExists(String x) {
    Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
            + " where name like '%" + x + "%'", null);
    boolean exists = (cursor.getCount() > 0);

    Log.e("Databaseeeeeeeee", String.valueOf(cursor));
    cursor.close();
    return exists;
}

public ArrayList<Contact> Get_Contacts() {
    try {
        contact_list.clear();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();

                contact.setTitle(cursor.getString(1));

                contact.setDescription(cursor.getString(2));

                contact.setPrice(cursor.getString(3));
                contact.setCounter(cursor.getString(4));

                contact.setImage(cursor.getString(5));

                contact_list.add(contact);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return contact_list;
    } catch (Exception e) {
        // TODO: handle exception
        Log.e("all_contact", "" + e);
    }

    return contact_list;
}

public int getProfilesCount() {
    String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;
}

} }

SQLAdapter.java code SQLAdapter.java代码

public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;

public StradaSQLAdapter(Activity act, int layoutResourceId,
        ArrayList<Contact> data) {

    this.layoutResourceId = layoutResourceId;
    this.activity = act;
    this.data = data;
    imageLoader = new ImageLoader(act.getApplicationContext());
    notifyDataSetChanged();
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View row = convertView;

    if (row == null) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        holder = new UserHolder();
        row = inflater.inflate(layoutResourceId, parent, false);

        holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
        holder.counter = (TextView) row.findViewById(R.id.smallCounter1);

        holder.dbcounter = (TextView) row
                .findViewById(R.id.DBSliderCounter);

        holder.Description = (TextView) row.findViewById(R.id.smallDesc1);

        holder.layout = (RelativeLayout) row
                .findViewById(R.id.DBSlideLayout);
        holder.layoutmain = (RelativeLayout) row
                .findViewById(R.id.DBSlideLayoutMain);
        holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
        holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
        holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);

        holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);

        holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);

        row.setTag(holder);
    } else {
        holder = (UserHolder) row.getTag();
    }
    user = data.get(position);

    holder.Title.setText(user.getTitle());
    holder.Description.setText(user.getDescription());
    holder.Price.setText(user.getPrice() + " GEL");

    holder.counter.setText(user.getCounter());

    holder.dbcounter.setText(user.getCounter());

    Log.e("image Url is........", data.get(position).toString());
    imageLoader.DisplayImage(user.getImage(), holder.pt);






    return row;

}

@Override
public int getCount() {

    return data.size();
}

@Override
public Object getItem(int position) {

    return data.get(position);
}

@Override
public long getItemId(int position) {

    return 0;
}

public class UserHolder {

    public TextView Price, counter, Description, Title, dbcounter;
    public ImageView pt,close,c_plus,c_minus;

    public RelativeLayout layout, layoutmain;

}

} and Main java code }和主要的Java代码

public class StradaChartFragments extends Fragment {

public static ListView list;

ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;


UserHolder holder;


private RelativeLayout.LayoutParams layoutParams;


private ArrayList<Contact> contact_array_from_db;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.strada_chart_fragment,
            container, false);

    dbHelper = new DatabaseHandler(getActivity());


    list = (ListView) rootView.findViewById(R.id.chart_listview);
    cAdapter = new StradaSQLAdapter(getActivity(),
            R.layout.listview_row_db, contact_data);
    contact_array_from_db = dbHelper.Get_Contacts();

    Set_Referash_Data();
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {
            holder = (UserHolder) view.getTag();

            layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
                    .getLayoutParams();

            if (holder.layout.getVisibility() != View.VISIBLE) {

                ValueAnimator varl = ValueAnimator.ofInt(0, -170);
                varl.setDuration(1000);

                varl.addUpdateListener(new AnimatorUpdateListener() {

                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {

                        layoutParams.setMargins(
                                (Integer) animation.getAnimatedValue(), 0,
                                0, 0);
                        holder.layoutmain.setLayoutParams(layoutParams);

                    }
                });
                varl.start();
                holder.layout.setVisibility(View.VISIBLE);

            }

            holder.close.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
                    var2.setDuration(1000);

                    var2.addUpdateListener(new AnimatorUpdateListener() {

                        @Override
                        public void onAnimationUpdate(
                                ValueAnimator animation) {


                            dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());


                            if (contact_data.size() > 0)

                                contact_data.remove(position);



                            layoutParams.setMargins(0, 0,
                                    (Integer) animation.getAnimatedValue(),
                                    0);
                            holder.layoutmain.setLayoutParams(layoutParams);


                            holder.layout.setVisibility(View.INVISIBLE);

                        }
                    });
                    var2.start();

                }
            });


        }

    });



    return rootView;
}

public void Set_Referash_Data() {
    contact_data.clear();



    for (int i = 0; i < contact_array_from_db.size(); i++) {

        String title = contact_array_from_db.get(i).getTitle();
        String Description = contact_array_from_db.get(i).getDescription();
        String Price = contact_array_from_db.get(i).getPrice();

        String Counter = contact_array_from_db.get(i).getCounter();

        String image = contact_array_from_db.get(i).getImage();

        Contact cnt = new Contact();

        cnt.setTitle(title);
        cnt.setDescription(Description);
        cnt.setPrice(Price);

        cnt.setCounter(Counter);

        cnt.setImage(image);

        contact_data.add(cnt);
    }
    dbHelper.close();

    list.setAdapter(cAdapter);

    Log.e("Adapter issss ...", String.valueOf(cAdapter));
}

} }

i can remove item in database ,but listview not updated . 我可以删除数据库中的项目,但listview未更新。 what am i doing wrong ? 我究竟做错了什么 ? if anyone knows solution help me thanks 如果有人知道解决方案可以帮助我,谢谢

Under your method dbHelper.deleteUser add this code: 在您的方法dbHelper.deleteUser添加以下代码:

contact_data.remove(position);

To function in addition to deleting it from the database also have to delete the array of objects that you sent to adapter. 要发挥作用,除了要从数据库中删除它之外,还必须删除发送给适配器的对象数组。

EDIT: 编辑:

Add one remove method in your adapter for you can remove object. 在适配器中添加一种删除方法,以便可以删除对象。 Code: 码:

Adapter: 适配器:

public void removeObject (int position) {
     this.data.remove(position);
}

Activity: 活动:

Change: 更改:

contact_data.remove(position);

to: 至:

cAdapter.removeObject(position);
cAdapter.notifyDataSetChanged();

EDIT 2: 编辑2:

Just delete all the objects from ArrayList. 只需删除ArrayList中的所有对象。

contact_data.clear();

or in your adapter 或在您的适配器中

data.clear();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM