在sqlite中删除方法只删除listview中的1行

时间:2013-08-23 11:28:54

标签: android database sqlite android-listview android-sqlite

我正在使用sqlite创建一个简单的应用程序。我问了很多与此相关的问题,但没有得到太多回复。

我的删除功能我有问题,我想在其他活动中使用。但是不能正常工作,因为我使用自定义列表视图所以我在动态创建的列的行上有2个按钮,一个用于更新内容,第二个用于删除行的列表。

实际上我得到的问题是当我通过使用每行上的按钮删除一行时。它只删除列表视图的第一个项目。完全搞砸了。 请帮我解决这个

My View

数据库处理程序类:

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "tt";

    // Table names
    private static final String TABLE_INCOME = "income";
    //private static final String TABLE_INCOME = "income";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_PRICE = "price";
    private static final String KEY_TYPE = "type";
    private static final String KEY_DATE = "date";
    private static final String KEY_DESCRIPTION = "description";
    private static final String KEY_PAY_MODE = "pay_mode";

    Context c;

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_INCOME_TABLE = "CREATE TABLE if not exists " + TABLE_INCOME + "("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + KEY_PRICE + " REAL,"  
                + KEY_TYPE + " TEXT,"
                + KEY_DATE + " TEXT," 
                + KEY_DESCRIPTION + " TEXT," 
                + KEY_PAY_MODE + " TEXT"
                +")";
        db.execSQL(CREATE_INCOME_TABLE);
        Log.d(TABLE_INCOME, "table created with "+ KEY_PRICE +" "+ KEY_TYPE +" "
                + KEY_DATE +" " + KEY_DESCRIPTION +" " + KEY_PAY_MODE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_INCOME);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new income
    void addContact(Income income) {
        try{
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_PRICE, income.getPrice());
        values.put(KEY_TYPE, income.getType());
        values.put(KEY_DATE, income.getDate());
        values.put(KEY_DESCRIPTION, income.getDescription());
        values.put(KEY_PAY_MODE, income.getPaymode());

        // Inserting Row
        db.insert(TABLE_INCOME, null, values);
        db.close(); // Closing database connection
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    // Getting single income
    Income getContact(int id) {
        Income income = null;
        try{
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_INCOME, new String[] { KEY_ID, KEY_PRICE,
                KEY_TYPE, KEY_DATE , KEY_DESCRIPTION, KEY_PAY_MODE}, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            income = new Income(Integer.parseInt(cursor.getString(0)),Long.parseLong(cursor.getString(1)),
                cursor.getString(2), cursor.getString(3),cursor.getString(4),cursor.getString(5));
            Log.d("Genrated..", "Sending data");
        }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        // return income
        return income;
    }

    // Getting All Income
    public List<Income> getAllContacts() {
        List<Income> contactList = new ArrayList<Income>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_INCOME;

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Income income = new Income();
                income.setPrice(Long.parseLong(cursor.getString(1)));
                income.setType(cursor.getString(2));
                income.setDate(cursor.getString(3));
                income.setDescription(cursor.getString(4));
                income.setPaymode(cursor.getString(5));
                // Adding income to list
                contactList.add(income);
            } while (cursor.moveToNext());
        }

        // return income list
        return contactList;
    }

    // Updating single income
    public int updateContact(Income income) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_PRICE, income.getPrice());
        values.put(KEY_TYPE, income.getType());
        values.put(KEY_DATE, income.getDate());
        values.put(KEY_DESCRIPTION, income.getDescription());
        values.put(KEY_PAY_MODE, income.getPaymode());
        // updating row
        return db.update(TABLE_INCOME, values, null, null);
    }

    //Deleting single income
    public void deleteContact(Income income) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_INCOME, KEY_ID + " = ?",new String[] { String.valueOf(income.getID()) });
        db.close();
    }


    // Getting income Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_INCOME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}

在其他活动中实施:

String b = Long.toString(_incomelist.get(position).getPrice());
            Typeface tf = Typeface.createFromAsset(getAssets(), "font/Rupee_Foradian.ttf");
            viewHolder.txt_price.setTypeface(tf);
                        viewHolder.txt_id.setText(Integer.toString(_incomelist.get(position).getID()).trim());
            viewHolder.txt_price.setText("` "+b.trim());
            viewHolder.txt_type.setText(_incomelist.get(position).getType().trim());
            viewHolder.txt_date.setText(_incomelist.get(position).getDate().trim());
            viewHolder.txt_desc.setText(_incomelist.get(position).getDescription().trim());
            viewHolder.txt_pmode.setText(_incomelist.get(position).getPaymode().trim());

            final int temp = position;
(convertView.findViewById(R.id.imageButton2))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {

                    AlertDialog.Builder alertbox = new AlertDialog.Builder(
                            ViewContact.this);
                    alertbox.setCancelable(true);
                    alertbox.setMessage("Are you sure you want to delete ?");
                    alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface arg0, int arg1) {
                                    try{                        
                                    Income income = db.getContact(temp);
                                    db.deleteContact(income); //here using my delete function
                                    ViewContact.this.onResume();
                                    Toast.makeText(getApplicationContext(),"Deleted..",Toast.LENGTH_SHORT).show();
                                    }
                                    catch(Exception e)
                                    {
                                        e.printStackTrace();
                                    }
                                }

                            });
                    alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface arg0, int arg1) {

                                }
                            });
                    alertbox.show();
                }
            });

1 个答案:

答案 0 :(得分:0)

在您的函数getContact(int id)中,id是联系人的ID。但是您不在查询中使用此ID。表示您未在查询中使用任何where子句。因此它始终返回数据库的第一行。