SQlite“删除单行”“并删除所有行”代码不起作用

时间:2017-01-03 15:15:29

标签: android sqlite android-sqlite

为什么不在ListView OnItemLongClickListener()中使用我的SQlite“delete”和“deleteall”代码? 我尝试了很多代码,但无法处理任何代码。 我的错误和方式对我来说哪个方面更好? 提前致谢

这是我的编码。

DBclass

      import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
 import android.database.SQLException;
import         android.database.sqlite.SQLiteDatabase;
     import             android.database.sqlite.SQLiteOpenHelper;
      import android.util.Log;

 public class DBclass {

public static final String KEY_ROWID = "_id";
public static final String KEY_COL1 = "col1";
public static final String KEY_COL2 = "col2";

private static final String DATABASE_NAME = "mydb";
private static final String DATABASE_TABLE = "mytable";
private static final int DATABASE_VERSION = 1;

private final Context ourContext;
private DbHelper dbh;
private SQLiteDatabase odb;

private static final String USER_MASTER_CREATE =
    "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE+ "("
        + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + KEY_COL1  + " VARCHAR(15) UNIQUE, " + KEY_COL2 + " VARCHAR(15) )";

private static class DbHelper extends SQLiteOpenHelper {

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

    @Override
   public void onCreate(SQLiteDatabase db) {
        db.execSQL(USER_MASTER_CREATE);
}

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // if DATABASE VERSION changes
        // Drop old tables and call super.onCreate()
    }
}

public DBclass(Context c) {
    ourContext = c;
    dbh = new DbHelper(ourContext);
}

public DBclass open() throws SQLException {
    odb = dbh.getWritableDatabase();
    return this;
}

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

public long insertmaster(String col1, String col2) throws SQLException{
    Log.d("", col1);
    Log.d("", col2);

    ContentValues IV = new ContentValues();

    IV.put(KEY_COL1, col1);
    IV.put(KEY_COL2, col2);

    return odb.insert(DATABASE_TABLE, null, IV);
    // returns a number >0 if inserting data is successful
}

public void updateRow(long rowID, String col1, String col2) {
    ContentValues values = new ContentValues();
    values.put(KEY_COL1, col1);
    values.put(KEY_COL2, col2);

   try {
        odb.update(DATABASE_TABLE, values, KEY_ROWID + "=" + rowID, null);
    } catch (Exception e) {
    }
}
public void delete(){

    //??????????????????????????????????????????????????????????
    //????????????????????????????????????????????????????????
    //?????????????????????????????????????????????????????
}




public void deleteall(){


    //??????????????????????????????????????????????????????????
    //????????????????????????????????????????????????????????
    //?????????????????????????????????????????????????????
}



// public void deleteEntry(long row,String key_name) {
 //   odb.delete(DATABASE_TABLE, KEY_ROWID + "=" + row + " and " + KEY_COL1 + "=" + key_name, null);
    /*if you just have key_name to select a row,you can ignore passing rowid(here-row) and use:
    db.delete(DATABASE_TABLE, KEY_NAME + "=" + key_name, null);
    */  
//  }


  //  private static final String mname = "'KEY_COL1'";
      //  public void deleteContact()
   //  {
         //     odb.delete(DATABASE_TABLE, KEY_COL1 + "=" + mname, null);
      //  }


    //   public boolean deleteSingleRow(String rowId) 
   //  {
          //    return  odb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
           //  }



   //  public void deleteRowFromTable(String tableName, String columnName, String keyValue) {
   //      String whereClause = columnName + "=?";
   //     String[] whereArgs = new String[]{String.valueOf(keyValue)};
   //     odb.delete(tableName, whereClause, whereArgs);
  //  }




  //  public boolean delete(String value){

  //      return odb.delete(DATABASE_TABLE,KEY_COL1+"="+value+";",null)>0;

 // }



  //  public void delete(long rowid){

  //      odb.delete(DATABASE_TABLE,KEY_COL1+"="+rowid,null);

 //  }



  //   public void delete(String value){
   //    odb.delete(DATABASE_TABLE,KEY_COL1+"=?",new String[]{String.valueOf(value)} ) ;

  //  }


    public Cursor queueAll(String id)throws SQLException{
      String[] columns = new String[]{KEY_COL1, KEY_COL2};
      Cursor mCursor = odb.query(DATABASE_TABLE, columns,
        null, null, null, null, null);

      return mCursor;
     }
  public Cursor getAllTitles() {
    // using simple SQL query
    return odb.rawQuery("select * from " + DATABASE_TABLE, null);
    }

   public Cursor getallCols(String id) throws SQLException {
     Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_COL1,
            KEY_COL2 }, null, null, null, null, null);
    Log.e("getallcols zmv", "opening successfull");
    return mCursor;
  }


