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.
Related
I am a newbie to Android programming.I want to use data inputted into an SQLite database to populate an Android Listview. However, Android keeps highlighting the SimpleCursorAdapter below as error. Can anyone help?
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
Below is the full code:
package com.allmycode.databaseinsertwithlistview;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText GetName,GetPhoneNumber,GetSubject ;
Button Submit ;
String Name, PhoneNumber, Subject ;
Boolean CheckEditTextEmpty ;
String SQLiteQuery;
SQLiteDatabase SQLITEDATABASE;
TextView display;
Cursor cursor;
ListView listView;
//Make these declarations to enable the fetchallitems() method work
public static final String name = "name";
public static final String phone_number = "Phone_number";
public static final String subject = "subject";
private SimpleCursorAdapter dataAdapter;
private static final String demoTable = "demoTable";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);GetName = (EditText)findViewById(R.id.editText1);
GetPhoneNumber = (EditText)findViewById(R.id.editText2);
GetSubject = (EditText)findViewById(R.id.editText3);
listView = (ListView) findViewById(R.id.ListVw);
//display= (TextView) findViewById(R.id.textView) ;
Submit = (Button)findViewById(R.id.button1);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DBCreate();
SubmitData2SQLiteDB();
displayListView();
}
});
}
public void DBCreate(){
SQLITEDATABASE = openOrCreateDatabase("DemoDataBase", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS demoTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name String, phone_number String, subject String);");
}
public void SubmitData2SQLiteDB(){
Name = GetName.getText().toString();
PhoneNumber = GetPhoneNumber.getText().toString();
Subject = GetSubject.getText().toString();
CheckEditTextIsEmptyOrNot( Name,PhoneNumber, Subject);
if(CheckEditTextEmpty == true)
{
SQLiteQuery = "INSERT INTO demoTable (name,phone_number,subject) VALUES('"+Name+"', '"+PhoneNumber+"', '"+Subject+"');";
SQLITEDATABASE.execSQL(SQLiteQuery);
Toast.makeText(MainActivity.this,"Data Submit Successfully", Toast.LENGTH_LONG).show();
ClearEditTextAfterDoneTask();
// addtoTextView();
}
else {
Toast.makeText(MainActivity.this,"Please Fill All the Fields", Toast.LENGTH_LONG).show();
}
}
public void CheckEditTextIsEmptyOrNot(String Name,String PhoneNumber, String subject ){
if(TextUtils.isEmpty(Name) || TextUtils.isEmpty(PhoneNumber) || TextUtils.isEmpty(Subject)){
CheckEditTextEmpty = false ;
}
else {
CheckEditTextEmpty = true ;
}
}
public void ClearEditTextAfterDoneTask(){
GetName.getText().clear();
GetPhoneNumber.getText().clear();
GetSubject.getText().clear();
}
/* void addtoTextView(){
cursor= SQLITEDATABASE.rawQuery("SELECT * FROM demoTable;",null);
if (cursor !=null && cursor.moveToFirst()){
String name;
do{
name = cursor.getString(0);
String pnone_number=cursor.getString(1);
String test2=cursor.getString(2);
String test3 = cursor.getString(3);
display.append(name + " " + pnone_number +" "+test2 +" "+ test3 +"\n");
} while (cursor.moveToNext());
}
display.append("-------------\n");
} */
public Cursor fetchAllItems() {
Cursor mCursor = SQLITEDATABASE.query(this.demoTable, new String[] {this.name,
this.phone_number, this.subject},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
private void displayListView()
{
Cursor cursor= fetchAllItems();
//The desired columns to be bound
String[] columns=new String[]{
this.name,
this.phone_number,
this.subject
};
//The XML defined views which the data will be bound to
int[] to = new int[] {
R.id.name,
R.id.phone_number,
R.id.subject,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
}
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();
}
});
}
}
package com.example.chris.thegiver;
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 LogIn extends AppCompatActivity implements View.OnClickListener {
private Button btnRegister2, btnLogIn;
private EditText etUser, etPass;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
btnRegister2 = (Button) findViewById(R.id.btnRegister2);
btnLogIn= (Button) findViewById(R.id.btnLogIn);
btnRegister2.setOnClickListener(this);
}
I think this is where I am having my problem. The app doesnt seem to access the database at all and in order to log in I need to check if the Username matches the password. If the password == the username then it will allow the user to log in. Unforunately that is not happening.
#Override
public void onClick(View v) {
if(v.getId() == R.id.btnRegister2){
startActivity(new Intent(LogIn.this, RegisterActivity.class));
}
if(v.getId() == R.id.btnLogIn){
EditText a = (EditText) findViewById(R.id.etUser);
String str = a.getText().toString();
EditText b = (EditText) findViewById(R.id.etPass);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if(pass.equals(password)){
Intent i = new Intent(LogIn.this,HomeActivity.class);
i.putExtra("Username: ", str);
startActivity(i);
}
else{
Toast temp = Toast.makeText(LogIn.this, "Username and Password dont match!", Toast.LENGTH_SHORT);
temp.show();
}
}
}
}
DATABASE CLASS
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COL_ID = "id";
private static final String COL_NAME= "name";
private static final String COL_EMAIL= "email";
private static final String COL_USERNAME= "username";
private static final String COL_PASSWORD= "password";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null, name text not null," +
"email text not null, username text not null, password text not null)";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
This method give functionality to the database and insert a users information whenever a new user object is created
public void insertContact(Contact c){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// * means all values
String query = "select * from contacts";
Cursor cursor = db.rawQuery(query,null);
int count = cursor.getCount();
values.put(COL_ID, count);
values.put(COL_NAME,c.getName());
values.put(COL_EMAIL, c.getEmail());
values.put(COL_USERNAME, c.getUsername());
values.put(COL_PASSWORD, c.getPassword());
**// this will insert the contact object into the database**
db.insert(TABLE_NAME, null, values);
db.close();
}
This method is where everything may be going wrong this searches the database for the username and checks if the username is equal to the password. If it isnt then b will be printed to the screen
public String searchPass(String uname){
db = this.getReadableDatabase();
String query = "select uname, pass from" + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a, b;
b = "not found";
if(cursor.moveToFirst()){
do{
//usernam
a = cursor.getString(0);
if(a.equals(uname)){
b = cursor.getString(1);
break;
}enter code here
}
while(cursor.moveToNext());
}
return b;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
REGISTRATION CLASS This sends the database all of the usernames information.
package com.example.chris.thegiver;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class RegisterActivity extends AppCompatActivity {
// calls the constructor of the DatabaseHelper class which will create the database and table
DatabaseHelper registerDB = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
public void onRegisterClick(View v) {
if (v.getId() == R.id.btnReg) {
EditText etName = (EditText) findViewById(R.id.etName);
EditText etEmail = (EditText) findViewById(R.id.etEmail);
EditText etUsername = (EditText) findViewById(R.id.etUsername);
EditText etPassword = (EditText) findViewById(R.id.etPassword);
EditText etConfirm = (EditText) findViewById(R.id.etConfirm);
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String user = etUsername.getText().toString();
String password = etPassword.getText().toString();
String confirm = etConfirm.getText().toString();
If password equals confirm then store everything in the java sqlite database created above.
If password and confirm password do not match then a toast message will appear saying passwords dont match.
if (password.equalsIgnoreCase(confirm)) {
Contact c = new Contact(); // Uses the contact class created earlier
c.setName(name);
c.setEmail(email);
c.setUsername(user);
c.setPassword(password);
registerDB.insertContact(c);
startActivity(new Intent(RegisterActivity.this,LogIn.class));
}
else {
// Pop up message
Toast pass = Toast.makeText(RegisterActivity.this, "Passwords Dont Match!", Toast.LENGTH_SHORT);
pass.show();
}
}
}
Android providing the directly SQLiteDatabase class by using this class you can access the data from database, no need to write the DatabaseHelper class
SQLiteDatabase db=openOrCreateDatabase("avishbarcodes.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setLocale(Locale.getDefault());
Create the table like this..
String createtable="CREATE TABLE IF NOT EXISTS eannumbers(_id INTEGER PRIMARY KEY AUTOINCREMENT,count NUMBER,ean_no TEXT)";
db.execSQL(createtable);
Read the values from database like this..
String selectquery= "select * from eannumbers";
Cursor c=db.rawQuery(selectquery, null);
if(c==null){
}else if(c.getCount()<=0){
}else{
while(c.moveToNext()){
String ean_no=c.getString(c.getColumnIndex("ean_no"));
}
c.close();
}
don't access the column values like this..
cursor.getString(1);
follow this way its better way..
c.getString(c.getColumnIndex("ean_no"));
when user click the login button check like this
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String selectquery= "select * from login";
Cursor c=db.rawQuery(selectquery, null);
if(c==null){
}else if(c.getCount()<=0){
}else{
while(c.moveToNext()){
String email=c.getString(c.getColumnIndex("emailid"));
String pwd=c.getString(c.getColumnIndex("pwd"));
}
c.close();
}
}
});
Do like this.. it will work...
My error:
at com.me.samplesqlite.DatabaseHelper.checkEmailExists(DatabaseHelper.java:83) at com.me.samplesqlite.DatabaseHelper.insert(DatabaseHelper.java:67) at com.me.samplesqlite.SignUp.onSignUpClick(SignUp.java:84)
I am getting an error (force stop) after i filled-up all the fields in my registration module.
I just want to have a validation for avoiding duplication of email address. Someone please help me with this kind of validation? This is a simple registration with some validations. So, my target here is to avoid duplication of inserted data for email address.
My goal is when there is an existing email address it will not be able to register again with the same email add
**package com.me.samplesqlite;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SignUp extends Activity
{
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
}
public void onSignUpClick(View view)
{
if(view.getId() == R.id.btnSignUp)
{
EditText name = (EditText)findViewById(R.id.txtName);
EditText uname = (EditText)findViewById(R.id.txtUsername);
EditText email = (EditText)findViewById(R.id.txtEmail);
EditText pass = (EditText)findViewById(R.id.txtPassword);
EditText cpass = (EditText)findViewById(R.id.txtConfirmPass);
String sname = name.getText().toString();
String suname = uname.getText().toString();
String semail = email.getText().toString();
String spass = pass.getText().toString();
String scpass = cpass.getText().toString();
if(sname.length()==0 && suname.length()==0 && semail.length()==0 && spass.length()==0)
{
name.requestFocus();
name.setError("FIELD CANNOT BE EMPTY");
uname.requestFocus();
uname.setError("FIELD CANNOT BE EMPTY");
email.requestFocus();
email.setError("FIELD CANNOT BE EMPTY");
pass.requestFocus();
pass.setError("FIELD CANNOT BE EMPTY");
}
else if(!sname.matches("[a-zA-Z]+"))
{
name.requestFocus();
name.setError("ENTER ONLY ALPHABETICAL CHARACTER");
}
else if(!(spass.length()>5))
{
pass.requestFocus();
pass.setError("PASSWORD MUST HAVE MORE THAN 5 CHARACTERS");
}
else if (!scpass.equals(spass))
{
cpass.requestFocus();
cpass.setError("PASSWORD DON'T MATCH");
}
else if(!semail.matches("[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+"))
{
email.requestFocus();
email.setError("INVALID EMAIL ADDRESS");
}
else
{
Contact b = new Contact();
boolean isEmailExist = helper.insertContact(b);
if(isEmailExist)
{
// notify user
Toast mail = Toast.makeText(SignUp.this, "Email Already Exist." , Toast.LENGTH_SHORT );
mail.show();
}
else
{
// proceed
Contact c = new Contact();
c.setName(sname);
c.setUName(suname);
c.setEmail(semail);
c.setPass(spass);
helper.insertContact(c);
//popup message
Toast password = Toast.makeText(SignUp.this, "Data has been saved." , Toast.LENGTH_SHORT );
password.show();
Intent i = new Intent(SignUp.this, MainActivity.class);
startActivity(i);
}
//insert the details on database
}
}
if(view.getId() == R.id.btnCancelSign)
{
Intent i = new Intent(SignUp.this, MainActivity.class);
startActivity(i);
finish();
}
}
}
**
package com.me.samplesqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null , " +
"name text not null , uname text not null , email text not null , pass text not null);";
public DatabaseHelper(Context context)
{
super(context , DATABASE_NAME , null , DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(TABLE_CREATE);
this.db = db;
}
public boolean insertContact(Contact c)
{
boolean isEmailExist = false;
db = this.getReadableDatabase();
ContentValues values = new ContentValues();
String query = "select * from contacts";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NAME , c.getName());
values.put(COLUMN_UNAME , c.getUName());
values.put(COLUMN_EMAIL , c.getEmail());
values.put(COLUMN_PASS, c.getPass());
if(checkEmailExists(c.getEmail()))
{
isEmailExist = true;
}
else
{
db.insert(TABLE_NAME, null, values);
}
db.close();
return isEmailExist;
}
private boolean checkEmailExists(String email) {
String query = new StringBuilder().append("Select ")
.append(email).append(" from ").append(TABLE_NAME)
.toString();
Cursor cursor = db.rawQuery(query,
new String[] { email });
if (cursor.getCount() > 0) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}
public String searchPass(String uname)
{
db = this.getReadableDatabase();
String query = "select uname, pass from "+ TABLE_NAME;
Cursor cursor = db.rawQuery(query , null);
String a,b;
b = "not found";
if(cursor.moveToFirst())
{
do
{
a = cursor.getString(0);
b = cursor.getString(1);
if(a.equals(uname))
{
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_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
relpace your checkEmailExists with below
private boolean checkEmailExists(String email) {
String query = "Select * from "+TABLE_NAME+" where email like '"+email+"'";
Cursor cursor = db.rawQuery(query,
null);
if (cursor.getCount() > 0) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}
2.Replace your create table query with this and let me know
private static final String TABLE_CREATE = "create table IF NOT EXISTS contacts (id integer primary key not null , " +
"name text not null , uname text not null , email text not null , pass text not null);";
3.Also you passing blank object to database for email check replace that with below
Contact b = new Contact();
b.setName(sname);
b.setUName(suname);
b.setEmail(semail);
b.setPass(spass);
boolean isEmailExist = helper.insertContact(b);
i think you are comparing it wrong. In your this part of code
private boolean checkEmailExists(String email) {
String query = new StringBuilder().append("Select ")
.append(email).append(" from ").append(TABLE_NAME)
.toString();
Cursor cursor = db.rawQuery(query,
new String[] { email });
if (cursor.getCount() > 0) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}
in this function you are taking the email which is enters by the user and putting it in the database directly but where you have done the matching ?
which part of code shows that you are comparing the email from the database email addresses .
what you should have done is
1. Make a function in the database which returns you a list on emails form the data base , lets suppose that you have 5 records , each has email filed, so make a function which returns the list of only emails , let say this function is called emailList();
call this function in your activity code and get the list , as I said above suppose you have 5 record so you have first to check the length of list , let say its length if of index 4
3 on button click event before saving data , you are most like to run the for loop , get each email from list from index zero and compare it with the current entered email address by the user , if it exist stop there and tell the user about the error if not then continue to save data to the database and sign up would be proceed
that all you need to implement.
I am having a problem validating my login for my android app. I have 2 fields that require user to enter email and password, if both exist in db then they will be taken to mainscreen (log in successful) if incorrect error will appear. I have tried everything but still doesnt work! Please help I have posted my code below.
package com.example.finalproject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity implements OnClickListener{
EditText mEmailAdd;
EditText mPassword;
private SQLiteAdapter mydb = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//addListenerOnButton();
}
public void onCreateMainscreen(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenmain_activity);
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogMain:
mEmailAdd = (EditText)findViewById(R.id.email);
mPassword = (EditText)findViewById(R.id.password);
String uname = mEmailAdd.getText().toString();
String pass = mPassword.getText().toString();
if(uname.equals("") || uname == null){
Toast.makeText(getApplicationContext(), "email Empty", Toast.LENGTH_SHORT).show();
}else if(pass.equals("") || pass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(uname, pass, LoginActivity.this);
if(validLogin){
System.out.println("In Valid");
Intent i = new Intent(LoginActivity.this, MainMenuActivity.class);
startActivity(i);
finish();
}
}
break;
}
}
// #SuppressWarnings("deprecation")
public boolean validateLogin(String uemail, String pass, Context context) {
mydb = new SQLiteAdapter(this);
SQLiteAdapter db = mydb.openToWrite();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "email=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uemail,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE email=uemail AND password=pass
cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void onDestroy(){
super.onDestroy();
mydb.close();
}
}
DATABASE CLASS
package com.example.finalproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "MY_PROJECT_DATABASE";
public static final String MYDATABASE_TABLE = "MY_USERS_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_EMAIL + " text not null, "
+ KEY_PASSWORD + " text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String name, String email, String password){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_EMAIL, email);
contentValues.put(KEY_PASSWORD, password);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_NAME, KEY_EMAIL,KEY_PASSWORD};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
not your error, but change
if(uname.equals("") || uname == null){ // throws nullpointerexception if uname == null
to
if(uname == null || uname.length() == 0 ){ // throws no exception and also checks the " "
Not sure if this was just a copy-paste error but the code as provided not only doesn't compile, but never sets up the click listener for the login button either. Here's what I modified to make it both compile and query the database.
In SQLiteAdapter:
public SQLiteDatabase openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return sqLiteDatabase;
}
In LoginActivity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//addListenerOnButton();
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public void onCreateMainscreen(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenmain_activity);
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public boolean validateLogin(String uemail, String pass, Context context) {
mydb = new SQLiteAdapter(this);
SQLiteDatabase db = mydb.openToWrite();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "email=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uemail,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE email=uemail AND password=pass
cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
Note also that this code will never insert anything into the database, either. I assume this will be done elsewhere. Further there are many naming convention and general good practices being broken here.
A few issues:
Never do database work on the main thread.
Variables prefixed with 'm' indicate they are member variables of the class.
Be sure to use the #Override notation when appropriate.