2012-12-03 6 views
1

SQLite 데이터베이스에서 채워진 값 목록에서 항목을 삭제하고 싶습니다. 그러나 나는 그것을 작동시키지 않는 것 같습니다. 클래스 MySQLitehelper는 SQL 연산을 가지고 ListViewDelete는 그가 선택한 항목 (위치를 나타냄)을 기반으로 onlistItemClick을 가지며, 그 레코드는 SQLite 데이터베이스에서 삭제되어야합니다.Android ListView 및 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 

} 


} 

로그 캣 출력

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 

이 내 프로젝트에서 막혀있는 마지막 부분입니다.

+0

이렇게하면 다른 NPE가 나중에 발생합니다 :'final MySQLitehelper dbhelper = 새로운 MySQLitehelper (this);'. 대신 그 라인을'MySQLitehelper dbhelper;'로 변경하고'onCreate()'에'dbhelper = new MySQLitehelper (this);'를 추가하십시오. – Sam

답변

3

하지만 난 일하러하지 않는 것. 모든

먼저, 대신 ListActivity의 필드로 MySQLitehelper 클래스를 인스턴스화 onCreate 방법으로 그것을하지 않습니다 당신은 또한 당신의 MySQLitehelper 인스턴스에서 open 메소드를 호출하는 것을 잊었다

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

그렇지 않으면이 호출없이 MySQLitehelper 클래스의 SQLiteDatabase 참조가 null이고 그 값이 NullPointerException이됩니다.

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

Luksprog는 좋은 충고를 가지고있다. 나는 "DeleteRecord"에 "column not found"또는 "syntax"오류가있을 것이라고 덧붙이고 싶습니다. 이 줄은'this.db.delete (TABLE_NAME, COLUMN_LOCATION + "="+ location, null);''this.db.delete (TABLE_NAME, COLUMN_LOCATION + "=?", 새로운 문자열 [] {위치});'' 왜냐하면'location'은 String입니다. – Sam

+0

@Luksprog : 고마워요. 그건 효과가 있었지만 지금은 또 다른 문제가 있습니다. 해당 항목 대신 삭제할 항목을 클릭하면 다음 항목이 삭제되고 선택한 항목은 삭제되지 않습니다. 배열의 색인 번호에 문제가 있습니다. 어떤 단서가 잘못 될 수 있습니다. – noobcoder

+0

@noobcoder 그 이유는 다음과 같습니다 : ** 처음 ** thelist *에서 요소를 제거합니다 (이제는 하나의 항목만큼 작을 것입니다). 그런 다음 당신은'thelist'에서 위치가있는 레코드를 삭제합니다. 그러나 이전에 한 항목을 삭제했기 때문에 항상 다음 위치가 삭제됩니다. 그래서'theResources' 메소드를 호출 한 후에'thelist' ** 엘리먼트를 삭제하십시오. – Luksprog

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 

} 
+0

dbhelper.DeleteRecord (thelist.get (position))에 인수 형식이 일치하지 않습니다. 그리고 MySQLite 도우미 클래스 – noobcoder

+0

에서 호출 된 것과 같은 메서드 인 DeleteRecord() 메서드를 String [] 배열 인수로 사용하면 단일 문자열 만 전달하게됩니다. 그 이유는 :::> 인수 형식이 일치하지 않습니다. – MAC

+0

글쎄, 나는 둘 다 시도했다. 나는 correlect 인수 타입을 전달한다고하더라도, MySQLitehelper 클래스의 db.delete() 메소드는 그것을 받아들이지 않는다. – noobcoder

관련 문제