Android从ListView和SQLite数据库中删除值

时间:2012-12-03 16:52:04

标签: android android-listview android-sqlite

我想从SQLite数据库中填充的值列表中删除一个项目。但我似乎无法让它发挥作用。 MySQLiteperper类具有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

这是我陷入项目的最后一部分。

2 个答案:

答案 0 :(得分:3)

  

但我似乎没有让它发挥作用。

首先,不要将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);
    // ...

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

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

答案 1 :(得分:0)

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

}