使用sqliteDatabase从自定义列表视图中删除项目

时间:2017-12-21 14:36:52

标签: android listview android-sqlite

每当我尝试使用deletedata方法删除时,应用程序其他功能都可以正常工作,但删除它时强制停止。 我正在尝试为我的日常开支制作应用程序。

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "users.db";
public static final String TABLE_NAME = "users_data";
public static final String COL1 = "ID";
public static final String COL2 = "FIRSTNAME";
public static final String COL3 = "LASTNAME";
public static final String COL4 = "FAVFOOD";
public static final String TABLE_NAMEA = "receivable";
public static final String COL5 = "ID";
public static final String COL6 = "FIRSTNAME";
public static final String COL7 = "LASTNAME";
public static final String COL8 = "FAVFOOD";

private SQLiteDatabase sqLiteDatabase;

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
    public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER 
PRIMARY KEY AUTOINCREMENT, " +
            " FIRSTNAME TEXT, LASTNAME TEXT, FAVFOOD INTEGER)";
    String createTablea = "CREATE TABLE " + TABLE_NAMEA + " (ID INTEGER 
PRIMARY KEY AUTOINCREMENT, " +
            " FIRSTNAME TEXT, LASTNAME TEXT, FAVFOOD INTEGER)";
    db.execSQL(createTable);
    db.execSQL(createTablea);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
    db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAMEA);
    onCreate(db);
}

public boolean addData(String fName, String lName, int fFood) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, fName);
    contentValues.put(COL3, lName);
    contentValues.put(COL4, fFood);

    long result = db.insert(TABLE_NAME, null, contentValues);

    //if date as inserted incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}

public boolean addDataa(String fName, String lName, int fFood) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL6, fName);
    contentValues.put(COL7, lName);
    contentValues.put(COL8, fFood);

    long result = db.insert(TABLE_NAMEA, null, contentValues);

    //if date as inserted incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
   }

  //query for 1 week repeats
public Cursor getListContents() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return data;
}

public Cursor getListContent() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAMEA, null);
    return data;
}

public int sumofcolumn() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT SUM(FAVFOOD) FROM users_data", 
null);
    int total = 0;
    if (cursor.moveToFirst()) {

        total = cursor.getInt(0);
    }

    return total;
}
public int sumofcolumn2() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT SUM(FAVFOOD) FROM receivable", 
null);
    int total = 0;
    if (cursor.moveToFirst()) {

        total = cursor.getInt(0);
    }

    return total;
}

public Cursor getItemId(String name){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = 
"SELECT"+COL1+"FROM"+TABLE_NAME+"WHERE"+COL2+"='"+name+"'";
    Cursor data = db.rawQuery(query,null);
    return data;


 }
public void deletedata(int id){
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME,ID+ "=" +id,null);
    db.close();

 }
}`

tab1.java

`public class tab1 extends Fragment {
 public static final String TAG = "tab1";

 DatabaseHelper myDB;
 ArrayList<User> userList;
 ListView listView;
 User user;
 TextView num;



  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);


    myDB = new DatabaseHelper(getActivity());

    userList = new ArrayList<>();
    Cursor data = myDB.getListContents();
    int numRows = data.getCount();
    if (numRows == 0) {
        Toast.makeText(getActivity(), "Click On Red Button To Add new 
     Expence ", Toast.LENGTH_LONG).show();
     } else {
        int i = 0;
        while (data.moveToNext()) {
            user = new User(data.getString(1), data.getString(2), 
     data.getString(3));
            userList.add(i, user);
            System.out.println(data.getString(1) + " " + data.getString(2) + 
    " " + data.getString(3));
            System.out.println(userList.get(i).getFirstName());
            i++;
        }


    }

   @Nullable
   @Override
   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
 container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab1, container, false);


    final ThreeColumn_ListAdapter adapter = new 
 ThreeColumn_ListAdapter(getActivity(), R.layout.list_adapter_view, 
 userList);
    listView = (ListView) view.findViewById(R.id.listview);
    listView.setAdapter(adapter);
    registerForContextMenu(listView);
    num = (TextView) view.findViewById(R.id.num3);
    myDB = new DatabaseHelper(getActivity());


    int tot = myDB.sumofcolumn();
    num.setText("" + tot);

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

               final int deleteId = position;


               AlertDialog alert = new 
  AlertDialog.Builder(view.getContext())
                       .setTitle("Delete " )
                       .setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                        public voidonClick(DialogInterfacedialog,
                        int whichButton) {

                         myDB.deletedata(position);


                         dialog.dismiss();
                                   }
                               })
                       .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                        int whichButton) {


                                    dialog.cancel();
                                   }
                               }).show();
               return false;
           }
       });

     return view;
 }

 }`

用户.java

public class User {
public Integer ID;
public String FirstName;
public String LastName;
public String FavFood;

public User(String fName,String lName, String fFood){

    FirstName = fName;
    LastName = lName;
    FavFood = fFood;
}



public String getFirstName() {
    return FirstName;
}

public void setFirstName(String firstName) {
    FirstName = firstName;
}

public String getLastName() {
    return LastName;
}

public void setLastName(String lastName) {
    LastName = lastName;
}

public String getFavFood() {
    return FavFood;
}

public void setFavFood(String favFood) {
    FavFood = favFood;
}

public Integer getID() {
    return ID;
}
public void setID(Integer ID) {
    this.ID = ID;
}
 }`

