使用 sqliteDatabase 从自定义列表视图中删除项目
Posted
技术标签:
【中文标题】使用 sqliteDatabase 从自定义列表视图中删除项目【英文标题】:delete item from custom listview with sqliteDatabase 【发布时间】:2017-12-21 14:36:51 【问题描述】:每当我尝试使用 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;
`
我不知道我做错了什么。我在这一点上卡住了。当用户长按所选项目时,我想从数据库中删除数据。但是当我运行它并长按项目并尝试删除时,应用程序强制关闭。
这里是 logcat...
12-21 10:09:20.723 1482-1482/? W/EGL_genymotion:eglSurfaceAttrib 未实现
12-21 10:09:23.019 1482-1482/? E/SQLiteLog: (1) no such column: KTU84P
12-21 10:09:23.019 1482-1482/? D/androidRuntime: 关闭虚拟机
12-21 10:09:23.019 1482-1482/? W/dalvikvm: threadid=1: 线程退出 有未捕获的异常 (group=0xa4d22b20)
12-21 10:09:23.023 1482-1482/? E/AndroidRuntime: FATAL EXCEPTION:main
进程:com.scriptit.hsl,PID:1482
android.database.sqlite.SQLiteException: no such column: KTU84P (code 1): , while compile: DELETE FROM users_data WHERE KTU84P=0
在 android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
在 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)
在 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)
在 dalvik.system.NativeStart.main(Native Method)
12-21 10:09:23.043 595-915/? W/ActivityManager:强制完成 活动 com.scriptit.hsl/.MainActivity
【问题讨论】:
分享你的错误日志? 崩溃后日志 【参考方案1】:您在 where 条件下使用了错误的常量 (ID
)。根据您的DatabaseHelper
,它应该是COL1
常量。
正如你的 logcat 所说:
没有这样的列:KTU84P
所以你错误地传递了 id 值来代替“ID”常量。
使用以下代码:
public void deletedata(int id)
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,COL1+ "=" +id,null);
db.close();
希望对你有帮助。
【讨论】:
以上是关于使用 sqliteDatabase 从自定义列表视图中删除项目的主要内容,如果未能解决你的问题,请参考以下文章