Android从数据库中删除一行

时间:2014-11-02 21:22:36

标签: java android sqlite delete-row

我正在尝试从我的数据库中删除一行,我想读取用户输入并删除该行。我遇到的问题是获取用户信息并使用它来删除行。

这是我在行信息中读取的代码。我不知道在onClick方法中写什么或者天气甚至是正确的地方

package com.example.rory.dbtest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.pinchtapzoom.R;


public class delete extends Activity {

Button delete;
Public EditText edit1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_delete);

    delete = (Button) findViewById(R.id.button);
    editi = (EditText) findViewById(R.id.edit1);
    delete.setOnClickListener((android.view.View.OnClickListener) this);

public void onClick(View v) {
    //what code do i enter here to read in and send rowid to the db class
}

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.delete, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

这是我正在使用的数据库代码

//---deletes a particular record---
public boolean deleteContact(long rowId)
{
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

1 个答案:

答案 0 :(得分:1)

首先,您需要获取用户输入并验证它是否是与KEY_ROWID数据类型对应的有效值(例如,如果它是整数或长整数)。

假设您将KEY_ROWID设为Long数字,您可以执行以下操作:

public void onClick(View v) {
    //what code do i enter here to read in and send rowid to the db class
    //..this code:
    String userInput = edit1.getText().toString();

    //if the ROW ID its a number (long)
    try{
        long rowID = Long.parseLong(userInput);
        //call the delete method
        deleteContact(rowID);
    }catch(NumberFormatException e){
        Log.e("INPUT ERROR","Input is not a number!",e);
        //notify the user that the input is invalid.
        Toast.makeText(this,"Invalid Value!",Toast.LENGTH_LONG).show();
    }
}