vendredi 11 décembre 2015

Android - Register and Login Activity crashed when saving to SQLite

My app crashed when I try to register account and login. The information is register account activity seems not to save in the database.

User.java (User class)

public class User {

    private String _username;
    private String _fullname;
    private String _password;
    private int _hpno;

    public User() {
    }

    public User(String username, String fullname, String password, int hpno, int userstate) {
        this._username = username;
        this._fullname = fullname;
        this._password = password;
        this._hpno = hpno;
    }

    public void set_username(String _username) {
        this._username = _username;
    }

    public void set_fullname(String _fullname) {
        this._fullname = _fullname;
    }

    public void set_password(String _password) {
        this._password = _password;
    }

    public void set_hpno(int _hpno) {
        this._hpno = _hpno;
    }

    public String get_username() {
        return _username;
    }

    public String get_fullname() {
        return _fullname;
    }

    public String get_password() {
        return _password;
    }

    public int get_hpno() {
        return _hpno;
    }
}

MyDBHandler.java

public class MyDBHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "RPRQS.db";
    public static final String TABLE_USER = "User";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_FULLNAME = "fullname";
    public static final String COLUMN_PASSWORD = "password";
    public static final String COLUMN_HPNO = "hpno";
    //public static final String COLUMN_USERSTATE = "userstate";
    SQLiteDatabase db;
    private static final String CREATE_TABLE = "create table User (id integer primary key autoincrement, " +
            "username text not null, fullname text not null, password text not null, hpno integer not null);";

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

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

    // register user
    public void createUser(User user) {
        db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        String query = "SELECT * FROM User";
        Cursor cursor = db.rawQuery(query, null);
        int count = cursor.getCount();

        values.put(COLUMN_ID, count);
        values.put(COLUMN_FULLNAME, user.get_fullname());
        values.put(COLUMN_USERNAME, user.get_username());
        values.put(COLUMN_PASSWORD, user.get_password());
        values.put(COLUMN_HPNO, user.get_hpno());

        db.insert(TABLE_USER, null, values);
    }

    // match username and password
    public String searchPassword(String username) {
        db = this.getReadableDatabase();
        String query = "SELECT username, password from " + TABLE_USER;
        Cursor cursor = db.rawQuery(query, null);
        String b = "not found";
        if (cursor.moveToFirst()) {
            do {
                if (cursor.getString(0).equals(username)) {
                    b = cursor.getString(1);
                    break;
                }
            } while (cursor.moveToNext());
        }

        return b;
    }

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

RegisterAccountActivity.java

public class RegisterAccountActivity extends ActionBarActivity {

    EditText fullNameText, usernameText, passwordText, confirmPasswordText, hpnoText;
    MyDBHandler dbHandler = new MyDBHandler(this);
    User user;

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

        // register account button
        final Button registerAccountButton = (Button) findViewById(R.id.registerAccountButton);
        registerAccountButton.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(final View v) {
                        fullNameText = (EditText) findViewById(R.id.fullNameText);
                        usernameText = (EditText) findViewById(R.id.usernameText);
                        passwordText = (EditText) findViewById(R.id.passwordText);
                        confirmPasswordText = (EditText) findViewById(R.id.confirmPasswordText);
                        hpnoText = (EditText) findViewById(R.id.hpnoText);

                        // check empty fields
                        if (TextUtils.isEmpty(fullNameText.getText().toString())) {
                            fullNameText.setError("Please enter your full name.");
                            return;
                        } else if (TextUtils.isEmpty(usernameText.getText().toString())) {
                            usernameText.setError("Please enter username.");
                            return;
                        } else if (TextUtils.isEmpty(passwordText.getText().toString())) {
                            passwordText.setError("Please enter password.");
                            return;
                        } else if (TextUtils.isEmpty(confirmPasswordText.getText().toString())) {
                            confirmPasswordText.setError("Please confirm your password.");
                            return;
                        } else if (TextUtils.isEmpty(hpnoText.getText().toString())) {
                            hpnoText.setError("Please enter your phone number.");
                            return;
                        }

                        // if all fields filled
                        if (!TextUtils.isEmpty(fullNameText.getText().toString()) && !TextUtils.isEmpty(usernameText.getText().toString()) && !TextUtils.isEmpty(passwordText.getText().toString()) && !TextUtils.isEmpty(confirmPasswordText.getText().toString()) && !TextUtils.isEmpty(hpnoText.getText().toString())) {
                            if (passwordText.getText().toString().equals(confirmPasswordText.getText().toString())) {
                                AlertDialog.Builder orderConfirm = new AlertDialog.Builder(RegisterAccountActivity.this);

                                // setting dialog title
                                orderConfirm.setTitle("Confirm Register");

                                // setting dialog message
                                orderConfirm.setMessage("Do you want to continue?");

                                // setting icon to dialog
                                //orderConfirm.setIcon(R.drawable.save);

                                // setting positive "Proceed" button
                                orderConfirm.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // user press Proceed button. Write logic here
                                        registerButtonClicked(v);

                                        AlertDialog.Builder registrationDone = new AlertDialog.Builder(RegisterAccountActivity.this);

                                        // setting dialog title
                                        registrationDone.setTitle("Register Successfully!");

                                        // setting dialog message
                                        registrationDone.setMessage("Your account has been registered successfully.");

                                        // setting icon to dialog
                                        //orderConfirm.setIcon(R.drawable.save);

                                        // setting positive "Okay" button
                                        registrationDone.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                // user press Proceed button. Write logic here
                                                registerButtonClicked(v);
                                                goToLoginActivity();
                                            }
                                        });
                                        registrationDone.show();
                                    }
                                });

                                // setting neutral "Cancel" button
                                orderConfirm.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // user press Cancel button. Write login here
                                        dialog.dismiss();
                                    }
                                });

                                orderConfirm.show();
                            } else {
                                confirmPasswordText.setError("Your password does not match!");
                            }
                        }
                    }
                }
        );
    }

    public void registerButtonClicked(View v) {
        if (v.getId() == R.id.registerAccountButton) {
            fullNameText = (EditText) findViewById(R.id.fullNameText);
            usernameText = (EditText) findViewById(R.id.usernameText);
            passwordText = (EditText) findViewById(R.id.passwordText);
            confirmPasswordText = (EditText) findViewById(R.id.confirmPasswordText);
            hpnoText = (EditText) findViewById(R.id.hpnoText);

            user = new User();
            user.set_fullname(fullNameText.getText().toString());
            user.set_username(usernameText.getText().toString());
            user.set_password(passwordText.getText().toString());
            user.set_hpno(Integer.parseInt(hpnoText.getText().toString()));

            dbHandler.createUser(user);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_register_account, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void goToLoginActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }
}

