Android从SQLITE删除行

时间:2014-11-18 02:29:56

标签: java android database sqlite

当用户长按listview中的某个项目时,我目前无法删除一行。我一次只能删除一行,这是我想要的,但当我删除前几个项时,它是成功的,当我尝试删除具有较晚ID的项目时。 id不会被删除并保留。我需要帮助,以便在要删除项目时始终删除项目。感谢。

这是我的数据库助手类

package com.example.health.adapter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.health.dao.ExerciseDAO;
import com.example.health.dao.RecipeDAO;

import java.util.ArrayList;
import java.util.List;

public class MySQLiteHelper extends SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "HealthDB";

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

@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_RECIPE_TABLE = "CREATE TABLE recipe ( " +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "title TEXT, " +
            "description TEXT )";

    db.execSQL(CREATE_RECIPE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS recipe");
    this.onCreate(db);
}

//START OF CRUD FOR RECIPE
private static final String TABLE_RECIPE = "recipe";
//column names
private static final String KEY_RID = "id";
private static final String KEY_RTITLE = "title";
private static final String KEY_RDESCRIPTION = "description";

private static final String[] RCOLUMNS = {KEY_RID,KEY_RTITLE,KEY_RDESCRIPTION};

public void addRecipe(RecipeDAO r) {
    Log.d("addRecipe", r.toString());
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_RTITLE, r.getTitle());
    values.put(KEY_RDESCRIPTION, r.getDescription());
    db.insert(TABLE_RECIPE, null, values);
    Log.d("Data Added", r.toString());
    db.close();
}

public RecipeDAO getRecipe(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor =
            db.query(TABLE_RECIPE, // a. table
                    RCOLUMNS, // b. column names
                    " id = ?", // c. selections
                    new String[] { String.valueOf(id) }, // d. selections args
                    null, // e. group by
                    null, // f. having
                    null, // g. order by
                    null);
    if (cursor != null)
        cursor.moveToFirst();

    RecipeDAO r = new RecipeDAO();
    r.setRecipeID(Integer.parseInt(cursor.getString(0)));
    r.setTitle(cursor.getString(1));
    r.setDescription(cursor.getString(2));

    Log.d("getRecipe("+id+")", r.toString());

    return r;
}

public List<RecipeDAO> getAllRecipe() {
    List<RecipeDAO> recipe = new ArrayList<RecipeDAO>();

    String query = "SELECT  * FROM " + TABLE_RECIPE;

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


    RecipeDAO r = null;
    if (cursor.moveToFirst()) {
        do {
            r = new RecipeDAO();
            r.setRecipeID(Integer.parseInt(cursor.getString(0)));
            r.setTitle(cursor.getString(1));
            r.setDescription(cursor.getString(2));

            recipe.add(r);
        } while (cursor.moveToNext());
    }

    Log.d("getAllRecipe()", recipe.toString());

    return recipe;
}

public int updateRecipe(RecipeDAO r) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put("title", r.getTitle());
    values.put("description", r.getDescription());


    int i = db.update(TABLE_RECIPE, //table
            values, // column/value
            KEY_RID+" = ?", // selections
            new String[] { String.valueOf(r.getRecipeID()) });

    db.close();

    return i;
}

public void deleteAllRecipe() {
    RecipeDAO r = new RecipeDAO();
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_RECIPE,null,null);
    db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_RECIPE + "'");

    db.close();

    Log.d("deleteRecipe", r.toString());
}
/*
public void deleteRecipe(RecipeDAO r) {
    SQLiteDatabase db = this.getWritableDatabase();

    db.delete(TABLE_RECIPE, KEY_RID+ " = ? ", new String[] { String.valueOf(r.getRecipeID()) });
    db.close();

}*/

public boolean deleteRecipe(long id)
{
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_RECIPE, KEY_RID + "=" + id, null) > 0;
}
//END OF CRUD FOR RECIPE
}

数据库CRUD操作的类

package com.example.health.recipe;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.example.health.adapter.MySQLiteHelper;
import com.example.health.dao.RecipeDAO;
import com.example.health.healthplanner.R;

import java.util.List;

public class Recipes extends Fragment {

    MySQLiteHelper db;
    Button deleteButton;
    ListView lv;
    List<RecipeDAO> data;
    RecipeDAO r = new RecipeDAO();

    public Recipes() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.recipe_fragment, container, false);
        db = new MySQLiteHelper(getActivity());

        /*
        db.addRecipe(new RecipeDAO("Windows", "Bill Gates"));//hardcode test
        db.addRecipe(new RecipeDAO("IOS", "Steve Jobs"));//same
        db.addRecipe(new RecipeDAO("Android", "Andy Rubin"));//same*/

        data = db.getAllRecipe();
        final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, data);
        lv = (ListView) v.findViewById(R.id.listView2);
        lv.setAdapter(adapter);

        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                data.remove(position);
                db.deleteRecipe(id + 1);
                adapter.notifyDataSetChanged();

                return false;

               // db.deleteRecipeRow(r.getRecipeID());
                //Toast.makeText(getActivity(),"ID = " + r.getRecipeID(),   Toast.LENGTH_LONG).show();

            }
        });

        deleteButton = (Button) v.findViewById(R.id.deletebutton);

        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
                alertDialog.setTitle("Delete");
                alertDialog.setMessage("Are you sure you want to delete all data?");
                alertDialog.setCancelable(false);


                alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        db.deleteAllRecipe();
                        adapter.notifyDataSetChanged();
                        Toast.makeText(getActivity(), "All data delete", Toast.LENGTH_SHORT).show();
                    }
                });

                alertDialog.setNegativeButton("No", null);
                alertDialog.show();

               /* data = db.getAllRecipe();
                for(RecipeDAO re : data) {  testing to see if data is in database
                    String log = "Id: " + re.getRecipeID() + ", Title: " + re.getTitle();
                    Log.d("Data", log);
                 }*/

            }
        });
        return v;
    }
}

2 个答案:

答案 0 :(得分:1)

试试这个

public void delete(String name) {
        db.delete(your_table_name, "name= ?", new String[] { name });
}

答案 1 :(得分:0)

请修改此方法,

//更改setOnItemLongClickListener中的代码

 lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            data.remove(position);
            db.deleteRecipe(id + 1);
           data = db.getAllRecipe();
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, data);
//and call change adapter in listview
            adapter.notifyDataSetChanged();

            return false;

           // db.deleteRecipeRow(r.getRecipeID());
            //Toast.makeText(getActivity(),"ID = " + r.getRecipeID(),   Toast.LENGTH_LONG).show();

        }
    });

//这个在sqlite数据库中删除的方法

public boolean deleteRecipe(long id)
{
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_RECIPE, KEY_RID + " =?" , new String[]{id}) > 0;
}