从sqlite DB发送和删除记录

时间:2013-04-01 05:15:46

标签: android android-sqlite

我想从数据库向服务器发送记录然后将其删除。这是我在服务中发送和删除的代码。

      DBAdapter db=new DBAdapter(this);
        db.open();
        Cursor cursor=db.getAllData();
        if(cursor.moveToFirst())
        {
            do{
                jObject = new JSONObject();
                jObject.put("Imei", cursor.getString(1));
                jObject.put("Lat", cursor.getString(2));
                jObject.put("Long", cursor.getString(3));
                jObject.put("Gpsdatetime", cursor.getString(4));
                jObject.put("Speed", cursor.getString(5));
                jObject.put("Altitude",cursor.getString(6));
                jObject.put("Battery", cursor.getString(7));
                //jArray.put(jObject);

                String datatoServer = jObject.toString()+"\n";
                      Toast.makeText(getApplicationContext(),datatoServer, Toast.LENGTH_LONG).show();

                HttpEntity entity;
                HttpClient client = new DefaultHttpClient();
                String url = "http://url";
                HttpPost request = new HttpPost(url);
                StringEntity se = new StringEntity(datatoServer);
                se.setContentEncoding("UTF-8");
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
                entity = se;
                request.setEntity(entity);
                HttpResponse response = client.execute(request);
                entity = response.getEntity();
                db.deleteContacts(1);
            }while(cursor.moveToNext());
        }//if
        db.close();             

我对删除功能感到困惑。数据正确发送到服务器,但只删除第一行。

这是我的DBHelper类中的delete函数。它将rowid作为参数。

public boolean deleteContacts(long rowId)
{
    return db.delete(DATABASE_TABLE, KEY_ROWID+"="+rowId, null)>0;
}

4 个答案:

答案 0 :(得分:0)

如果db.deleteContacts(1);删除第一行,则可以在do...while()循环中放入一个int变量,并在每次迭代时为其提供1的增量。然后执行db.deleteContacts(your_var)

答案 1 :(得分:0)

 db.deleteContacts(1);

问题在这里你发送1作为你的方法的参数。所以它总是寻找那个有rowId

的1

使用cursor.getLong(columnIndex)  获得长期值

答案 2 :(得分:0)

假设您的db.getAllData()方法选择了所有列(包括id列列),请更改...

db.deleteContacts(1);

到...

db.deleteContacts(cursor.getLong(cursor.getColumnIndex(KEY_ROWID)));

永远不要假设任何给定的列数据在任何固定的列索引处 - 使用列名找到索引。

答案 3 :(得分:0)

试试这个,

 context.deleteDatabase(DATABASE_NAME);