我不知道我做错了什么。我在这一点上陷入困​​境。当用户长按所选项目时,我想从数据库中删除数据。但是当我运行它时,&amp;长按项目&amp;尝试删除,app强制关闭。

这里是logcat ...

  

12-21 10:09:20.723 1482-1482 /? W / EGL_genymotion:eglSurfaceAttrib未实现

     

12-21 10:09:23.019 1482-1482 /? E / SQLiteLog:(1)没有这样的列:KTU84P

     

12-21 10:09:23.019 1482-1482 /? D / AndroidRuntime:关闭VM

     

12-21 10:09:23.019 1482-1482 /? W / dalvikvm:threadid = 1:线程退出   未捕获的异常(组= 0xa4d22b20)

     

12-21 10:09:23.023 1482-1482 /? E / AndroidRuntime:FATAL EXCEPTION:main

     

处理:com.scriptit.hsl,PID:1482

     

android.database.sqlite.SQLiteException:没有这样的列:KTU84P(代码1):,编译时:DELETE FROM users_data WHERE KTU84P = 0

     

在android.database.sqlite.SQLiteConnection.nativePrepareStatement(原生方法)

     

在android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)

     

在android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)

     

在android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)

     

在android.database.sqlite.SQLiteProgram。(SQLiteProgram.java:58)

     

在android.database.sqlite.SQLiteStatement。(SQLiteStatement.java:31)

     

在android.database.sqlite.SQLiteDatabase.delete(SQLiteDatabase.java:1494)

     

at com.scriptit.hsl.DatabaseHelper.deletedata(DatabaseHelper.java:136)

     

at com.scriptit.hsl.tab1 $ 1 $ 2.onClick(tab1.java:121)

     

在android.support.v7.app.AlertController $ ButtonHandler.handleMessage(AlertController.java:161)

     

在android.os.Handler.dispatchMessage(Handler.java:102)

     

在android.os.Looper.loop(Looper.java:136)

     

在android.app.ActivityThread.main(ActivityThread.java:5001)

     

at java.lang.reflect.Method.invokeNative(Native Method)

     

at java.lang.reflect.Method.invoke(Method.java:515)

     

at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:785)

     

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

     

at dalvik.system.NativeStart.main(Native Method)

     

12-21 10:09:23.043 595-915 /? W / ActivityManager:强制完成   activity com.scriptit.hsl / .MainActivity

1 个答案:

答案 0 :(得分:0)

你在条件的地方使用了错误的常量(ID)。根据您的COL1,<{1}}应该DatabaseHelper不变。

正如您的logcat所说:

  

没有这样的专栏:KTU84P

所以你错误地传递id值代替&#34; ID&#34;恒定。

使用以下代码:

public void deletedata(int id){ 
    SQLiteDatabase db = this.getWritableDatabase(); 
    db.delete(TABLE_NAME,COL1+ "=" +id,null); 
    db.close();      
 }

希望它有所帮助。