How to update a value using SQLite in android

  • Replies:1
Daniel Cowan
  • Forum posts: 2

Apr 4, 2016, 9:35:30 PM via Website

Hi, I am a beginner at programming and android and everything really but my course likes to throw me in the deep end. Anyway have an android app that a user can create a user account and will save the values in an SQLite datebase, those values are username and password. My question is I need to add a page to my android app that will allow the users to change the password meaning they need to change the password in the database and this is where I get completely lost and could use some guidance.

Here is my ChangePassword Activity that currently has nothing of great use as I am so lost.

public void onClickUpdate(View v) {
    if (v.getId() == R.id.Bupdate) {

        //Take all text field values
        EditText findUname = (EditText) findViewById(R.id.TFfindusername);
        EditText newPass1 = (EditText) findViewById(R.id.TFnewpassword);
        EditText newPass2 = (EditText) findViewById(R.id.TFverifynewpassword);

        // Converts them to strings

        String newunamestr = findUname.getText().toString();
        String newpass1str = newPass1.getText().toString();
        String newpass2str = newPass2.getText().toString();

        //Check if passwords match
        if (!newpass1str.equals(newpass2str)) {
            // Show Toast Message
            Toast pass = Toast.makeText(ChangePassword.this, "Passwords Do Not Match!", Toast.LENGTH_SHORT);
            pass.show();

            // Clears Text fields if passwords do not match
            newPass1.setText("");
            newPass2.setText("");
        } else {
            // Code to update password goes here


            Toast created = Toast.makeText(ChangePassword.this, "Password Successfuly Changed", Toast.LENGTH_SHORT);
            created.show();
        }
    }
}

I need to add stuff to the else statement that will allow me to update the password in the database with the new password which is newpass1str. Ignore the password 2 part that is just for button click validation.

That activity communicates to the database using the following line at the top of the activity.

 DatabaseHelper helper = new DatabaseHelper(this);

Below is my database page that creates the database etc.

public class DatabaseHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null , " +
        "uname text not null , pass text not null);";

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

} //Ends DatabaseHelper Constructor

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(TABLE_CREATE);
    this.db = db;
} // Ends onCreate


public void insertContact(Contact c) {
    db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    String query = "select * from contacts";
    Cursor cursor = db.rawQuery(query, null);
    int count = cursor.getCount();

    values.put(COLUMN_ID, count);
    values.put(COLUMN_UNAME, c.getUname());
    values.put(COLUMN_PASS, c.getPass());

    // Inserts values
    db.insert(TABLE_NAME, null, values);
    db.close();
}


public String searchPass(String uname) {
    db = this.getReadableDatabase();
    String query = "select uname, pass from " + TABLE_NAME;
    Cursor cursor = db.rawQuery(query, null);
    String a, b;
    b = "not found";
    if (cursor.moveToFirst()) {
        do {
            a = cursor.getString(0); // Username

            if (a.equals(uname)) {
                b = cursor.getString(1); // Password
                break;
            }
        }
        while (cursor.moveToNext());
    }
    return b;
} // Ends searchPass


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
    db.execSQL(query);
    this.onCreate(db);
} // Ends onUpgrade

} // Ends DatabaseHelper

I will say I followed a tutorial for the that code above and I managed some slight changes but I don't understand any of it enough to work it out and the guides online completely go over my head. What would I need to add to both of these activities for me to be able to change the password for the user mentioned in the change password form. If you need any more information or I am in the wrong place and stupid please don't hesitate to tell me.

Oh I don't think this page is useful here but I also have an activity called contact which is used for the database would I need to add anything to that.

public class Contact {
int id;
String uname, pass;

// Set the ID
public void setId(int id) {
    this.id = id;
}

// Get the ID
public int getId() {
    return this.id;
}

// Set the Username
public void setUname(String uname) {
    this.uname = uname;
}

// Get the Username
public String getUname() {
    return this.uname;
}

// Set the Password
public void setPass(String pass) {
    this.pass = pass;
}

// Get the Password
public String getPass() {
    return this.pass;
}

} // Ends Contact

Reply
REZKY AULIA PRATAMA
  • Forum posts: 5

Apr 8, 2016, 5:55:44 AM via Website

hei Daniel ,

i will make a simple code for you.

first,I will create a class which function to create a database sqlite / open db sqlite / drop table , i name it DataBaseHelper, the code :

