简体   繁体   中英

Unable to update a record in sqlite database

I am making this sample app that will insert, update, delete and retrieve data from database. now the problem I am facing is how to update the record. I know I have to pass Id but how.

MainActivity.java :

public class MainActivity extends Activity {

Button btnSubmit, btnUpdate, btnDelete;
EditText UserName, FirstName, LastName, txtPassword;
RunDatabase db;

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

    db = new RunDatabase(this);

    UserName = (EditText) findViewById(R.id.User_Name);
    FirstName = (EditText) findViewById(R.id.First_Name);
    LastName = (EditText) findViewById(R.id.Last_Name);
    txtPassword = (EditText) findViewById(R.id.Password);

    btnSubmit = (Button) findViewById(R.id.btn_Submit);
    btnSubmit.setOnClickListener  (new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            addRow();
        }
    });

    btnUpdate = (Button) findViewById(R.id.btn_Update);
    btnUpdate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            updateRow();
        }
    });

}   

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private void addRow()
{
    try
    {
        db.addRow
        (
                UserName.getText().toString(),
                FirstName.getText().toString(),
                LastName.getText().toString(),
                txtPassword.getText().toString()
        );

        // remove all user input from the Activity
        emptyFormFields();
    }
    catch (Exception e)
    {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }
 }


private void updateRow()
{
    try
    {

        db.updateRow
        (
            UserName.getText().toString(),
            FirstName.getText().toString(),
            LastName.getText().toString(),
            txtPassword.getText().toString()
        );

        emptyFormFields();
    }
    catch (Exception e)
    {
        Log.e("Update Error", e.toString());
        e.printStackTrace();
    }
}

private void emptyFormFields()
{
    User_Id.setText("");
    FirstName.setText("");
    LastName.setText("");
    UserName.setText("");
    txtPassword.setText("");
}
}

RunDatabase.java:

 public class RunDatabase {

Context context;

private SQLiteDatabase db; // a reference to the database manager class.
private final String DB_NAME = "Records"; // the name of our database
private final int DB_VERSION = 1; // the version of the database

// the names for our database columns
private final String TABLE_NAME = "tblRecords";
private final String TABLE_ROW_ID = "id";
private final String TABLE_ROW_ONE = "UserName";
private final String TABLE_ROW_TWO = "FirstName";
private final String TABLE_ROW_THREE = "LastName";
private final String TABLE_ROW_FOUR = "Password";

// the beginnings our SQLiteOpenHelper class

    public void onCreate(SQLiteDatabase db)
    {
        String newTableQueryString =    
            "create table " +
            TABLE_NAME +
            " (" +
        TABLE_ROW_ID + " integer primary key autoincrement not null, " +
            TABLE_ROW_ONE + " text, " +
            TABLE_ROW_TWO + " text, " +
            TABLE_ROW_THREE + " text, " +
            TABLE_ROW_FOUR + " text" +
            ");";
     System.out.println(newTableQueryString);
        // execute the query string to the database.
        db.execSQL(newTableQueryString);
    }

    public RunDatabase(Context context)
    {
        this.context = context;

        // create or open the database
    CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
        this.db = helper.getWritableDatabase();
    }


public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public void addRow(String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
    // this is a key value pair holder used by android's SQLite functions
    ContentValues values = new ContentValues();

    values.put(TABLE_ROW_ONE, rowStringOne);
    values.put(TABLE_ROW_TWO, rowStringTwo);
    values.put(TABLE_ROW_THREE, rowStringThree);
    values.put(TABLE_ROW_FOUR, rowStringFour);

    try
    {
        db.insert(TABLE_NAME, null, values);
    }
    catch(Exception e)
    {
        Log.e("DB ERROR", e.toString()); 
        e.printStackTrace(); // prints the stack trace to the log
    }
}

public void updateRow(long rowID, String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{

    ContentValues values = new ContentValues();
    values.put(TABLE_ROW_ONE, rowStringOne);
    values.put(TABLE_ROW_TWO, rowStringTwo);
    values.put(TABLE_ROW_THREE, rowStringThree);
    values.put(TABLE_ROW_FOUR, rowStringFour);

    try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);}
    catch (Exception e)
    {
        Log.e("DB Error", e.toString());
        e.printStackTrace();
    }
}
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // NOTHING TO DO HERE. THIS IS THE ORIGINAL DATABASE VERSION.
        // OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THE DATABASE.
    }
}
}

你可以这样试试——

db.update(TABLE_NAME, values, TABLE_ROW_ID + "=?", String[]{rowID});

1. In your create table String,

String newTableQueryString =    
            "create table " +
            TABLE_NAME +
            " (" +
        TABLE_ROW_ID + " integer primary key autoincrement not null, " +
            TABLE_ROW_ONE + " text, " +
            TABLE_ROW_TWO + " text, " +
            TABLE_ROW_THREE + " text, " +
            TABLE_ROW_FOUR + " text" +
            ");";  

The ROW_ID is an integer, so in your function updateRow() , the data type for parameter of rowID should be integer, which is passed in the "where" clause. So should change
-> public void updateRow(long rowID, String rowStringOne,...

2. To identify the row you have added, you need to have a primary key which you will be able to identify on the basis of the entry.

Auto increment integer is good for ensuring that the database will have a new row each time,
but the primary key you need should be something you will know to differentiate entries.

Can try a derived key which would be another column in your db, to insert the same with adding rows would be like:

String customPrimaryKey="UserName.getText().toString()+FirstName.getText().toString()+txtPassword.getText().toString()";
db.updateRow
        (
            UserName.getText().toString(),
            FirstName.getText().toString(),
            LastName.getText().toString(),
            txtPassword.getText().toString(),
// add one more value for a particular entry-a primary key for You to identify that row
            customPrimaryKey
        );  

So you have a way to identify which row to update then, and pass the same in the updateRow() parameters for the where clause

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM