Home » Android » How to implement a reset password feature in my android app?

How to implement a reset password feature in my android app?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’ve been developing an app and I want to implement a password reset in it. I have created codes now and it does not seem to be working. Here is the situation: When I click the “Change Password” button, the app crashes and restarts. There are no errors on runtime. Someone, please help. Thanks.

ResetPasswordActivity.Java

package org.cvsuimus.theflare;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.kosalgeek.android.md5simply.MD5;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.ExceptionHandler;
import com.kosalgeek.genasync12.PostResponseAsyncTask;

import java.util.HashMap;

import static org.cvsuimus.theflare.StartupActivity.PREFS_NAME;

public class ResetPasswordActivity extends AppCompatActivity implements View.OnClickListener {

    final String TAG = "ResetPasswordActivity";
    EditText newPass, confirmPass;
    TextView studentNumber;
    Button btnChangePassword;

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

        studentNumber = (TextView) findViewById(R.id.resetStudNum);
        newPass = (EditText) findViewById(R.id.etNewPass);
        confirmPass = (EditText) findViewById(R.id.etConfirmPassword);

        btnChangePassword = (Button)findViewById(R.id.btn_ChangePassword);
        btnChangePassword.setOnClickListener(this);

        SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String studNumString = pref.getString("studentNumber", "");
        studentNumber.setText(String.valueOf(studNumString));
    }

    private boolean emptyValidate(EditText newPass, EditText confirmPass){
        String newPassString = newPass.getText().toString();
        String confirmPassString = confirmPass.getText().toString();
        return (newPassString.isEmpty() && confirmPassString.isEmpty());
    }

    private boolean isNetworkAvailable()
    {
        final ConnectivityManager connectivityManager = ((ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE));
        return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
    }

    private boolean passwordLengthValidate(EditText newPass){
        String password = newPass.getText().toString();
        return (password.length() >= 6);
    }

    String newPassString = "";
    String studentNumString = "";
    @Override
    public void onClick(View v) {
        if (!emptyValidate(newPass, confirmPass)) {
            if(passwordLengthValidate(newPass)) {
                if (isNetworkAvailable()) {
                    newPassString = MD5.encrypt(newPass.getText().toString());
                    studentNumString = studentNumber.getText().toString();

                    HashMap<String, String> changePassData = new HashMap<>();
                    changePassData.put("studentNumber", studentNumString);
                    changePassData.put("newPass", newPassString);

                    PostResponseAsyncTask changePasswordTask = new PostResponseAsyncTask(this, changePassData, new AsyncResponse() {
                        @Override
                        public void processFinish(String s) {
                            Log.d(TAG, s);
                            if (s.contains("ChangePasswordSuccess")) {
                                Intent in = new Intent(getApplicationContext(), MainPageActivity.class);
                                startActivity(in);
                            } else { // else there is error in changing password
                                Toast.makeText(getApplicationContext(), "Something went wrong. Cannot change update password.", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                    changePasswordTask.setExceptionHandler(new ExceptionHandler() {
                        @Override
                        public void handleException(Exception e) {
                            if (e != null && e.getMessage() != null) {
                                Log.d(TAG, e.getMessage());
                            }
                        }
                    });
                    changePasswordTask.execute("http://192.168.0.31/theflare/app/changepassword.php");
                }
                else { // if device can't connect to the internet
                    Toast.makeText(getApplicationContext(), "Cannot connect to the server!", Toast.LENGTH_LONG).show();
                }
            }
            else { // if etPassword > 7
                Toast.makeText(getApplicationContext(), "Password must be 6 characters and above!", Toast.LENGTH_LONG).show();
            }
        }
        else { // if fields are empty
            Toast.makeText(getApplicationContext(), "Please fill up all fields!", Toast.LENGTH_LONG);
        }
    }
}

activity_reset_password.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    tools:context="org.cvsuimus.theflare.ResetPasswordActivity">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp">


        <TextView
            android:id="@+id/textView6"
            android:layout_width="368dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="32dp"
            android:text="@string/reset_header"
            android:textAlignment="center"
            android:textAppearance="@style/TextAppearance.AppCompat.Display1"
            android:textColor="@color/primaryTextColor"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView7"
            android:layout_width="160dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="32dp"
            android:text="@string/reset_studNum"
            android:textColor="@color/primaryTextColor"
            android:textSize="18sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView6" />

        <TextView
            android:id="@+id/resetStudNum"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="32dp"
            android:textColor="@color/primaryTextColor"
            android:textSize="18sp"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintLeft_toRightOf="@+id/textView7"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView6" />

        <TextView
            android:id="@+id/textView9"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="15dp"
            android:text="@string/enter_password"
            android:textColor="@color/primaryTextColor"
            android:textSize="18sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView7" />

        <EditText
            android:id="@+id/etNewPass"
            android:layout_width="255dp"
            android:layout_height="44dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="15dp"
            android:ems="10"
            android:inputType="textPassword"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toRightOf="@+id/textView9"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/resetStudNum" />

        <TextView
            android:id="@+id/textView14"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:text="@string/confirm_password"
            android:textColor="@color/primaryTextColor"
            android:textSize="18sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView9" />

        <EditText
            android:id="@+id/etConfirmPass"
            android:layout_width="252dp"
            android:layout_height="67dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:ems="10"
            android:inputType="textPassword"
            app:layout_constraintLeft_toRightOf="@+id/textView14"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/etNewPass" />

        <Button
            android:id="@+id/btn_ChangePassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="24dp"
            android:background="@color/primaryColor"
            android:text="@string/btn_changepw"
            android:textAppearance="@style/TextAppearance.AppCompat.Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/etConfirmPass"
            app:layout_constraintVertical_bias="1.0" />

    </android.support.constraint.ConstraintLayout>

</ScrollView>

changepassword.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['newPass']) && !empty(isset($_POST['newPass'])) 
  && isset($_POST['confirmPass']) && !empty(isset($_POST['confirmPass']))){ 
    include_once("../connection.php"); 
    $studentNumber = $_POST['studentNumber'];
    $newPass = $_POST['newPass']; 

    $sql = "UPDATE users SET password='$newPass' where studentNumber='$studentNumber'";
    $result = $conn->query($sql); 
  if ($result->num_rows > 0) { 
    echo "ChangePasswordSuccess"; 
  } 
  else { 
    echo "Error: " . $sql . "<br>" . $conn->error; 
  }
}?>

Logcat

FATAL EXCEPTION: main Process: org.cvsuimus.theflare, PID: 31500
   java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
       at org.cvsuimus.theflare.ResetPasswordActivity.emptyValidate(ResetPasswordActivity.java:51)
       at org.cvsuimus.theflare.ResetPasswordActivity.onClick(ResetPasswordActivity.java:69)
       at android.view.View.performClick(View.java:4848)
       at android.view.View$PerformClick.run(View.java:20262)
       at android.os.Handler.handleCallback(Handler.java:815)
       at android.os.Handler.dispatchMessage(Handler.java:104)
       at android.os.Looper.loop(Looper.java:194)
       at android.app.ActivityThread.main(ActivityThread.java:5631)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Answers:

I have found the issue. It’s in this line:
confirmPass = (EditText) findViewById(R.id.etConfirmPassword);
Turns out that the id of the EditText is android:id="@+id/etConfirmPass". So I had to change it to confirmPass = (EditText) findViewById(R.id.etConfirmPass);. The button is now clickable. My only problem is it doesn’t really change the password based on the SharedPreferences studentNumber. But nevertheless, thanks to all that helped!