【问题标题】:Android Deleting a value from the ListView and SQLite databaseAndroid 从 ListView 和 SQLite 数据库中删除一个值
【发布时间】:2012-12-03 16:52:03
【问题描述】:

我想从 SQLite 数据库填充的值列表中删除一个项目。但我似乎没有让它工作。 MySQLitehelper 类具有 SQL 操作,ListViewDelete 具有 onlistItemClick,根据他选择的项目(代表位置),应该从 SQLite 数据库中删除该记录。

--- MySQLitehelper.java----

public class MySQLitehelper {

//public static final String TABLE_COMMENTS = "comments";
  public static final String COLUMN_ID = "GWid";
  public static final String COLUMN_DATE = "DateGWU";
  public static final String COLUMN_LOCATION = "location";
  public static final String COLUMN_TIME = "time";

  public static final String TABLE_NAME = "UPDTable";

  private static final String DATABASE_NAME = "UPDdb_version6";
  private static final int DATABASE_VERSION = 6;

  private final Context context;
  GetSet getset = new GetSet();
  public void GetIdForGwid(GetSet get)
  {
     getset=get; 
  }

  // Database creation sql statement
  private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_NAME +
                                " (" +COLUMN_ID+ " integer," + COLUMN_DATE + " VARCHAR," +
                                COLUMN_LOCATION+" VARCHAR," +COLUMN_TIME +" VARCHAR);";

//  private static final String DATABASE_INSERT = "INSERT INTO " +TABLE_NAME +
//                                              " Values (47688507,'DEC-07-2012','MARVIN 203','20:00');";

  private static final String DATABASE_INSERT = "INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +
          COLUMN_LOCATION+" ," +COLUMN_TIME +" )"  +
                          " Values (47688507,'DEC-07-2012','MARVIN 203','20:00');";



  DatabaseHelper dbhelper;
  SQLiteDatabase db;




 public MySQLitehelper(Context ctx)
  {
      this.context = ctx;
      dbhelper = new DatabaseHelper(ctx);
  }



private static class DatabaseHelper extends SQLiteOpenHelper {

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

 @Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(DATABASE_CREATE);            //execute create table
    db.execSQL(DATABASE_INSERT);            //execute insert query
    db.execSQL("INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +" )" +" Values (47688507,'DEC-22-2012','OLD MAIN','23:00');");
    db.execSQL("INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +" )" +" Values (1234567,'DEC-14-2012','FUNGER','12:00');");
    db.execSQL("INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +" )" +" Values (7654321,'DEC-29-2012','GELMAN','22:00');");
    db.execSQL("INSERT INTO " +TABLE_NAME +  " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +" )" +" Values (47688507,'DEC-12-2012','IVORY','23:00');");
 }

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    Log.w(MySQLitehelper.class.getName(),
            "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}


// open the DB
 public MySQLitehelper open() throws SQLException
 {
    System.out.println("Inside open function");
     db = dbhelper.getWritableDatabase();
    return this;
 }

 public void close()
 {
     dbhelper.close();
 }



 public void insertRecord(long gwid, String date, String location, String time)
     {
           ContentValues initialValues = new ContentValues();
          initialValues.put(COLUMN_ID, gwid);
          initialValues.put(COLUMN_DATE, date);
          initialValues.put(COLUMN_LOCATION, location);
          initialValues.put(COLUMN_TIME, time);
          db.insert(TABLE_NAME, null, initialValues);
     }

public Cursor getAllrows()      //function to get all rows in the DB. Testing initially.
{

     Cursor cur = db.rawQuery("SELECT * FROM "+TABLE_NAME, null);
     return cur;
}

public Cursor getRecord(long getid) throws SQLException
{
        Cursor mCursor =
        db.query(true, TABLE_NAME, new String[] {COLUMN_ID,
        COLUMN_DATE, COLUMN_LOCATION, COLUMN_TIME},
        COLUMN_ID + "= "+getid, null, null, null, null, null);  
        if (mCursor != null) 
        {
            mCursor.moveToFirst();
        }
 return mCursor;
}

public void DeleteRecord (String location)
{
    try {
        //String sSQLQuery = "DELETE FROM "+TABLE_NAME +
         //   "WHERE "+COLUMN_LOCATION+"='" + location + "';";
        //db.execSQL(sSQLQuery);
        //db.dele
        this.db.delete(
                  TABLE_NAME,
                  COLUMN_LOCATION+" = "+location,null);
        String Message = "Record is deleted: ";
    } catch (SQLiteException ex) {

    }
}

}

--ListViewDelete.java--- onItemListClick方法所在

public class ListViewDelete extends ListActivity {


private ArrayList<String> thelist;


 final MySQLitehelper dbhelper = new MySQLitehelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_list_view_delete);

    final Intent intent = getIntent();
    final Bundle extras = getIntent().getExtras();    //gets the GWID


    thelist = new ArrayList<String>(extras.getStringArrayList(SelectOptions.EXTRA_MESSAGE));
    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,extras.getStringArrayList(SelectOptions.EXTRA_MESSAGE)));
}       

