gpt4 book ai didi

sqlite - 我无法从 SQLiteDatabase 中删除行

转载 作者:行者123 更新时间:2023-12-01 16:23:16 25 4
gpt4 key购买 nike

在我的代码中,当我搜索时,会从数据库创建一个 ListView 。我想从这里删除表行。我使用了上下文菜单。有一个用于 getter 和 setter 的 Book.java 文件。一切都很顺利,但是当我按删除然后确定程序停止时。我认为问题出在 processDelete 函数中。我也无法从表中获取 id,因为 rowId 是列表中的 id。请尽快帮助我。没有这个我什么也做不了。

`

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class EmployeeList extends ListActivity {

protected EditText searchText;
protected SQLiteDatabase db;
protected Cursor cursor;
protected ListAdapter adapter;
public Integer pid=null;
public DatabaseHelper databaseHelper=new DatabaseHelper(null); //my database(I gave parameter null because i don't know what to give)
public Book book; //getter setter
private static final int DELETE_ID = Menu.FIRST+3;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = (new DatabaseHelper(this)).getWritableDatabase();
searchText = (EditText) findViewById (R.id.searchText);

}

public void search(View view) {
// || is the concatenation operation in SQLite
Toast.makeText(getApplicationContext(), "insert successfull", Toast.LENGTH_LONG).show();
cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?",
new String[]{"%" + searchText.getText().toString() + "%"});
adapter = new SimpleCursorAdapter(
this,
R.layout.employee_list_item,
cursor,
new String[] {"firstName", "lastName", "title"},
new int[] {R.id.firstName, R.id.lastName, R.id.title});
setListAdapter(adapter);
registerForContextMenu(getListView());
}
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this, EmployeeDetails.class);
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id"))); **strong text**
startActivity(intent);

}

public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {

menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete")
.setAlphabeticShortcut('d');
}

@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterView.AdapterContextMenuInfo info=
(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

delete(info.id);
return(true);
}

return(super.onOptionsItemSelected(item));
}
private void delete(final long rowId) {
if (rowId>0) {
new AlertDialog.Builder(this)
.setTitle(R.string.delete_title)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {

processDelete(rowId);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// ignore, just dismiss
}
})
.show();
}
}
private void processDelete(long rowId) { //I get exact rowid.
String[] args={String.valueOf(rowId)};

databaseHelper.getWritableDatabase().delete("employee", "_ID=?", args); //employee is table name and _ID is id column(here i get nullPointerException)
cursor.requery();
}
}`

数据库辅助类:

`公共(public)类 DatabaseHelper 扩展 SQLiteOpenHelper{

  public static final String DB_NAME = "employee_directory"; 
public static final Integer VERSION=1;

public static final String TABLE_NAME= "employee";
public static final String _id= "id";
public static final String firstName= "firstName";
public static final String lastName= "lastName";
public static final String title= "title";
public static final String officePhone= "officePhone";
public static final String cellPhone= "cellPhone";
public static final String email= "email";

public static final String TABLE_SQL = "CREATE TABLE " + TABLE_NAME+" (" +_id+" INTEGER PRIMARY KEY AUTOINCREMENT, "
+ firstName+ " TEXT, " + lastName+ " TEXT, " + title+ " TEXT, " + officePhone+ " TEXT, " + cellPhone+" TEXT, " + email+" TEXT)";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, VERSION);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Log.d("TABLE SQL", TABLE_SQL);
db.execSQL(TABLE_SQL);

}


@Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
db.execSQL("DROP TABLE IF EXISTS employees");
onCreate(db);
}
// public void delete(int pos) {
// SQLiteDatabase db = this.getWritableDatabase();
// db.delete(TABLE_NAME, _id + " = ?",
// new String[] { String.valueOf(pos)});
// db.close();
// }

//public void delete(String value1) {
// TODO Auto-generated method stub

// getWritableDatabase().delete(TABLE_NAME, "id=?", new String[] { value1 });

//}

}`

Logcat 说我收到 NullPointerException。我的删除查询有问题吗?

日志猫:

