UPDATE not working in sqlite android - android

I have a login and reset password activity. When I enter the new updated password and try to login again, I cannot do so with the new password. Logging in with the old password works fine. Basically, the password field is not getting updated/overwritten.
There is no error in the logcat. Just that the password is not updated.
Please help as I am new to android development.
Code for update( DataRegister is the class with GET AND SET functions):
public int updatePassword(DataRegister dataregister) {
db = dbHelper.getWritableDatabase();
ContentValues updated = new ContentValues();
updated.put("PASSWORD", dataregister.getPASSWORD());
return db.update(DataRegister.TABLE, updated, "EMAIL=?" , new String[]{email});
}
Code for retrieval:
public String getPass(DataRegister dataRegister) {
db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(DataRegister.TABLE, null, "EMAIL=?",
new String[]{dataRegister.getEMAIL()}, null, null, null, null);
if (cursor != null && cursor.moveToFirst())
{
pass = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
}
return pass;
// return contact
}
Code for Login:
String email = editTextUserName.getText().toString();
dataRegister.setEMAIL(email);
String password = editTextPassword.getText().toString();
dataRegister.setPASSWORD(password);
String storedPassword = loginDataBaseAdapter.getSinlgeEntry(dataRegister);
Toast.makeText(Login.this, storedPassword,Toast.LENGTH_LONG).show();
Boolean a=loginDataBaseAdapter.isExist(dataRegister.getEMAIL());
validation = getSharedPreferences("myShaPreferences", Context.MODE_PRIVATE);
if (password.equals(storedPassword)) {
Toast.makeText(Login.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
}
else {
Toast.makeText(Login.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
}
}
});
Code for reset password:
public class ResetPassword extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
email = (EditText) findViewById(R.id.em2);
dataRegister=new DataRegister();
loginDataBaseAdapter = new DatabaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
pass = (EditText) findViewById(R.id.text12);
conpass = (EditText) findViewById(R.id.text13);
email1 = email.getText().toString();
dataRegister.setEMAIL(email1);
pass1 = pass.getText().toString();
conpass1 = conpass.getText().toString();
dataRegister.setPASSWORD(conpass1);
Button btnReset = (Button) findViewById(R.id.btnReset);
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (pass1.equals(conpass1)) {
loginDataBaseAdapter.updatePassword(email1,pass1);
String newpass = loginDataBaseAdapter.getPass(dataRegister);
Toast.makeText(ResetPassword.this, newpass, Toast.LENGTH_LONG).show();
Intent intent = new Intent(ResetPassword.this, Login.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(ResetPassword.this,
"Password does not match",
Toast.LENGTH_LONG).show();
}
}
});

Maybe this can help you for updating data :
public void updating( Password password) {
ContentValues value = new ContentValues();
value.put( PasswordDAO.LOGIN, password.getlogin() );
value.put( PasswordDAO.PASSWORD, password.getPassword());
this.mDb.update( PasswordDAO.NAME_TABLE, value, PasswordDAO.ID + " = ?", new String[]{String.valueOf(password.getId())} );
}
PasswordDao is the name of the class who extends the DAOBase, NAME_TABLE is "Password", and you need to create a class password with id login and password.
hope this can help you

Related

database created? login button does nothing.AndroidStudio,sqlite

