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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用sqliteDatabase从自定义列表视图中删除项目相关的知识,希望对你有一定的参考价值。

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

database helper.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();

 }
}`

他不1.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;
}
 }`

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

这是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:致命异常:主要

处理: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)

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

在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)

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

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

在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:强制完成活动com.scriptit.hsl / .MainActivity

答案

你在条件的地方使用了错误的常数(ID)。根据你的COL1,它应该是DatabaseHelper常数。

正如你的logcat所说:

没有这样的专栏:KTU84P

所以你错误地传递id值代替“ID”常数。

使用以下代码:

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

希望能帮助到你。

以上是关于使用sqliteDatabase从自定义列表视图中删除项目的主要内容,如果未能解决你的问题,请参考以下文章

使用微调器从自定义列表视图中删除了错误的行

使用基本适配器解决方案从自定义列表中删除行视图

如何从自定义列表视图中获取选定项目并在 toast 消息中打印?

Android:从自定义列表视图中单击的按钮获取列表视图项目

列表视图中的页脚按钮,如何从自定义列表适配器中获取值

Android - 从自定义列表视图中删除一个项目并在长按时更新它