LoginActivity.java

public class LoginActivity extends ActionBarActivity {

    EditText usernameText, passwordText;
    MyDBHandler dbHandler = new MyDBHandler(this);

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

        // sign in button
        Button signiInButton = (Button) findViewById(R.id.signInButton);
        signiInButton.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {
                        usernameText = (EditText) findViewById(R.id.usernameText);
                        passwordText = (EditText) findViewById(R.id.passwordText);

                        if (TextUtils.isEmpty(usernameText.getText().toString())) {
                            usernameText.setError("Please enter username");
                            return;
                        } else if (TextUtils.isEmpty(passwordText.getText().toString())) {
                            passwordText.setError("Please enter password");
                            return;
                        } else if (TextUtils.isEmpty(usernameText.getText().toString()) && TextUtils.isEmpty(passwordText.getText().toString())) {
                            usernameText.setError("Please enter username");
                            passwordText.setError("Please enter password");
                            return;
                        } else {
                            loginButtonClicked(v);
                        }

                        /*String pass = dbHandler.searchPassword(usernameText.getText().toString());
                        if (passwordText.getText().toString().equals(pass)) {
                            goToAdminMainActivity();
                        } else {
                            AlertDialog.Builder loginError = new AlertDialog.Builder(LoginActivity.this);

                            // setting dialog title
                            loginError.setTitle("Invalid");

                            // setting dialog message
                            loginError.setMessage("Username or Password is not correct.");

                            // setting icon to dialog
                            //orderConfirm.setIcon(R.drawable.save);

                            // setting positive "Okay" button
                            loginError.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // user press Proceed button. Write logic here
                                    passwordText.setText("");
                                    dialog.dismiss();
                                }
                            });
                            loginError.show();
                        }*/
                    }
                }
        );

        // register account link
        TextView registerAccountLink = (TextView) findViewById(R.id.registerAccountLink);
        registerAccountLink.setOnClickListener(
                new TextView.OnClickListener() {
                    public void onClick(View v) {
                        goToRegisterAccountActivity();
                    }
                }
        );
    }

    public void loginButtonClicked(View v) {
        if (v.getId() == R.id.signInButton) {
            //usernameText = (EditText) findViewById(R.id.usernameText);
            //passwordText = (EditText) findViewById(R.id.passwordText);

            String pass = dbHandler.searchPassword(usernameText.getText().toString());
            if (passwordText.getText().toString().equals(pass)) {
                goToAdminMainActivity();
            } else {
                AlertDialog.Builder loginError = new AlertDialog.Builder(LoginActivity.this);

                // setting dialog title
                loginError.setTitle("Invalid");

                // setting dialog message
                loginError.setMessage("Username or Password is not correct.");

                // setting icon to dialog
                //orderConfirm.setIcon(R.drawable.save);

                // setting positive "Okay" button
                loginError.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // user press Proceed button. Write logic here
                        passwordText.setText("");
                        dialog.dismiss();
                    }
                });
                loginError.show();
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void goToAdminMainActivity() {
        Intent intent = new Intent(this, AdminMainActivity.class);
        startActivity(intent);
    }

    public void goToCustomerMainActivity() {
        Intent intent = new Intent(this, CustomerMainActivity.class);
        startActivity(intent);
    }

    public void goToRegisterAccountActivity() {
        Intent intent = new Intent(this, RegisterAccountActivity.class);
        startActivity(intent);
    }

}

I have been trying many others method to do this, but all didn't work.

Aucun commentaire:

Enregistrer un commentaire