Sorry for my English.
I have created a simple application of log and registry with database.
if I register a user I need to log and that the application takes me to another screen.
the problem is not if the logs are created, the login button does absolutely nothing
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button registrar;
Button iniciar;
BaseDatos bd = new BaseDatos(this, "bd1", null, 1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registrar = (Button) findViewById(R.id.registro);
registrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent m = new Intent(getApplicationContext(), Registrar.class);
startActivity(m);
}
});
iniciar = (Button) findViewById(R.id.iniciar);
iniciar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.editText);
EditText editText1 = (EditText) findViewById(R.id.editText2);
try {
Cursor cursor = bd.check(editText.getText().toString(), editText1.getText().toString());
if (cursor.getCount() > 0) {
Intent m = new Intent(getApplicationContext(), Musica.class);
startActivity(m);
} else {
Toast.makeText(getApplicationContext(), "Usuario o contraseña incorrectos", Toast.LENGTH_LONG).show();
}
editText.setText("");
editText1.setText("");
editText.findFocus();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
}
Registrar.java
public class Registrar extends AppCompatActivity {
EditText nombre, usuario, password, puesto;
Button reg;
BaseDatos bd = new BaseDatos(this, "bd1",null,1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
final BaseDatos Bdu = new BaseDatos(this, "bd1", null, 1);
reg = (Button) findViewById(R.id.reg);
nombre = (EditText) findViewById(R.id.nombre);
usuario = (EditText) findViewById(R.id.usuario);
password = (EditText) findViewById(R.id.password);
puesto = (EditText) findViewById(R.id.puesto);
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bd.abrir();
bd.nuevosUsuarios(String.valueOf(nombre.getText()),
String.valueOf(usuario.getText()),
String.valueOf(password.getText()),
String.valueOf(puesto.getText()));
bd.cerrar();
Toast.makeText(getApplicationContext(), "Registro guardado con exito", Toast.LENGTH_LONG).show();
Intent m = new Intent(getApplicationContext(), MainActivity.class);
startActivity(m);
}
});
}
}
BaseDatos.java
public class BaseDatos extends SQLiteOpenHelper {
public BaseDatos(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate (SQLiteDatabase db){
String query = ("create table trabajadores(_ID integer primary key autoincrement, Nombre text, Usuario text, Password text,Puesto text)");
}
#Override
public void onUpgrade (SQLiteDatabase db,int oldVersion, int newVersion){
db.execSQL("insert into trabajadores values(01,'admin','admin')");
}
public void abrir ()
{
this.getWritableDatabase();
}
public void cerrar ()
{
this.close();
}
public void nuevosUsuarios (String nom, String usr, String pass, String pues){
ContentValues valores = new ContentValues();
valores.put("Nombre", nom);
valores.put("Usuario", usr);
valores.put("Password", pass);
valores.put("Puesto", pues);
this.getWritableDatabase().insert("trabajadores", null, valores);
}
public Cursor check( String usr, String pass) throws SQLException{
Cursor rcursor=null;
rcursor=this.getReadableDatabase().query("trabajadores", new String[]{"_ID,","Nombre","Usuario","Password","Puesto"},
"Usuario like '"+usr+"'"+" and Password like'"+pass+"'",null,null,null,null);
return rcursor;
}
}
You aren't creating the table.
In the BaseDatos.java in the onCreate method add the line :-
db.execSQL(query);
So the method should be :-
#Override
public void onCreate (SQLiteDatabase db){
String query = ("create table trabajadores(_ID integer primary key autoincrement, Nombre text, Usuario text, Password text,Puesto text)");
db.execSQL(query);
}
There is also an issue the the check method that will result in a SQlite syntax error due to an extra ,.
Instead of
rcursor=this.getReadableDatabase().query("trabajadores", new String[]{"_ID,","Nombre","Usuario","Password","Puesto"},
"Usuario like '"+usr+"'"+" and Password like'"+pass+"'",null,null,null,null);
it should be
rcursor=this.getReadableDatabase().query("trabajadores", new String[]{"_ID","Nombre","Usuario","Password","Puesto"},
"Usuario like '"+usr+"'"+" and Password like'"+pass+"'",null,null,null,null);
(comma removed after _ID).
Note before running after making the change, delete the App's data or uninstall the App.
Demo
When started :-
Note all displays have the Activity's name (as highlighted).
The red arrow indicates the button that was clicked
At this stage clicking the INICIAR button just issues a toast.
Clicking the Registrar button :-
User number(1), username (Fred), password (password) and puesto (blah) are entered and the Reg buttons is clicked.
Returns to the MainActivity
Fred and password are entered into the Username and password and the INICIAR button is clicked.
The Musica Acivity

How to get user data with SharedPreferences from RegisterActivity

i programmed my register activity to get my user details and store it with SharePreferences
Now , im trying to get those values stored in the data to log in in my app but it seems im missing something, when i put anything in my edittexts in my login layout it logs in without checking the user
RegisterActivity.class
public class RegistrarUsuario extends AppCompatActivity {
private Button mBtnRegistrarUsuario;
private TextView mRegistrarTxt;
private EditText mUsername,mPassword,mSecondPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrar_usuario);
mRegistrarTxt = (TextView) findViewById(R.id.titulo2);
mUsername = (EditText) findViewById(R.id.nombreUsuario);
mPassword = (EditText) findViewById(R.id.primeraContraseña);
mSecondPassword = (EditText) findViewById(R.id.segundaContraseña);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mRegistrarTxt.setTypeface(fuente);
mBtnRegistrarUsuario = (Button) findViewById(R.id.btnRegistrarUsuario);
mBtnRegistrarUsuario.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String secondpassword = mSecondPassword.getText().toString().trim();
if(username.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese un usuario.", Toast.LENGTH_SHORT).show();
}
else if(password.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese contraseña.", Toast.LENGTH_SHORT).show();
}
else if(secondpassword.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Confirme su contraseña.", Toast.LENGTH_SHORT).show();
}
else if(password.equals(secondpassword)){
SharedPreferences.Editor editor = preference.edit();
editor.putString("Username",username);
editor.putString("Password",password);
editor.putString("SecondPassword",secondpassword);
editor.commit();
finish();
Toast.makeText(RegistrarUsuario.this, "Usuario creado con exito!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegistrarUsuario.this,PantallaPrincipal.class);
startActivity(intent);
}
else{
Toast.makeText(RegistrarUsuario.this, "No coinciden las contraseñas.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
** LoginActivity.class**
public class MainActivity extends AppCompatActivity {
private EditText mUsername,mPassword;
private Button mLoginBtn,mBtnRecuperar,mBtnRegistrar;
private TextView mTextView;
private static String usuario ="admin";
private static String contraseña="123";
private final String KEY_USERNAME = "username";
private final String KEY_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = (EditText) findViewById(R.id.usuario);
mPassword = (EditText) findViewById(R.id.contraseña);
mLoginBtn = (Button) findViewById(R.id.btnIngresar);
mTextView = (TextView) findViewById(R.id.titulo);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mTextView.setTypeface(fuente);
mBtnRecuperar = (Button) findViewById(R.id.btnRecuperar);
mBtnRecuperar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RecuperarContrasenia.class);
startActivity(intent);
}
});
mBtnRegistrar = (Button) findViewById(R.id.btnRegistrar);
mBtnRegistrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RegistrarUsuario.class);
startActivity(intent);
}
});
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String userDetails = preference.getString(username + password + "data","No information on that user.");
SharedPreferences.Editor editor = preference.edit();
editor.putString("display",userDetails);
editor.commit();
if(mUsername.getText().toString().trim().length() == 0 && mPassword.getText().toString().trim().length() == 0 ){
Toast.makeText(MainActivity.this, "Los campos estan vacios", Toast.LENGTH_SHORT).show();
}else
{
if(mUsername.getText().toString().trim().equals(username) && mPassword.getText().toString().trim().equals(password)){
Toast.makeText(MainActivity.this, "Bienvenido", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,PantallaPrincipal.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Los campos son incorrectos", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
i dont know what im missing that it dont verify the user if exists or login with the credentials i make in RegisterActivity.class
thanks
You are never retrieving the username and password from SharedPreferences. And at the end you are checking the information the user puts in the TextEdits against itself so the validation always returns true to any non empty value.
Change this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
To this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = preference.getString("Username", "");
String password = preference.getString("Password", "");

query is not executed in sql server with android app

I have no idea why is this happening, I mean the connection with the database is established, but the query itself is not giving any output. No exceptions or anything, I press the button and nothing is happening
Here's the Java code:
public class LogIn extends AppCompatActivity {
EditText pass;
EditText usname;
Connection con = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
connectTodatabase();
Button btn=(Button) findViewById(R.id.button);
TextView txtView1=(TextView)findViewById(R.id.textView1);
txtView1.setText("ffgf");
}
public void logIn(View v)
{
EditText usname=(EditText) findViewById(R.id.editText);
EditText pass=(EditText) findViewById(R.id.editText2);
TextView txtView1=(TextView)findViewById(R.id.textView1);
String username=usname.getText().toString();
String password=pass.getText().toString();
txtView1.setText("ffgf");
String SQLStatment = "select * from users where usname='"+username+"' AND uspass='"+password+"'";
try {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(SQLStatment);
int count=rs.getRow();
txtView1.setText("ffgf");
if(count>0)
{
Toast.makeText(this,"Query success",Toast.LENGTH_LONG).show();
Intent intent=new Intent(getBaseContext(),appPage.class);
startActivity(intent);
}
else
{
txtView1.setText("incorrect");
}
}
catch(Exception e)
{
txtView1.setText(e.getMessage());
}
}
public void connectTodatabase()
{
Connection con;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String url = "jdbc:jtds:sqlserver://192.168.111.14:1433;instanceName=SQLEXPRESS;DatabaseName=test";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "sam";
String password = "111";
// Declare the JDBC objects.
try
{
// Establish the connection.
Class.forName(driver);
con = DriverManager.getConnection(url, userName, password);
// Create and execute an SQL statement that returns some data.
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getApplicationContext(), "aa" + ex.getMessage().toString() + "ss", Toast.LENGTH_LONG).show();
}
}
}

Open different activities according to the login credentials entered

Below is my login activity.
It has a simple layout,where user enters his username and password and click login button.
A list of username and passwords is being stored in ms sql server.
And connection is also being established.
But the problem is on different combinations of usernames and passwords i want to open different activities.
How can i do it?
Lets say I have two combinations of username and password in my database-1.username1 , password1 (should open activity 1 on login button click)
2.username2, password2 (shoud open activity 2 on login button click)
Here is the code-----
public class Login extends Activity
{
private static final String DUMMY_CREDENTIALS = "user#test.com:hello";
// private UserLoginTask userLoginTask = null;
private View loginFormView;
private View progressView;
ConnectionClass connectionClass;
private AutoCompleteTextView emailTextView;
private EditText passwordTextView;
private Button btnlogin;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
connectionClass = new ConnectionClass();
emailTextView = (AutoCompleteTextView) findViewById(R.id.email);
//loadAutoComplete();
passwordTextView = (EditText) findViewById(R.id.password);
btnlogin=(Button) findViewById(R.id.email_sign_in_button);
class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
String userid = emailTextView.getText().toString();
String password = passwordTextView.getText().toString();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(Login.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess) {
Intent i = new Intent(Login.this, Activity1.class);//For any combination ,it will open activity1 now.
startActivity(i);
finish();
}
}
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select EmailID,Password from Login_DB where EmailID='" + userid + "' and Password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successfull";
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
}
return z;
}
}
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();// this is the Asynctask
doLogin.execute("");
}
});
}
}
Create a table in your database that links usernames to activities, and then query it after authenticating the user.