public void onListItemClick(ListView parent, View view, int position, long id)
{
    Toast.makeText(this, "You have selected "+thelist.get(position)+" and will be deleted", Toast.LENGTH_LONG).show();
    thelist.remove(position);
    dbhelper.DeleteRecord(thelist.get(position));   // I don't know how to deal    with this statement

}


}

LOGCAT 输出

  12-03 19:40:04.959: W/dalvikvm(6510): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
12-03 19:40:04.998: E/AndroidRuntime(6510): FATAL EXCEPTION: main
12-03 19:40:04.998: E/AndroidRuntime(6510): java.lang.NullPointerException
12-03 19:40:04.998: E/AndroidRuntime(6510):     at com.example.upd.MySQLitehelper.DeleteRecord(MySQLitehelper.java:147)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at com.example.upd.ListViewDelete.onListItemClick(ListViewDelete.java:45)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at android.widget.AdapterView.performItemClick(AdapterView.java:298)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at android.widget.AbsListView$1.run(AbsListView.java:3423)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at android.os.Handler.handleCallback(Handler.java:725)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at android.os.Looper.loop(Looper.java:137)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at android.app.ActivityThread.main(ActivityThread.java:5039)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at java.lang.reflect.Method.invokeNative(Native Method)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at java.lang.reflect.Method.invoke(Method.java:511)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-03 19:40:04.998: E/AndroidRuntime(6510):     at dalvik.system.NativeStart.main(Native Method)
12-03 19:40:09.049: I/Process(6510): Sending signal. PID: 6510 SIG: 9

这是我在项目中陷入困境的最后一部分。

【问题讨论】:

  • 这将在以后导致另一个 NPE:final MySQLitehelper dbhelper = new MySQLitehelper(this);。而是将该行更改为MySQLitehelper dbhelper; 并在onCreate() 中添加dbhelper = new MySQLitehelper(this);

标签: android android-listview android-sqlite


【解决方案1】:

但我似乎没有让它工作。

首先,不要将MySQLitehelper 类实例化为ListActivity 中的字段,而是在onCreate 方法中进行:

// ...
final MySQLitehelper dbhelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_list_view_delete);
    dbHelper = new MySQLitehelper(this);
    // ...

您还忘记在您的MySQLitehelper 实例上调用open 方法,否则,如果没有此调用,MySQLitehelper 类中的SQLiteDatabase 引用为空,它将抛出NullPointerException

// ....
thelist.remove(position);
try {
    dbhelper.open();
} catch (SQLException sqle) {
     Log.e("TAG", "Never ignore exception!!! " + sqle);
}  
dbhelper.DeleteRecord(thelist.get(position)); 

【讨论】:

  • Luksprog 有很好的建议。我想补充一下,DeleteRecord 中会出现“找不到列”或“语法”错误。这一行:this.db.delete(TABLE_NAME, COLUMN_LOCATION+" = "+location,null); 应该是 this.db.delete(TABLE_NAME, COLUMN_LOCATION+" = ?",new String[] {location});,因为 location 是一个字符串。
  • @Luksprog:谢谢伙计。那行得通,但现在我有另一个问题。当我单击要删除的项目而不是该项目时,下一个项目将被删除,而我选择的项目不会。数组中的索引号存在一些问题。任何线索可能是错误的。
  • @noobcoder 发生这种情况是因为:首先从 *thelist* 中删除元素(所以现在它会小一个项目),然后删除带有来自thelist 的位置。但是因为您之前删除了一个项目,所以您总是会删除下一个位置。所以从thelist中删除元素你调用DeleteRecord方法之后。
  • @Luksprog 我试图指出原始查询无法将字符串括在引号中,即COLUMN_LOCATION+" = '"+location+"'"。但不想留下600字的评论。 :)
  • @Sam:你的担心被忽略了。这两件事都奏效了。我很感激你的努力。在 Stackoverflow 上像你这样的人长达一周的帮助后,我的项目终于结束了。我知道这条评论会被删除,但我只是想感谢它。项目演示在 2 小时内完成。 :)
【解决方案2】:
ArrayAdapter ad =new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,extras.getStringArrayList(SelectOptions.EXTRA_MESSAGE));

public void onListItemClick(ListView parent, View view, int position, long id)
{
    Toast.makeText(this, "You have selected "+thelist.get(position)+" and will be deleted", Toast.LENGTH_LONG).show();
    thelist.remove(position);
    dbhelper.DeleteRecord(thelist.get(position));   // I don't know how to deal    with this statement
    ad.notifyDataSetChanged(); <------ TRY THIS

}

【讨论】:

  • 在 dbhelper.DeleteRecord(thelist.get(position)) 处存在参数类型不匹配;以及在 MySQLite 助手类中调用的相同方法
  • DeleteRecord() 方法作为参数 String []array 并且您只传递单个字符串。这就是为什么你得到:::> 参数类型不匹配
  • 我都试过了。我的意思是即使我传递了正确的参数类型,MySQLitehelper 类中的 db.delete() 方法也不接受它。
  • 我说的是 DeleteRecord() 方法而不是 db.delete() 伙计
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多