public void onSignUpClick(View v){
if(v.getId() == R.id.btnRegister)
{
EditText name = (EditText)findViewById(R.id.TFname);
EditText email = (EditText)findViewById(R.id.TFemail);
EditText pass1 = (EditText)findViewById(R.id.TFpass1);
EditText pass2 = (EditText)findViewById(R.id.TFpass2);
String namestr = name.getText().toString();
String emailstr = name.getText().toString();
String pass1str = name.getText().toString();
String pass2str = name.getText().toString();
if(!pass1str.equals(pass2str))
{
//popup msg:
Toast tpass = Toast.makeText(signup.this, "passwords don't match", Toast.LENGTH_LONG);
tpass.show();
}
else
{
//insert the details in DB:
Contact c = new Contact();
c.setName(namestr);
c.setEmail(emailstr);
c.setPass(pass1str);
helper.insertContact(c);
}
}
}
I'm trying to make a signup form linked to sqlite database. the registraion button that's linked to onSignUpClick method doesn't work. any help to fix this error?
I have implemented a similar functionality to my app.. You can use this as a reference.You need to add whatever elements needed for your signup activity.
1. Create a database handler for your sqlite application.(DatabaseHandler.java)
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context, Object name,
Object factory, int version) {
// TODO Auto-generated constructor stub
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
String password;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Mydatabase.db";
// Contacts table name
private static final String TABLE_REGISTER= "register";
public static final String KEY_EMAIL_ID="email_id";
public static final String KEY_MOB_NO = "mobile_number";
public static final String KEY_PASSWORD = "password";
public static final String CREATE_TABLE="CREATE TABLE " + TABLE_REGISTER + "("
+ KEY_EMAIL_ID+ " TEXT,"
+ KEY_MOB_NO + " TEXT," + KEY_PASSWORD + " TEXT " + ")";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
onCreate(db);
}
void addregister(UserRegister registerdata)
// code to add the new register
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EMAIL_ID, registerdata.getEmailId());//register email id
values.put(KEY_MOB_NO, registerdata.getMobNo());//register mobile no
values.put(KEY_PASSWORD, registerdata.getPassword());
// Inserting Row
db.insert(TABLE_REGISTER, null, values);
db.close(); // Closing database connection
}
//code to get the register
String getregister(String username){
SQLiteDatabase db = this.getReadableDatabase();
//String selectquery="SELECT * FROM TABLE_REGISTER";
Cursor cursor=db.query(TABLE_REGISTER,null, "email_id=?",new String[]{username},null, null, null, null);
if(cursor.getCount()<1){
cursor.close();
return "Not Exist";
}
else if(cursor.getCount()>=1 && cursor.moveToFirst()){
password = cursor.getString(cursor.getColumnIndex(KEY_PASSWORD));
cursor.close();
}
return password;
}
public String getDatabaseName() {
return DATABASE_NAME;
}
public static String getTableContacts() {
return TABLE_REGISTER;
}
public static int getDatabaseVersion() {
return DATABASE_VERSION;
}
}
2. Create a modal class UserRegister
public class UserRegister {
//private variables
String email_id;
String mobile_number;
String password;
// Empty constructor
public UserRegister(){}
// constructor
public UserRegister( String email_id,String mobile_number, String password){
this.email_id=email_id;
this.mobile_number=mobile_number;
this.password = password;
}
public String getEmailId() {
return email_id;
}
public void setEmailId(String email_id){
this.email_id = email_id;
}
public String getMobNo() {
// TODO Auto-generated method stub
return mobile_number;
}
public void setMobNo(String mobile_number){
this.mobile_number=mobile_number;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.Create the RegistrationActivity
public class Registration_Activity extends AppCompatActivity {
EditText reg_email,reg_phone,reg_password;
Button reg_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final DatabaseHandler db = new DatabaseHandler(this, null, null, 2);
reg_email = (EditText)findViewById(R.id.reg_email);
reg_phone = (EditText)findViewById(R.id.reg_phone);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_button = (Button)findViewById(R.id.reg_button);
final String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = reg_email.getText().toString();
String phone = reg_phone.getText().toString();
String password = reg_password.getText().toString();
if (email.matches(emailPattern)) {
DatabaseHandler db = new DatabaseHandler(Registration_Activity.this, null, null, 2);
UserRegister userRegister = new UserRegister();
userRegister.setEmailId(email);
userRegister.setMobNo(phone);
userRegister.setPassword(password);
db.addregister(userRegister);
Toast.makeText(getApplicationContext(), "Account Created", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Registration_Activity.this, Login_Activity.class);
startActivity(intent);
Registration_Activity.this.finish();
}
else
{
Toast.makeText(getApplicationContext(),"Enter a valid Email Address",Toast.LENGTH_SHORT).show();
}
}
});
}
}
4. Login_Activity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login_Activity extends AppCompatActivity {
TextView signup;
String email,password;
EditText log_username,log_password;
Button login_button;
DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signup = (TextView)findViewById(R.id.signup);
String htmlString="<u>Signup</u>";
signup.setText(Html.fromHtml(htmlString));
log_username = (EditText)findViewById(R.id.log_username);
log_password = (EditText)findViewById(R.id.log_password);
login_button = (Button)findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db=new DatabaseHandler(Login_Activity.this, null, null, 2);
email = log_username.getText().toString();
password = log_password.getText().toString();
String StoredPassword =db.getregister(email);
if(password.equals(StoredPassword)){
Toast.makeText(getApplicationContext(),"Login Successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Login_Activity.this,VideoActivity.class);
startActivity(intent);
Login_Activity.this.finish();
}
else{
Toast.makeText(getApplicationContext(), "Username/Password incorrect", Toast.LENGTH_LONG).show();
log_username.setText("");
log_password.setText("");
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login_Activity.this,Registration_Activity.class);
startActivity(intent);
Login_Activity.this.finish();
}
});
}
}
Related
I'm creating an app for doctor's appointment.. So I want to see the booked appointments records in the listview for different activities with a delete button to delete a specific record..
this is my code for making appointments...
that is Appo.java
package com.example.medilyf;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class Appo extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet, confirm, seeappo;
TextView tvw, text, receiver_msg;
DBHelper myDB;
CheckBox android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appo);
tvw = findViewById(R.id.textView1);
eText = findViewById(R.id.editText1);
myDB = new DBHelper(Appo.this);
android = findViewById(R.id.checkBox);
angular = findViewById(R.id.checkBox1);
java = findViewById(R.id.checkBox2);
python = findViewById(R.id.checkBox3);
text = findViewById(R.id.txt);
Button btn = findViewById(R.id.getbtn);
receiver_msg =findViewById(R.id.textView5);
// create the get Intent object
Intent intent = getIntent();
String str = intent.getStringExtra("dr_name");
// display the string into textView
receiver_msg.setText(str);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(Appo.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet = findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt = eText.getText().toString();
tvw.setText(txt);
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result ="";
if (android.isChecked()) {
result += "\n9:00 - 10:30";
}
if (angular.isChecked()) {
result += "\n10:30 -11:30";
}
if (java.isChecked()) {
result += "\n11:30 -12:30";
}
if (python.isChecked()) {
result += "\n2:00 - 3:00";
}
text.setText(result);
}
});
confirm = findViewById(R.id.confirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String time = text.getText().toString();
String date = tvw.getText().toString();
if (str.equals("")) {
Toast.makeText(Appo.this, "Blank values", Toast.LENGTH_SHORT).show();
} else {
boolean booking = myDB.insertData2(str, time, date);
if (booking) {
Toast.makeText(Appo.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Appo.this, "Booking not confirmed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox:
str = checked?"9:00 - 10:30 Selected":"9:00 - 10:30 Deselected";
break;
case R.id.checkBox1:
str = checked?"10:30 -11:30 Selected":"10:30 -11:30 Deselected";
break;
case R.id.checkBox2:
str = checked?"11:30 -12:30 Selected":"11:30 -12:30 Deselected";
break;
case R.id.checkBox3:
str = checked?"2:00 - 3:00 Selected":"2:00 - 3:00 Deselected";
break;
}
Toast.makeText(Appo.this, str, Toast.LENGTH_SHORT).show();
}
}
This is the code for sqlite database... that is DBHelper.java
package com.example.medilyf;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class DBHelper extends SQLiteOpenHelper {
public static final String col1="name";
public static final String col2="username";
public static final String col3="email";
public static final String col4="PhoneNo";
public static final String col5="password";
public static final String NAME = "name";
public static final String PHONE = "phone";
public static final String col6="Appointment_id ";
public static final String col7="full_Name ";
public static final String col9="Doc_name ";
public static final String col12="ATime ";
public static final String col8="Phone_Number";
public DBHelper(#Nullable Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(name Text, username Text primary key, email Text, PhoneNo Text, password Text)");
myDB.execSQL("create table appo(Dr Text,time Text, date Text)");
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int oldVersion, int newVersion) {
myDB.execSQL("Drop Table if exists users");
myDB.execSQL("Drop Table if exists appo");
}
public boolean insertData(String name, String username, String email, String PhoneNo, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col1,name);
contentValues.put(col2,username);
contentValues.put(col3,email);
contentValues.put(col4,PhoneNo);
contentValues.put(col5,password);
long result = myDB.insert("users",null,contentValues);
return result != -1;
}
public boolean insertData2(String Dr, String time, String date){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Dr",Dr);
contentValues.put("time",time);
contentValues.put("date",date);
long result = myDB.insert("appo",null,contentValues);
return result != -1;
}
public boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?", new String[] {username});
return cursor.getCount() > 0;
}
public boolean checkusernamepassword(String username, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?", new String[] {username,password});
return cursor.getCount() > 0;
}
}
Can anyone help me with the code to retrieve and display the records of the appointment for another activity in list view..???
My Parent_home Activity needs data (name, surname, id) from the logged in user, my login activity can only check if the database has the parent(user) credential, and I want after checking if have parent in login activity, parent data from the database gonna given to the Parent_home Activity
DatabaseHelper.java
package edu.angelo.parentsportal;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Parents_Portal.db";
public static final String TABLE_NAME = "Parents_Table";
public static final String COL_0 = "ID";
public static final String COL_1 = "NAME";
public static final String COL_2 = "SURNAME";
public static final String COL_3 = "EMAIL_ADDRESS";
public static final String COL_4 = "PHONE_NUMBER";
public static final String COL_5 = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, EMAIL_ADDRESS TEXT, PHONE_NUMBER TEXT, PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String surname, String email_address, String phone_number, String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,surname);
contentValues.put(COL_3,email_address);
contentValues.put(COL_4,phone_number);
contentValues.put(COL_5,password);
long result = db.insert(TABLE_NAME, null , contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public ArrayList<ParentModel> getAllParentsData(){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
public void updateData(int id, String name , String surname , String email , String phone_number , String password){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.update(TABLE_NAME, contentValues, COL_0 + "=" + id, null);
mydb.close();
}
public void deleteParent(int id){
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.delete(TABLE_NAME, COL_0 + "=" + id, null);
mydb.close();
}
public ArrayList<ParentModel> getParentLoginData(String emailOrPhone,String pwd){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "SELECT * FROM " + TABLE_NAME+" WHERE ("+COL_3+"= "+emailOrPhone+" OR "+COL_4 +" = "+emailOrPhone+") AND "+COL_5 +" = "+pwd;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
}
Login.java
package edu.angelo.parentsportal;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText editTextEmailPhone;
private EditText editTextPassword;
private Button Login;
private ProgressDialog progressDialog;
DatabaseHelper mydb;
SQLiteDatabase sqLiteDatabase;
CustomAdapter customAdapter;
Cursor cursor;
ArrayList<ParentModel> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextEmailPhone = findViewById(R.id.input_username);
editTextPassword = findViewById(R.id.input_password);
findViewById(R.id.btn_register).setOnClickListener(Login.this);
progressDialog = new ProgressDialog(this);
mydb =new DatabaseHelper(this);
sqLiteDatabase = mydb.getReadableDatabase();
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_register: {
userLogin();
break;
}
}
}
private void userLogin() {
String email = editTextEmailPhone.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmailPhone.setError("Email or Phone Number is required");
editTextEmailPhone.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length()<6 ){
editTextPassword.setError("Minimum of length of password should be 6");
editTextPassword.requestFocus();
return;
}
//if the email&pass is not empty
//display dialog
else{
progressDialog.setMessage("Please Wait...");
progressDialog.show();
if (mydb.getParentLoginData(editTextEmailPhone.getText().toString(),editTextPassword.getText().toString()).size()>0) {
progressDialog.dismiss();
DatabaseHelper mydb = new DatabaseHelper(this);
SharedPrefs.saveSharedSetting(this, "CaptainCode", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
// intent or something to forward the data from the selected parent row from the database
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
else {
Toast.makeText(getApplicationContext(), "Login error", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
return;
}
}
}
}
ParentModel.java (if needed)
package edu.angelo.parentsportal;
public class ParentModel {
public String ID;
public String Name;
public String Surname;
public String Email;
public String Phone_number;
public String Password;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone_number() {
return Phone_number;
}
public void setPhone_number(String phone_number) {
Phone_number = phone_number;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
}
You can pass the values to the activity using Intent Extras when starting an activity via an Intent.
So you use something like :-
ArrayList<ParentModel> parents = mydb.getParentLoginData(editTextEmailPhone.getText().toString(),editTextPassword.getText().toString());
if (parents.size()>0) {
progressDialog.dismiss();
DatabaseHelper mydb = new DatabaseHelper(this);
SharedPrefs.saveSharedSetting(this, "CaptainCode", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
intent.putExtra("IK_CURRENTPARENTID",parents[0].getId());
intent.putExtra("IK_CURRENTPARENTNAME",parents[0].getName());
intent.putExtra("IK_CURRENTPARENTSURNAME",parents[0].getSurname();
// intent or something to forward the data from the selected parent row from the database
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
You then retrieve the values from the Intent Extras in the Parent_Home activity. using something like in the onCreate method :-
currentId = getIntent().getStringExtra("IK_CURRENTPARENTID");
currentName = getIntent().getStringExtra("IK_CURRENTPARENTNAME");
currentSurName = getIntent().getStringExtra("IK_CURRENTPARENTSURNAME");
noting that the above assumes that currentId, currentName and currentSurName have been declared as class variables.
typically you'd also define constants for the Intent Extra keys rater than hard coding them.
The above is in-principle code, it hasn't been run or tested and may therefore contain some errors.
If you can check the code and fix the errors in this code
Home.java
package com.;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Home extends AppCompatActivity {
EditText username_editText;
EditText password_editText;
Button loginbtn;
Button registerbtn;
public static final String USERID = "userID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
username_editText = (EditText)findViewById(R.id.home_userName);
password_editText = (EditText)findViewById(R.id.home_password);
loginbtn = (Button)findViewById(R.id.home_loginBtn);
registerbtn = (Button)findViewById(R.id.home_registerBtn);
final DBHandler dbHandler = new DBHandler(Home.this);
registerbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent("com.modelpaper.mad.it17121002.ProfileManagement");
startActivity(intent);
}
});
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userName = username_editText.getText().toString();
String password = password_editText.getText().toString();
if(userName.equals("") || password.equals("")){
Toast.makeText(Home.this,"Login Unsuccessful",Toast.LENGTH_SHORT).show();
}
else{
UserProfile.Users users = dbHandler.readAllInfor(userName);
if(users == null){
Toast.makeText(Home.this,"Invalid username or password",Toast.LENGTH_SHORT).show();
}
else{
int userID = users.getId();
Intent editProfIntent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
editProfIntent.putExtra(USERID,Integer.toString(userID));
startActivity(editProfIntent);
}
}
}
});
}
I think there is error in db class I can't find this error.app is crashed db not created . please try to understand it
DBHandler.java
package com.;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class DBHandler extends SQLiteOpenHelper {
public DBHandler(Context context) {
super(context, "user_db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE "+UserProfile.Users.TABLE_NAME +"( "+UserProfile.Users.COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT ,"+UserProfile.Users.COL_USERNAME+" TEXT UNIQUE," +
UserProfile.Users.COL_PASSWORD +" TEXT, "+UserProfile.Users.COL_GENDER +" TEXT, "+UserProfile.Users.COL_DOB +" TEXT"+")";
Log.d("createQuery",createQuery);
try {
db.execSQL(createQuery);
}
catch (Exception e){
e.printStackTrace();
Log.e("Exception",e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String createQuery = "CREATE TABLE "+UserProfile.Users.TABLE_NAME +"( "+UserProfile.Users.COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT ,"+UserProfile.Users.COL_USERNAME+" TEXT," +
UserProfile.Users.COL_PASSWORD +" TEXT, "+UserProfile.Users.COL_GENDER +" TEXT, "+UserProfile.Users.COL_DOB+" TEXT"+")";
Log.d("createQuery",createQuery);
try {
db.execSQL(createQuery);
}
catch (Exception e){
e.printStackTrace();
Log.e("Exception",e.getMessage());
}
}
public boolean addInfo(UserProfile.Users users){
SQLiteDatabase db = this.getWritableDatabase();
String insertQuery = "INSERT INTO "+UserProfile.Users.TABLE_NAME+"("+UserProfile.Users.COL_USERNAME+","+UserProfile.Users.COL_PASSWORD+","+UserProfile.Users.COL_GENDER+","+
UserProfile.Users.COL_DOB+") VALUES('"+users.getUsername()+"','"+users.getPassword()+"','"+users.getGender()+"','"+users.getDob()+"')";
Log.d("insertQuery",insertQuery);
try {
db.execSQL(insertQuery);
return true;
}
catch (Exception e){
e.printStackTrace();
Log.d("Exception",e.getMessage());
}
db.close();
return false;
}
public boolean updateInfor(UserProfile.Users users){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String username = users.getUsername();
String password = users.getPassword();
String dob = users.getDob();
String gender = users.getGender();
int id = users.getId();
values.put(UserProfile.Users.COL_DOB,dob);
values.put(UserProfile.Users.COL_GENDER,gender);
values.put(UserProfile.Users.COL_PASSWORD,password);
values.put(UserProfile.Users.COL_USERNAME,username);
int result = db.update(UserProfile.Users.TABLE_NAME,values,UserProfile.Users.COL_ID+" = ?",new String[]{String.valueOf(id)});
if(result >0)
return true;
return false;
}
public ArrayList<UserProfile.Users> readAllInfor(){
ArrayList<UserProfile.Users> userList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String readAllQuery = "SELECT * FROM "+UserProfile.Users.TABLE_NAME;
Cursor cursor = db.rawQuery(readAllQuery,null);
if(cursor.moveToFirst()){
do{
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setId(Integer.parseInt(cursor.getString(0)));
users.setUsername(cursor.getString(1));
users.setPassword(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setDob(cursor.getString(4));
userList.add(users);
} while (cursor.moveToNext());
}
return userList;
}
public UserProfile.Users readAllInfor(String userName){
SQLiteDatabase db = this.getWritableDatabase();
String readSingleQuery = "SELECT * FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_USERNAME + " = '"+ userName+"'";
Cursor cursor = db.rawQuery(readSingleQuery,null);
if(cursor.moveToFirst()){
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setId(Integer.parseInt(cursor.getString(0)));
users.setUsername(cursor.getString(1));
users.setPassword(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setDob(cursor.getString(4));
return users;
}
return null;
}
public UserProfile.Users readAllInfor(int id){
SQLiteDatabase db = this.getWritableDatabase();
String readSingleQuery = "SELECT * FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_ID + " = '"+ id+"'";
Cursor cursor = db.rawQuery(readSingleQuery,null);
if(cursor.moveToFirst()){
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setId(Integer.parseInt(cursor.getString(0)));
users.setUsername(cursor.getString(1));
users.setPassword(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setDob(cursor.getString(4));
return users;
}
return null;
}
public void deleteInfo(String username){
SQLiteDatabase db = this.getWritableDatabase();
String deleteQuery = "DELETE FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_USERNAME +" = '"+ username +"' ";
Log.d("deleteQuery ",deleteQuery);
db.execSQL(deleteQuery);
db.close();
}
}
I checked this one and couldn't find the solution for solve it. This is user profile class to handle user profiles.
UserProfile.java
package com.modelpaper.mad.it17121002;
public final class UserProfile {
private UserProfile(){
}
public static UserProfile getProfile(){
UserProfile userProfile = new UserProfile();
return userProfile;
}
class Users implements BaseColumn{
public static final String TABLE_NAME = "UserInfo";
public static final String COL_ID = "_ID";
public static final String COL_USERNAME = "userName ";
public static final String COL_DOB = "dateOfBirth";
public static final String COL_GENDER = "Gender";
public static final String COL_PASSWORD = "Password";
//displya karana ona variable tika
private int id;
private String username;
private String dob;
private String gender;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
//hethuwa-wena thanaka class ekaka wena wenama varible cll krnnaq ona unoth
public Users getUser(){
Users users = new Users();
return users;
}
}
This is edit profile class i have doubt of this class.
EditProfile.java
package com.;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class EditProfile extends AppCompatActivity {
Button searchBtn;
EditText userName_editText;
EditText password_editText;
EditText dob_editText;
RadioGroup genderRadioGroup;
RadioButton genderRadioBtn;
//new Edit
RadioButton genderRadioBtnMale;
RadioButton genderRadioBtnFemale;
Button editBtn;
Button deleteBtn;
Intent intent;
DBHandler dbHandler;
public static final String USERID_EDITPROFILE = "userID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
searchBtn = (Button)findViewById(R.id.editprof_searchbtn);
userName_editText = (EditText)findViewById(R.id.editprof_userName);
password_editText = (EditText)findViewById(R.id.editprof_password);
dob_editText = (EditText)findViewById(R.id.editprof_dob);
genderRadioGroup = (RadioGroup)findViewById(R.id.editprof_radiogroup);
editBtn = (Button)findViewById(R.id.editprof_editbtn);
deleteBtn = (Button)findViewById(R.id.editprof_deletebtn);
//new edit
genderRadioBtnMale = (RadioButton) findViewById(R.id.editprof_male_radio);
genderRadioBtnFemale = (RadioButton) findViewById(R.id.editprof_female_radio);
intent = getIntent();
dbHandler = new DBHandler(EditProfile.this);
setUserDetails();
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = userName_editText.getText().toString();
if(username == null){
Toast.makeText(EditProfile.this,"Please enter username to delete your profile",Toast.LENGTH_SHORT).show();
}
else{
UserProfile.Users users = dbHandler.readAllInfor(username);
if(users == null){
Toast.makeText(EditProfile.this,"No profile found from this username, please enter valid username",Toast.LENGTH_SHORT).show();
}
else{
dbHandler.deleteInfo(username);
Intent redirectintent_home = new Intent(EditProfile.this,Home.class);
startActivity(redirectintent_home);
}
}
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userID_String = intent.getStringExtra(Home.USERID);
if(userID_String == null){
Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
Intent redirectintent_home = new Intent(getApplicationContext(),Home.class);
startActivity(redirectintent_home);
}
int userID = Integer.parseInt(userID_String);
String username = userName_editText.getText().toString();
String password = password_editText.getText().toString();
String dob = dob_editText.getText().toString();
int selectedGender = genderRadioGroup.getCheckedRadioButtonId();
genderRadioBtn = (RadioButton)findViewById(selectedGender);
String gender = genderRadioBtn.getText().toString();
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setUsername(username);
users.setPassword(password);
users.setDob(dob);
users.setGender(gender);
users.setId(userID);
dbHandler.updateInfor(users);
Toast.makeText(EditProfile.this,"Updated Successfully",Toast.LENGTH_SHORT).show();
Intent redirectintent_home = new Intent(getApplicationContext(),Home.class);
startActivity(redirectintent_home);
}
});
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = userName_editText.getText().toString();
if (username == null){
Toast.makeText(EditProfile.this,"Please enter a username",Toast.LENGTH_SHORT).show();
}
else{
UserProfile.Users users_search = dbHandler.readAllInfor(username);
if(users_search == null){
Toast.makeText(EditProfile.this,"Please enter a valid username",Toast.LENGTH_SHORT).show();
}
else{
userName_editText.setText(users_search.getUsername());
password_editText.setText(users_search.getPassword());
dob_editText.setText(users_search.getDob());
int id = users_search.getId();
Intent redirectintent = new Intent(EditProfile.this,EditProfile.class);
redirectintent.putExtra(USERID_EDITPROFILE,Integer.toString(id));
startActivity(redirectintent);
}
}
}
});
}
public void setUserDetails(){
String userID_String = intent.getStringExtra(Home.USERID);
if(userID_String == null){
Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
startActivity(redirectintent_home);
}
int userID = Integer.parseInt(userID_String);
UserProfile.Users users = dbHandler.readAllInfor(userID);
userName_editText.setText(users.getUsername());
password_editText.setText(users.getPassword());
dob_editText.setText(users.getDob());
//new edit
String gender = users.getGender();
if(gender.equals("Male")){
genderRadioBtnMale.setChecked(true);
genderRadioBtnFemale.setChecked(false);
}
else{
genderRadioBtnMale.setChecked(false);
genderRadioBtnFemale.setChecked(true);
}
}
}
if you can try to check this also
ProfileManagement.java
package com.;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class ProfileManagement extends AppCompatActivity {
EditText username_editText;
EditText password_editText;
EditText dob_editText;
RadioGroup radioGroup;
RadioButton gender_radioBtn;
Button saveProfBtn;
public final static String USERID_PROFILEMGMT = "userID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
username_editText = (EditText)findViewById(R.id.profmgmt_userName);
password_editText = (EditText)findViewById(R.id.profmgmt_password);
dob_editText = (EditText)findViewById(R.id.profmgmt_dob);
radioGroup = (RadioGroup)findViewById(R.id.profmgmt_radiogroup);
saveProfBtn = (Button)findViewById(R.id.profmgmt_btn);
final DBHandler dbHandler = new DBHandler(ProfileManagement.this);
saveProfBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = username_editText.getText().toString();
String password = password_editText.getText().toString();
String dob = dob_editText.getText().toString();
int selectedGender = radioGroup.getCheckedRadioButtonId();
gender_radioBtn = (RadioButton)findViewById(selectedGender);
String gender = gender_radioBtn.getText().toString();
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setUsername(username);
users.setPassword(password);
users.setDob(dob);
users.setGender(gender);
boolean result = dbHandler.addInfo(users);
if(result == true){
Toast.makeText(ProfileManagement.this,"Successfully added",Toast.LENGTH_SHORT).show();
UserProfile.Users newusers = dbHandler.readAllInfor(username);
int userID = newusers.getId();
Intent intent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
intent.putExtra(USERID_PROFILEMGMT,Integer.toString(userID));
startActivity(intent);
}
}
});
}
}
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "student.db";
public static final String TABLE_NAME = "student_table";
public static final String COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "SURNAME"
;
public static final String COL4 = "MARKS";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
// SQLiteDatabase db = this.getWritableDatabase(); }
public void onCreate(SQLiteDatabase db) {
db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String surname, String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, name);
contentValues.put(COL3, surname);
contentValues.put(COL4, marks);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAlldata() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
}
public boolean updateData(String id, String name, String surname, String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, id);
contentValues.put(COL2, name);
contentValues.put(COL3, surname);
contentValues.put(COL4, marks);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] {
id
});
return true;
}
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ? ", new String[] {
id
});
}
public class MainActivity extends AppCompatActivity {
public Button but1;
DatabaseHelper myDb;
EditText editName, editSurname, editMarks, editTextid;
Button btnAddData;
Button btnViewall;
public void init() {
but1 = (Button) findViewById(R.id.button5);
but1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent my = new Intent(MainActivity.this, Activity2.class);
startActivity(my);
}
});
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myDb = new DatabaseHelper(this);
editName = (EditText) findViewById(R.id.editText_name);
editSurname = (EditText) findViewById((R.id.editText_surname));
editMarks = (EditText) findViewById((R.id.editText_marks));
editTextid = (EditText) findViewById(R.id.editText_id);
btnAddData = (Button) findViewById((R.id.button_add));
btnViewall = (Button) findViewById(R.id.button_view);
Adddata();
viewAll();
update();
}
public void Adddata() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editName.getText().toString(), editSurname.getText().toString(), editMarks.getText().toString());
if (isInserted == true)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data Not Inserted", Toast.LENGTH_LONG).show();
}
});
}
public void update() {
btnUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isUpdate = myDb.updateData(editTextid.getText().toString(), editName.getText().toString(), editSurname.getText().toString(), editMarks.getText().toString());
if (isUpdate == true)
Toast.makeText(MainActivity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Not Updated", Toast.LENGTH_LONG).show();
}
}
public void Delete() {
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deleteRows = myDb.deleteData(editTextid.getText().toString());
if (deleteRows > 0)
Toast.makeText(MainActivity.this, "Data Updated", Toast.LENGTH_LONG).show();
}
});
}
public void viewAll() {
btnViewall.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAlldata();
if (res.getCount() == 0) {
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("id :" + res.getString(0) + "\n");
buffer.append("name :" + res.getString(1) + "\n");
buffer.append("surname: " + res.getString(2) + "\n");
buffer.append("marks: " + res.getString(3) + "\n\n");
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "student.db";
public static final String TABLE_NAME ="student_table";
public static final String COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "SURNAME"
; public static final String COL4 = "MARKS";
public DatabaseHelper( Context context) {
super(context, DATABASE_NAME , null, 1);
// SQLiteDatabase db = this.getWritableDatabase(); }
public void onCreate(SQLiteDatabase db) {
db.execSQL( " create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS INTEGER)" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME );
onCreate(db);
}
public boolean insertData(String name, String surname, String marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2,name);
contentValues.put(COL3,surname);
contentValues.put(COL4,marks);
long result= db.insert(TABLE_NAME, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAlldata(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null );
return res; }
}
public boolean updateData(String id, String name, String surname, String marks){ SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1,id);
contentValues.put(COL2,name);
contentValues.put(COL3,surname);
contentValues.put(COL4,marks);
db.update(TABLE_NAME , contentValues, "ID = ?",new String[]{ id }); return true; } }
public Integer deleteData(String id){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME , "ID = ? ", new String[]{id}); }
public class MainActivity extends AppCompatActivity {
public Button but1;
DatabaseHelper myDb;
EditText editName, editSurname, editMarks,editTextid;
Button btnAddData;
Button btnViewall;
public void init(){
but1 = (Button)findViewById(R.id.button5);
but1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) { Intent my = new Intent(MainActivity.this,Activity2.class); startActivity(my); } } );
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editSurname = (EditText)findViewById((R.id.editText_surname));
editMarks = (EditText)findViewById((R.id.editText_marks));
editTextid = (EditText)findViewById(R.id.editText_id);
btnAddData= (Button)findViewById((R.id.button_add));
btnViewall=(Button)findViewById(R.id.button_view);
Adddata();
viewAll();
update();
}
public void Adddata(){
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData( editName.getText().toString(), editSurname.getText().toString(), editMarks.getText().toString() );
if(isInserted == true)
Toast.makeText(MainActivity.this ,"Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data Not Inserted", Toast.LENGTH_LONG).show(); } } ); }
public void update(){
btnUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isUpdate = myDb.updateData(editTextid.getText().toString(), editName.getText().toString(), editSurname.getText().toString(), editMarks.getText().toString() );
if(isUpdate == true)
Toast.makeText(MainActivity.this , "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Not Updated" , Toast.LENGTH_LONG).show(); } }
public void Delete(){
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deleteRows = myDb.deleteData(editTextid.getText().toString());
if(deleteRows > 0)
Toast.makeText(MainActivity.this , "Data Updated", Toast.LENGTH_LONG).show(); } } ); }
public void viewAll(){
btnViewall.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res= myDb.getAlldata();
if(res.getCount() == 0){
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){
buffer.append("id :" + res.getString(0)+ "\n");
buffer.append("name :" + res.getString(1)+ "\n");
buffer.append("surname: " + res.getString(2) +"\n");
buffer.append("marks: " + res.getString(3) + "\n\n");
public final class UserProfile {
private UserProfile(){
}
public static UserProfile getProfile(){
UserProfile userProfile = new UserProfile();
return userProfile;
}
class Users implements BaseColumn{
public static final String TABLE_NAME = "UserInfo";
public static final String COL_ID = "_ID";
public static final String COL_USERNAME = "userName ";
public static final String COL_DOB = "dateOfBirth";
public static final String COL_GENDER = "Gender";
public static final String COL_PASSWORD = "Password";
private int id;
private String username;
private String dob;
private String gender;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public Users getUser(){
Users users = new Users();
return users;
}
}
seems this codeline works properly and there anrent any issues please implement it and check it..
well done
I have a Android application written in Java which utilises an SQLite database.
I want the passwords upon input on the sign up page to generate an MD5 or SHA1 hash which is stored in the database. Which can then be used when logging back into the application.
Can anyone offer any help?
Signup
package com.example.oliver.beckettreg;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class SignUp extends Activity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
}
//if button clicked
public void onSignUpClick(View v) {
if (v.getId() == R.id.Bsignupbutton) {
EditText name = (EditText) findViewById(R.id.TFname);
EditText email = (EditText) findViewById(R.id.TFemail);
EditText uname = (EditText) findViewById(R.id.TFuname);
EditText pass1 = (EditText) findViewById(R.id.TFpass1);
EditText pass2 = (EditText) findViewById(R.id.TFpass2);
String namestr = name.getText().toString();
String emailstr = email.getText().toString();
String unamestr = uname.getText().toString();
String pass1str = pass1.getText().toString();
String pass2str = pass2.getText().toString();
//check passwords match
if(!pass1str.equals(pass2str))
{
//popup msg if fails
Toast pass = Toast.makeText(SignUp.this , "Passwords don't match!" , Toast.LENGTH_SHORT);
pass.show();
}
else
{
//validations for data input
if (name.getText().toString().length() == 0)
{name.setError("Name Required");}
else if (!email.getText().toString().matches("[a-z]{1}\\.[a-z]*[0-9]{4}#student\\.leedsbeckett\\.ac\\.uk"))
{email.setError("Incorrect Email Format");}
else if (!uname.getText().toString().matches("[cC][0-9]{7}"))
{uname.setError("Incorrect ID Format");}
else if (!pass1.getText().toString().matches("(?=.*[\\d])(?=.*[a-z])(?=.*[A-Z]).{8,}"))
{pass1.setError("Incorrect Password Format");}
else{
//insert the details in database
Contact c = new Contact();
c.setName(namestr);
c.setEmail(emailstr);
c.setUname(unamestr);
c.setPass(pass1str);
helper.insertContact(c);
//popup if data passes validations
Toast pass = Toast.makeText(SignUp.this , "User Registered" , Toast.LENGTH_LONG);
pass.show();
}
}
}
}
public void onButtonClick(View v) {
if (v.getId() == R.id.Blogin2) {
Intent i = new Intent(SignUp.this, com.example.oliver.beckettreg.MainActivity.class);
startActivity(i);
}
}
}
Login
package com.example.oliver.beckettreg;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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_main, menu);
return true;
}
public void onButtonClick(View v)
{
//if button clicked
if(v.getId() == R.id.Blogin)
{
//check if passwords match
EditText a = (EditText)findViewById(R.id.TFusername);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.TFpassword);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if(pass.equals(password))
{
Intent i = new Intent(MainActivity.this, NFC.class);
i.putExtra("Username",str);
startActivity(i);
}
else
{å
Toast temp = Toast.makeText(MainActivity.this , "Username and password don't match!" , Toast.LENGTH_SHORT);
temp.show();
}
}
//sign up button if data passes
if(v.getId() == R.id.Bsignup)
{
Intent i = new Intent(MainActivity.this, com.example.oliver.beckettreg.SignUp.class);
startActivity(i);
}
if(v.getId() == R.id.Bnfc)
{
Intent i = new Intent(MainActivity.this, com.example.oliver.beckettreg.AttendanceRegistration.class);
startActivity(i);
}
}
#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);
}
}
Database Helper
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
public class
DatabaseHelper extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "contacts.db";
//Table Names
private static final String REGISTER_TABLE_NAME = "register";
private static final String CONTACTS_TABLE_NAME = "contacts";
//Contacts Column Names
private static final String CONTACTS_COLUMN_ID = "id";
private static final String CONTACTS_COLUMN_NAME = "name";
private static final String CONTACTS_COLUMN_EMAIL = "email";
private static final String CONTACTS_COLUMN_UNAME = "uname";
private static final String CONTACTS_COLUMN_PASS = "pass";
//Register Column Names
private static final String REGISTER_COLUMN_ID = "id";
private static final String REGISTER_COLUMN_SEMINAR = "seminar";
private static final String REGISTER_COLUMN_LECTURE = "lecture";
SQLiteDatabase db;
//Table Create Statements
private static final String CONTACTS_TABLE_CREATE = "create table contacts (id integer primary key not null , " +
"name text not null , email text not null , uname text not null , pass text not null);";
private static final String REGISTER_TABLE_CREATE = "create table register (id integer primary key not null , " +
" time DATETIME DEFAULT CURRENT_TIMESTAMP, seminar text not null , lecture text not null, );";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Creating Required Tables
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(REGISTER_TABLE_CREATE);
db.execSQL(CONTACTS_TABLE_CREATE);
this.db = db;
}
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(CONTACTS_COLUMN_ID, count);
values.put(CONTACTS_COLUMN_NAME, c.getName());
values.put(CONTACTS_COLUMN_EMAIL, c.getEmail());
values.put(CONTACTS_COLUMN_UNAME, c.getUname());
values.put(CONTACTS_COLUMN_PASS, c.getPass());
db.insert(CONTACTS_TABLE_NAME, null, values);
db.close();
}
public void insertRegister(Register r) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from register";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(REGISTER_COLUMN_ID, count);
values.put(REGISTER_COLUMN_SEMINAR, r.getSeminar());
values.put(REGISTER_COLUMN_LECTURE, r.getLecture());
db.insert(REGISTER_TABLE_NAME, null, values);
db.close();
}
public String searchPass(String uname)
{
db = this.getReadableDatabase();
String query = "select uname, pass from "+CONTACTS_TABLE_NAME;
Cursor cursor = db.rawQuery(query , null);
String a, b;
b = "not found";
if(cursor.moveToFirst())
{
do{
a = cursor.getString(0);
if(a.equals(uname))
{
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
//On Upgrade Drop Older Tables
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + REGISTER_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + CONTACTS_TABLE_NAME);
//Create New Tables
this.onCreate(db);
}
}
You can implement this method, which will return the hash as a string.
private String hashMe(String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1"); //could also be MD5, SHA-256 etc.
md.reset();
md.update(password.getBytes("UTF-8"));
byte[] resultByte = md.digest();
password = String.format("%01x", new java.math.BigInteger(1, resultByte));
} catch (NoSuchAlgorithmException e) {
//do something.
} catch (UnsupportedEncodingException ex) {
//do something
}
return password;
}
Since you are dealing with passwords, you should also salt the hash, and save them both in your Db.
I`m trying to make sure that the username value stored in my database is not repeating, and if it is repeated, a toast will inform the user that the username is already taken, how can I do so?
My DBAdapter:
package com.nyp.reddot5;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class LoginDataBaseAdapter
{
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
// PartyItems table name
private static final String TABLE_NAME = "login";
// PartyItems Table Columns names
private static final String ID = "id";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String EMAIL = "email";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password, String email)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("EMAIL", email);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
My SignUPActivity
package com.nyp.reddot5;
import com.nyp.reddot5.R;
import com.nyp.reddot5.R.id;
import com.nyp.reddot5.R.layout;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editTextEmail;
Button btnCreateAccount, tcbutton, backb;
CheckBox TCcb;
Context mcursor;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
tcbutton=(Button)findViewById(R.id.tcbutton);
backb=(Button)findViewById(R.id.backb);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
editTextEmail=(EditText)findViewById(R.id.editTextEmail);
TCcb=(CheckBox)findViewById(R.id.TCcb);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
String email=editTextEmail.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
if(editTextUserName.getText().toString().length() < 7){
editTextUserName.setError(getString(R.string.error_field_required_user));
}
if(editTextPassword.getText().toString().length() < 5){
editTextPassword.setError(getString(R.string.error_field_required_pw));
}
if(TCcb.isChecked() == false){
Toast.makeText(getApplicationContext(), "You must agree to the terms and conditions!", Toast.LENGTH_LONG).show();
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password, email);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
}
});
tcbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intent=new Intent(getApplicationContext(),TCActivity.class);
startActivity(intent);
}
});
backb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
You should use the UNIQUE constraint to the user name field in you DB. That way you make sure all values in the collumn are different (you can achieve the same thing making it PK but maybe your ussing another primary key). As for the toast, Im not sure which exception is thrown when the unique constraint is broken, but you should catch that exception, infomr the UI tier and throw the toast.
It throws a SQLiteConstraintException:
try{
db.insertOrThrow("LOGIN", null, newValues); // the normal insert may not throw an error
}catch(SQLiteConstraintException e){
Toast.makeText(context(), "User already on database", Toast.LENGTH_SHORT).show();
}