about update data in Android Studio and SQlite

I have 2 questions want to ask about android studio and sqlite.
1) I am trying to run my project in emulator or phone. When I want to return to previous activity by pressing the return button(return function for phone) but it close all my project.But I saw my friend's can return to previous activity by pressing the return button.May I know how and why??
2) I had done update function for my project.The situation is when userA go to "view profile" activity and click edit info, another activity that call "updateinfo" will come out.Then after userA update his information by clicking update button.It's successful update and go back to "view profile" activity to see his updated profile.
But the problem I faced is it does not show out the updated information.It just show a blank "view profile" activity without any information that updated or haven updated.
What should I do?
here my database update function
public boolean updateProfile(String username, String password, String email, String phone)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put (COL_2,username);
values.put(COL_3,password);
values.put(COL_4,email);
values.put(COL_5,phone);
db.update(Table_NAME,values,COL_2 + "=?",new String[]{username});
db.close();
return true;
}
here is my updateinfo activity function
public class EditProfile extends AppCompatActivity {
EditText etEmail,etPhone,etPassword,etConPassword,etUsername;
String password,conpassword,Email,Phone;
Button bUpdate;
DatabaseOperations DB = new DatabaseOperations(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
etEmail = (EditText) findViewById(R.id.etEmail);
etPhone = (EditText) findViewById(R.id.etPhone);
etPassword = (EditText) findViewById(R.id.etPassword);
etConPassword = (EditText) findViewById(R.id.etConPassword);
etUsername = (EditText) findViewById(R.id.etUsername);
bUpdate = (Button) findViewById(R.id.bUpdate);
Intent i = getIntent();
String email = i.getStringExtra("email");
etEmail.setText(email);
String phone = i.getStringExtra("phone");
etPhone.setText(phone);
String username = i.getStringExtra("username");
etUsername.setText(username);
bUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
password = etPassword.getText().toString();
conpassword = etConPassword.getText().toString();
Email = etEmail.getText().toString();
Phone = etPhone.getText().toString();
if (!(password.equals(conpassword))) {
Toast.makeText(getBaseContext(), "Passwords are not matching", Toast.LENGTH_LONG).show();
etPassword.setText("");
etConPassword.setText("");
etEmail.setText("");
etPhone.setText("");
} else if (etPassword.length() == 0 || etConPassword.length() == 0 || etEmail.length() == 0 || etPhone.length() == 0) {
etPassword.setError("Please complete all information");
etConPassword.setError("Please complete all information");
etEmail.setError("Please complete all information");
etPhone.setError("Please complete all information");
} else if (etPassword.length() < 6) {
etPassword.requestFocus();
etPassword.setError("Password at least 6 characters");
etPassword.setText("");
etConPassword.setText("");
etEmail.setText("");
etPhone.setText("");
} else {
boolean isUpdate = DB.updateProfile(etUsername.getText().toString(),etPassword.getText().toString(),etEmail.getText().toString(),etPhone.getText().toString());
if(isUpdate == true) {
Toast.makeText(getBaseContext(), "Update Success", Toast.LENGTH_LONG).show();
Intent i = new Intent(EditProfile.this, MyProfile.class);
startActivity(i);
finish();
}
else
{
Toast.makeText(getBaseContext(), "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
}
});
}
and here is my viewprofile activity function
public class MyProfile extends AppCompatActivity {
EditText etName,etEmail,etPhone,etShow;
Button bEdit;
String fullname,email,phone;
DatabaseOperations db = new DatabaseOperations(this);
PersonalData profileInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etPhone = (EditText) findViewById(R.id.etPhone);
bEdit = (Button) findViewById(R.id.bEdit);
etShow = (EditText) findViewById(R.id.etShow);
fullname = etName.getText().toString();
email = etEmail.getText().toString();
phone = etPhone.getText().toString();
Intent i = getIntent();
String username = i.getStringExtra("username");
etShow.setText(username);
profileInfo = db.getAllinfo(username);
etName.setText(profileInfo.get_name());
etEmail.setText(profileInfo.get_email());
etPhone.setText(profileInfo.get_phone());
bEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyProfile.this,EditProfile.class);
i.putExtra("email", etEmail.getText().toString());;
i.putExtra("phone", etPhone.getText().toString());;
i.putExtra("username", etShow.getText().toString());
startActivity(i);
finish();
}
});
}
you always start new activity and finish the last activity
startActivity(i);
finish();
dont finish it if you want to go back later, you can go back to last activity with finish(); or pressing back in phone
you just need to call finish() when update success (you need to implement answer number 1 first)
Toast.makeText(getBaseContext(), "Update Success", Toast.LENGTH_LONG).show();
Intent i = new Intent(EditProfile.this, MyProfile.class);
startActivity(i);
finish();
in MyProfile make the username variable global
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
....
username = i.getStringExtra("username");
....
}
last,this code need to be inside onResume()
etShow.setText(username);
profileInfo = db.getAllinfo(username);
etName.setText(profileInfo.get_name());
etEmail.setText(profileInfo.get_email());
etPhone.setText(profileInfo.get_phone());
public boolean update(editProfile.EUsers eusers){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalues = new ContentValues();
String username = eusers.getUsername();
String password = eusers.getPassword();
int id = eusers.getId();
contentvalues.put(editProfile.EUsers.COL3_PASSWORD,password);
contentvalues.put(editProfile.EUsers.COL2_USERNAME,username);
int res =db.update(editProfile.EUsers.TABLE_NAME,values,editProfile.EUsers.COL1_ID+" = ?",new String[]{String.valueOf(id)});
if(res >0)
return true;
return false;
}

Categories

Resources