public Cursor getColsById(String id) throws SQLException {
    Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_COL1,
            KEY_COL2 }, KEY_ROWID + " = " + id, null, null, null, null);
   Log.e("getallcols zmv", "opening successfull");
    return mCursor;
   }

 }

这是我的:MainActivity

   public class MainActivity extends Activity {
private ListView list_lv;
private EditText col1_ed;

private Button sub_btn;

private DBclass db;
private ArrayList<String> collist_1;
private ArrayList<String> collist_2;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    collist_1 = new ArrayList<String>();
    collist_2 = new ArrayList<String>();
    items();
    getData();
    AnimationSet anim2 = (AnimationSet) AnimationUtils.loadAnimation(getBaseContext(), R.anim.rotate);
    sub_btn.startAnimation(anim2); 
}
private void items() {
    sub_btn = (Button) findViewById(R.id.submit_btn);

    col1_ed = (EditText) findViewById(R.id.ed1);

    list_lv = (ListView) findViewById(R.id.dblist);

    sub_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            submitData();
        }
    });
}
protected void submitData() {
    String a = col1_ed.getText().toString();
    db = new DBclass(this);
    long num;

    if(a.length()>0){
        col1_ed.setText("");

        db.open();
        num = db.insertmaster(a, "");
        getData();
        db.close();
          }





}
public void getData() {
    collist_1.clear();
    collist_2.clear();
    db = new DBclass(this);
    try {
        db.open();
        Cursor cur = db.getAllTitles();
        while (cur.moveToNext()) {
            String valueofcol1 = cur.getString(1);
            String valueofcol2 = cur.getString(2);
  //                Log.e("---****---", "***********   col 1 = " + valueofcol1);
  //                Log.e("---****---", "***********   col 2 = " + valueofcol2);
            collist_1.add(valueofcol1);
            collist_2.add(valueofcol2);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.close();
    }
    printList();
    setDataIntoList();
}
private void printList() {
    for (int i = 0; i < collist_1.size(); i++) {
        Log.e("***************",
                collist_1.get(i) + " --- " + collist_2.get(i));
    }
}
private void setDataIntoList() {
    // create the list item mapping
    String[] from = new String[] { "col_1", "col_2" };
    int[] to = new int[] { R.id.col1tv};
    // prepare the list of all records
    List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
    for (int i = 0; i < collist_1.size(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("col_1", collist_1.get(i));
        map.put("col_2", collist_2.get(i));
        fillMaps.add(map);
    }
    // fill in the grid_item layout
    SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
            R.layout.custom, from, to);
    list_lv.setAdapter(adapter);
}
}

谢谢!

1 个答案:

答案 0 :(得分:1)

DatabaseHelper有很多有用的方法。

要删除它,最好使用以下内容:

public boolean delete(int ID){
  return db.delete(TABLE_NAME, KEY + "=" + ID, null) > 0;
}

如果您需要删除所有行,这适合您:

db.delete(TABLE_NAME, null, null);

这将删除KEY = ID的所有行,您可以使用Android studio's提示

根据需要排列代码