----------------------------------------------------------------------------------- database helper --------------------------------------------------------------------------------------------------
/**
* Created by Rezky on 2016/04/08.
*/
public class DataBaseHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "myDb"; //You can change with your db name
private static final String TABLE_NAME = "contacts";

public static final String CREATE_TBL1 = "create table contacts (id integer primary key not null , uname text not null , pass text not null)";

private static DataBaseHelper instance;

public static synchronized DataBaseHelper getHelper(Context context) {
    if (instance == null)
        instance = new DataBaseHelper(context);
    return instance;
}

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

@Override
public void onOpen(SQLiteDatabase db) {
    super.onOpen(db);
    if (!db.isReadOnly()) {
        // Enable foreign key constraints
        db.execSQL("PRAGMA foreign_keys=ON;");
    }
}

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

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w("db upgrade",
                "Upgrading the database from version " + oldVersion + " to " + newVersion);
    // clear all data
    db.execSQL("DROP TABLE IF EXISTS " + CREATE_TBL1);     
}

}

---------------------------------------------------------------------- end of database helper --------------------------------------------------------------------------------

after that , i will create a class which will use database helper. this class will be function for manipulate data on database sqlite. i name it "SqliteManipulate", the code :

note : you can change this code according your needs
----------------------------------------------------------------------------------- SqliteManipulate --------------------------------------------------------------------------------------------------

public class SqliteManipulate {
public static final String TAG = "NotificationDataDAO";

private SQLiteDatabase mDatabase;
private DataBaseHelper mDbHelper;
private Context mContext;
private String[] mAllColumns ={"id ","uname","pass "};

public SqliteManipulate (Context mContext){
    this.mContext = mContext;
    mDbHelper = new DataBaseHelper(mContext);

    // open the database
    try {
        open();
    } catch (SQLException e) {
        Log.e(TAG, "SQLException on openning database " + e.getMessage());
        e.printStackTrace();
    }
}

public void open() throws SQLiteException{
    mDatabase = mDbHelper.getWritableDatabase();
}

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

//basic code for inserting data , this code based on your data
public long insDataUser(String Username, String Password){
ContentValues mValues = new ContentValues();

        mValues.put("uname", Username);
        mValues.put("pass", Password);
        long res=mDatabase.insert("contacts", null, mValues); //contacts is your table name (you can change it with you tables name)


      return res;
}

//basic code for updating data, this code based on your data
public boolean updatePassword(String Username ,String Password) {
Cursor mCursor = mDatabase.query("contacts",mAllColumns, "uname = " + mUsername ,null,null,null,null); //contacts is table name, this code query data from table contacts with value columnusername equals variabel Username

    try {

        if (mCursor != null) {
            mCursor.moveToFirst();
            while (!mCursor.isAfterLast()) {

                ContentValues values = new ContentValues();
                values.put("uname",mCursor.getString(1));
                values.put("pass", mCursor.getString(2));
                mDatabase.update("contacts", values, "id = ?",
                        new String[]{String.valueOf(mCursor.getString(0))});

                mCursor.moveToNext();
            }
            mCursor.close();

            return true;

        }else{
            return false;
        }

    } catch (SQLException e) {
        return false;
    }
}

//this code for clear all data from table contacts
public boolean deleteAllData() {
int doneDelete = 0;
doneDelete = mDatabase.delete("contacts", null, null);
return doneDelete > 0;
}

}

---------------------------------------------------------------------- end of SqliteManipulate --------------------------------------------------------------------------------

and then, in your activity, write this code :

if (!newpass1str.equals(newpass2str)) {
// Show Toast Message
Toast pass = Toast.makeText(ChangePassword.this, "Passwords Do Not Match!", Toast.LENGTH_SHORT);
pass.show();

        // Clears Text fields if passwords do not match
        newPass1.setText("");
        newPass2.setText("");
    } else {
        // Code to update password goes here
         SqliteManipulate mDao = new SqliteManipulate (getApplicationContext());
         boolean isUpdate = mDao .updatePassword(newunamestr,newPass1);

        if (isUpdate){
          Toast created = Toast.makeText(ChangePassword.this, "Password Successfuly Changed", Toast.LENGTH_SHORT);
          created.show();
        }
    }

All of this code based from my project, I've not yet tested it. so if you get an error, tell me :)

hopefully i can help you.

Reply