`

07-28 20:10:23.384: E/AndroidRuntime(977): FATAL EXCEPTION: main
07-28 20:10:23.384: E/AndroidRuntime(977): java.lang.NullPointerException
07-28 20:10:23.384: E/AndroidRuntime(977): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
07-28 20:10:23.384: E/AndroidRuntime(977): at com.example.intent.EmployeeList.processDelete(EmployeeList.java:124)
07-28 20:10:23.384: E/AndroidRuntime(977): at com.example.intent.EmployeeList.access$0(EmployeeList.java:115)
07-28 20:10:23.384: E/AndroidRuntime(977): at com.example.intent.EmployeeList$1.onClick(EmployeeList.java:101)
07-28 20:10:23.384: E/AndroidRuntime(977): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
07-28 20:10:23.384: E/AndroidRuntime(977): at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 20:10:23.384: E/AndroidRuntime(977): at android.os.Looper.loop(Looper.java:123)
07-28 20:10:23.384: E/AndroidRuntime(977): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-28 20:10:23.384: E/AndroidRuntime(977): at java.lang.reflect.Method.invokeNative(Native Method)
07-28 20:10:23.384: E/AndroidRuntime(977): at java.lang.reflect.Method.invoke(Method.java:521)
07-28 20:10:23.384: E/AndroidRuntime(977): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-28 20:10:23.384: E/AndroidRuntime(977): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-28 20:10:23.384: E/AndroidRuntime(977): at dalvik.system.NativeStart.main(Native Method)

`

通过插入this解决了这些问题。但仍然存在一些错误。

08-09 02:09:52.955: E/Database(310): close() was never explicitly called on database '/data/data/com.example.intent/databases/employee_directory' 
08-09 02:09:52.955: E/Database(310): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
08-09 02:09:52.955: E/Database(310): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1810)
08-09 02:09:52.955: E/Database(310): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:817)
08-09 02:09:52.955: E/Database(310): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:851)
08-09 02:09:52.955: E/Database(310): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:844)
08-09 02:09:52.955: E/Database(310): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:540)
08-09 02:09:52.955: E/Database(310): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
08-09 02:09:52.955: E/Database(310): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
08-09 02:09:52.955: E/Database(310): at com.example.intent.EmployeeList.onCreate(EmployeeList.java:44)
08-09 02:09:52.955: E/Database(310): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-09 02:09:52.955: E/Database(310): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-09 02:09:52.955: E/Database(310): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-09 02:09:52.955: E/Database(310): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-09 02:09:52.955: E/Database(310): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-09 02:09:52.955: E/Database(310): at android.os.Handler.dispatchMessage(Handler.java:99)
08-09 02:09:52.955: E/Database(310): at android.os.Looper.loop(Looper.java:123)
08-09 02:09:52.955: E/Database(310): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-09 02:09:52.955: E/Database(310): at java.lang.reflect.Method.invokeNative(Native Method)
08-09 02:09:52.955: E/Database(310): at java.lang.reflect.Method.invoke(Method.java:521)
08-09 02:09:52.955: E/Database(310): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-09 02:09:52.955: E/Database(310): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-09 02:09:52.955: E/Database(310): at dalvik.system.NativeStart.main(Native Method)

如何解决光标问题?

最佳答案

创建数据库助手时,您调用

public DatabaseHelper databaseHelper=new DatabaseHelper(null);

但是 null 是错误的。如果您查看有关 Context 的文档,您会发现例如Activity 是已知的间接子类。您当前的事件是此处的上下文:

public DatabaseHelper databaseHelper=new DatabaseHelper(this);

编辑:

作为构造函数定义

public DatabaseHelper(Context context)

告诉我们,创建DatabaseHelper需要一个Context类型的参数。 Context 对象提供有关特定应用程序的信息并提供与应用程序相关的服务。

可以使用子类的对象来代替Context,例如列表事件。在文档中,您可以看到 ListActivity 扩展了 Activity,而 Activity 又扩展了 ContextThemeWrapper 等等,直到 Context。这些类之一的每个对象都可以在需要 Context 对象作为参数的情况下使用(至少在形式上,根据用例,可能有一些对象在实践中不起作用)。

您的EmployeeList 扩展了ListActivity,因此也可以用作上下文。方法中的关键字 this 始终引用调用该方法的对象,例如在通话中

obj.foo()
foo() 中的

this 将表示 obj 引用的同一对象。

在开头的特定情况下,this 引用一个 EmployeeList 对象。

关于sqlite - 我无法从 SQLiteDatabase 中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17897311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com