-6

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.
    }
}
}
Umair
  • 6,366
  • 15
  • 42
  • 50
  • 2
    This seems like a lot of code to show us considering your question is essentially "_How do I update a record in SQLLite Database_". – takendarkk Apr 25 '14 at 06:21
  • actually it's my first time so don't know how to post the through code. Sorry .. :) – Umair Apr 25 '14 at 06:24
  • Check out that : http://stackoverflow.com/questions/9798473/sqlite-in-android-how-to-update-a-specific-row or that http://stackoverflow.com/questions/10011122/android-sqlite-update-row. there are possible duplicate. – tanou Apr 25 '14 at 06:26
  • 1
    hey, Check the [Tour](http://stackoverflow.com/tour) and [Help Center](http://stackoverflow.com/help), you will know how to ask questions better and make the site useful, productive welcome to SO – Pararth Apr 25 '14 at 06:27
  • 1
    there seems to be a disconnect your updateRow signature is `public void updateRow(long rowID, String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)` and while calling it you are passing `db.updateRow ( UserName.getText().toString(), FirstName.getText().toString(), LastName.getText().toString(), txtPassword.getText().toString() );` no long id ... this should be a compile time error. – Sanjeev Apr 25 '14 at 06:31
  • @Sanjeev I entered 0 in place of long id in order to run the code. and then i tried to update the record and it throws me null pointer exception. I just wanna know how to pass the Id in updateRow in mainActivity. – Umair Apr 25 '14 at 06:36
  • you need to keep track of this id so after adding a row to table just get the id and keep it with your user information. or use user name as the key to update information as it seems it will also be unique – Sanjeev Apr 25 '14 at 06:39
  • @Darkie either way i think the data type of ROW ID being passed should be integer, not long, as you are already declaring it as an Integer -primary key – Pararth Apr 25 '14 at 06:40
  • @Sanjeev let me try using User name I think that will work... :) – Umair Apr 25 '14 at 06:45
  • @user2450263 but changing to int is not making any difference . – Umair Apr 25 '14 at 06:46
  • @Darkie you are right, currently there is no way you will identify the rowId, either return it or check my answer, i have used that derived primary key way while working with db – Pararth Apr 25 '14 at 06:54

2 Answers2

0

You could try like this-

db.update(TABLE_NAME, values, TABLE_ROW_ID + "=?", String[]{rowID});
Vikrant_Dev
  • 430
  • 2
  • 15
0

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

Pararth
  • 8,114
  • 4
  • 34
  • 51