How do I make sure username is not repeated in my database? - java

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();
}

Related

How to Setup a Sign up and login form in android studio and link it with SQLite database

I have some problem when I get to link the two form in my android application with SQLite database can you please help me to get the right code because, I try many time to find where the e problem and I didn't get it.
this is the code in loginActivity linked with form of login, I think the code is all correct but I have a problem is the user when he try to insert the email and password that he signup with it it show that it's invalid data in spite of the data is correct, I think the problem is with the the section of the if statement (res.getCount()== 1).
package com.example.cs50;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class loginActivity2 extends AppCompatActivity {
TextView dont_have_account;
EditText email,password;
Button signin;
DBapp my_DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
email=findViewById(R.id.editEmail);
password=findViewById(R.id.editPassword);
signin=findViewById(R.id.buttonLogin);
my_DB = new DBapp(this);
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attemp_login();
}
});
//make listener for text dont have account
dont_have_account=findViewById(R.id.textview_dont_have_account);
dont_have_account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(loginActivity2.this,signupActivity2.class);
startActivity(intent);
}
});
}
private void attemp_login() {
String Email=email.getText().toString();
String pass=password.getText().toString();
if(!isEmailValid(Email)){
Toast.makeText( this, "Email Invalid", Toast.LENGTH_SHORT).show();
}
if(!isPasswordValid(pass)){
Toast.makeText( this, "Password Invalid", Toast.LENGTH_SHORT).show();
}
Cursor res = my_DB.login_user(Email,pass);
if (res.getCount()== 1){
final Intent intent = new Intent(loginActivity2.this,Home.class);
startActivity(intent);
}
else {
Toast.makeText( this, "Invalid Account", Toast.LENGTH_SHORT).show();
}
}
private boolean isEmailValid(String email){
return email.contains("#");
}
private boolean isPasswordValid(String password){
return password.length()>6;
}
}
the class of Signup Activity it totally work for me but ,I must have another statement to check that if the data already have insert in the signup form (account already signup), and after that it must to redirect him to the login form, but I didn't know how to implement this statement, can you please help me to setup the correct statement to do that this is the code of The signup Activity.
package com.example.cs50;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.pedant.SweetAlert.SweetAlertDialog ;
public class signupActivity2 extends AppCompatActivity {
TextView already_signin;
EditText username,email,password;
Button signup;
DBapp my_DB;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup2);
username=findViewById(R.id.editName);
email = findViewById(R.id.editEmail);
password=findViewById(R.id.editPassword);
signup=findViewById(R.id.buttonSignup);
my_DB = new DBapp(this);
Register_user();
//make listener for text already sign in
already_signin =findViewById(R.id.textView_alreadysign);
already_signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(signupActivity2.this,loginActivity2.class);
startActivity(intent);
}
});
}
private void Register_user() {
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Email=email.getText().toString();
String pass=password.getText().toString();
String user=username.getText().toString();
if(!isEmailValid(Email)){
Toast.makeText(signupActivity2.this, "Is Not Valid Email try Again", Toast.LENGTH_SHORT).show();
}
else if(!isPasswordvalid(pass)){
Toast.makeText( signupActivity2.this, "Too Small password length !!!",Toast.LENGTH_SHORT) .show();
}
else if(Email.isEmpty()){
Toast.makeText(signupActivity2.this, "Mail field Required !!", Toast.LENGTH_SHORT).show();
}
else if(pass.isEmpty()) {
Toast.makeText(signupActivity2.this, "Password Field Required !!", Toast.LENGTH_SHORT).show();
}
else {
boolean isInserted= my_DB.insertData(Email,pass,user);
new SweetAlertDialog( signupActivity2.this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Message")
.setContentText("You are Registered")
.setConfirmText("OK")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener(){
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
Intent i =new Intent( signupActivity2.this, loginActivity2.class);
startActivity(i);
}
})
.show();
}
}
});
}
private boolean isEmailValid(String email){
return email.contains("#");
}
private boolean isPasswordvalid(String password){
return password.length()>6;
}
}
and Finally this is the code of the database
package com.example.cs50;
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;
public class DBapp extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "DB";
public static final String TABLE_NAME = "user";
public static final String COL_2 = "EMAIL";
public static final String COL_3 = "USERNAME";
public static final String COL_4 = "PASSWORD";
public DBapp(#Nullable 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, EMAIL TEXT , USERNAME TEXT,PASSWORD TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//registration
public boolean insertData(String email, String password, String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues ContentValues = new ContentValues();
ContentValues.put(COL_2, email);
ContentValues.put(COL_3, username);
ContentValues.put(COL_4, password);
long result = db.insert(TABLE_NAME, null, ContentValues);
if (result == -1)
return false;
else
return true;
}
//LOGIN
public Cursor login_user(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery(" Select * from " + TABLE_NAME + " where EMAIL= '" + email + " 'and PASSWORD= '" + password + "'", null);
return res;
}
}
if you didn't understand something in the code please mention that for me to explain more the code for you.
Issue
I believe that your issue is that you have an errant space in the query that is added to the end of the email.
Fix
Change :-
Cursor res = db.rawQuery(" Select * from " + TABLE_NAME + " where EMAIL= '" + email + " 'and PASSWORD= '" + password + "'", null);
to :-
Cursor res = db.rawQuery(" Select * from " + TABLE_NAME + " where EMAIL= '" + email + "' and PASSWORD= '" + password + "'", null);
Recommended FIX
However, it would be considered better practice to use the query convenience method and to utilise parameter binding which offers protection against SQL Injection.
As such you may wish to consider using:-
public Cursor login_user(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_NAME,null,"email=? AND password=?",new String[]{email,password},null,null,null );
}
This has the advantage that the values will be suitable enclosed in single quotes and the accidental errant extra space would not result.
Recommended other changes
You should also note that when traversing activities, that the correct way is to finish() the child activity it will then return to the parent activity. Starting the parent activity actually results in the actual parent activity being destroyed and a new parent activity being started.
e.g. consider using :-
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
//Intent i =new Intent( signupActivity2.this, loginActivity2.class);
//startActivity(i);
finish(); //<<<<<<<<<< RETURN TO PARENT (invoking) ACTIVITY
}
})
.show();
old code commented out.

How to compare data from different activities using SQLite on Android Studio

//MAIN ACTIVITY
package com.example.saosteste2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private BancoDados_Registo dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new BancoDados_Registo(MainActivity.this);
TextView email = (TextView) findViewById(R.id.id_email);
TextView password = (TextView) findViewById(R.id.id_password);
Button BLogIn = (Button) findViewById(R.id.id_Blogin);
Button conta_btn = (Button) findViewById(R.id.id_criarconta);
//testing email e password
BLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ????
}
});
conta_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, registo.class);
startActivity(intent);
}
});
}
}
//-----------------------SECOND ACTIVITY WITH THE DATABASE-----------------------//
//BANCODADOS_REGISTOS
package com.example.saosteste2;
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 android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class BancoDados_Registo extends SQLiteOpenHelper {
public BancoDados_Registo(Context context) {
super(context, "REGISTOS.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create Table Registos(nome TEXT primary key, email TEXT, password TEXT, morada TEXT, telemovel TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop Table if exists Registos");
}
// INSERT DATA
public Boolean insertuserdata(String nome, String email, String password, String morada, String telemovel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nome", nome);
contentValues.put("email", email);
contentValues.put("password", password);
contentValues.put("morada", morada);
contentValues.put("telemovel", telemovel);
long result=db.insert("Registos", null, contentValues);
if (result==-1){ //se o insert falhar
return false;
}else{
return true;
}
}
//UPDATE DATA
public Boolean updateuserdata(String nome, String email, String password, String morada, String telemovel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nome", nome);
contentValues.put("email", email);
contentValues.put("password", password);
contentValues.put("morada", morada);
contentValues.put("telemovel", telemovel);
Cursor cursor = db.rawQuery("Select * from Registos where nome = ?", new String[] {nome});
if (cursor.getCount()>0){ //se o cursor tiver dados
long result=db.update("Registos", contentValues, "nome=?", new String [] {nome});
if (result==-1){ //se o insert falhar
return false;
}else{
return true;
}
}else {
return false;
}
}
//DELETEDATA
public Boolean deleteuserdata(String nome){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from Registos where nome = ?", new String[] {nome});
if (cursor.getCount()>0){ //se o cursor tiver dados
long result=db.delete("Registos", "nome=?", new String [] {nome});
if (result==-1){ //se o insert falhar
return false;
}else{
return true;
}
}else {
return false;
}
}
public Cursor getuserdata(String email, String password){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from Registos", null);
return cursor;
}
Hi everyone!
I'm new in the world of Java and Android Studio. I don't know how to transmit data from the databse created in the second Activity to the first one. I need help checking if the email and password that the user puts on the first Activity (MainActivity) already exists in the database I created in the second Activity (BancoDados_Registo). Thank you for your attention in advance!
Here's a working example (but one that uses the deprecated startActivityForresult) based upon your code.
You should really look at https://developer.android.com/training/basics/intents/result for the non-deprecated way though.
When the App is started MainActivity displays the login/registo buttons:-
note hints added for email and password just to show where the TextViews.
Clicking the Registo button starts the Registo activity with empty EditTexts
for the nome,email,password morada and telemovel and a button to register (add) :-
Entering suitable data e.g. :-
And then clicking the Registo button, adds the user (if not a duplicate) and returns to MainActivity passing the nome and rowid which is then used to complete the email and password TextViews (not that you would do this, but rather to show extracting the data from the database) :-
The code:-
MainActivty
public class MainActivity extends AppCompatActivity {
private BancoDados_Registo dbManager;
TextView email; //<<<<< MOVED for full scope
TextView password; //<<<<< Moved for full scope
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new BancoDados_Registo(MainActivity.this);
email = (TextView) findViewById(R.id.id_email);
password = (TextView) findViewById(R.id.id_password);
Button BLogIn = (Button) findViewById(R.id.id_Blogin);
Button conta_btn = (Button) findViewById(R.id.id_criarconta);
//testing email e password
BLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ????
}
});
conta_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Registo.class);
startActivityForResult(intent,Registo.REGISTO_RESULTSCODE); // deprecated but works
}
});
}
#SuppressLint("Range")
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Registo.REGISTO_RESULTSCODE && resultCode == RESULT_OK) {
Toast.makeText(this,"Registered with ID " + data.getLongExtra(Registo.INTENTEXTRAKEY_REGISTOID,-1),Toast.LENGTH_LONG).show();
if (data.getLongExtra(Registo.INTENTEXTRAKEY_REGISTOID,-1) > 0) {
Cursor csr = dbManager.getUserDataByNome(data.getStringExtra(Registo.INTENTEXTRAKEY_REGISTONOME));
if (csr.moveToFirst()) {
password.setText(csr.getString(csr.getColumnIndex("password")));
email.setText(csr.getString(csr.getColumnIndex("email")));
}
}
}
}
}
BancoDados_Registo (changed/added methods only) :-
// INSERT DATA <<<<< CHANGED (to return rowid which can be more useful as it can be used to get the row)
public Long insertuserdata(String nome, String email, String password, String morada, String telemovel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nome", nome);
contentValues.put("email", email);
contentValues.put("password", password);
contentValues.put("morada", morada);
contentValues.put("telemovel", telemovel);
return db.insert("Registos", null, contentValues);
}
/* ADDED to get User just by nome */
public Cursor getUserDataByNome(String nome) {
SQLiteDatabase db = this.getWritableDatabase();
return db.query("Registos",null,"nome=?",new String[]{nome},null,null,null);
}
Registo activity (note capitalised) :-
public class Registo extends AppCompatActivity {
private BancoDados_Registo dbManager;
public static final int REGISTO_REQUESTCODE = 98; //<<<
public static final String INTENTEXTRAKEY_REGISTOID = "ie_registo_id";
public static final String INTENTEXTRAKEY_REGISTONOME = "ie_registo_nome";
EditText nome;
EditText email;
EditText password;
EditText morada;
EditText telemovel;
Button registro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registo);
nome = this.findViewById(R.id.id_nome);
email = this.findViewById(R.id.id_email);
password = this.findViewById(R.id.id_password);
morada = this.findViewById(R.id.id_morada);
telemovel = this.findViewById(R.id.id_telemovel);
registro = (Button) findViewById(R.id.id_registro);
dbManager = new BancoDados_Registo(this);
registro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* Only insert in valid data - else Toast incomplete*/
if (
email.getText().length() > 0
&& password.getText().length() >= 8
&& morada.getText().length() > 0
&& telemovel.getText().length() > 0
) {
Long rowid = dbManager.insertuserdata(nome.getText().toString(),email.getText().toString(),password.getText().toString(),morada.getText().toString(),telemovel.getText().toString());
if (rowid > 0) {
Toast.makeText(view.getContext(),"Registered",Toast.LENGTH_LONG).show();
Intent resultIntent = new Intent();
resultIntent.putExtra(INTENTEXTRAKEY_REGISTOID,rowid);
resultIntent.putExtra(INTENTEXTRAKEY_REGISTONOME,nome.getText().toString());
setResult(RESULT_OK,resultIntent);
finish();
} else {
Toast.makeText(view.getContext(),"Not Registered (duplicate)",Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(view.getContext(),"Not Registered Incomplete input fields!!",Toast.LENGTH_LONG).show();
}
}
});
}
}

"User Name or Password does not match" even when the username and pass exist in database and are valid

I have been trying to create a sign up and login page and using only username and password worked but when I added the field of subject I can't log into the account I create and it says "User Name or Password does not match". I am pretty sure the error is in my LoginDataBaseAdapter but im not sure what is the error.
DataBaseHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
LoginDataBaseAdapter.java
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;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text,SUBJECT text); ";
// 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 Subject)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("SUBJECT", Subject);
// 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"));
String Subject= cursor.getString(cursor.getColumnIndex("SUBJECT"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password,String Subject)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
updatedValues.put("SUBJECT", Subject);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
}
MainActivity.java+login page
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity
{
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity abd Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
// Methos to handleClick Event of Sign In Button
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(MainActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.putString("USERNAME",userName);
editor.apply();
Intent myIntent = new Intent(getBaseContext(), signedin.class);
myIntent.putExtra("USERNAME",userName);
startActivity(myIntent);
}
else
{
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
SignUPActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword,editTextSubject;
Button btnCreateAccount;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get References of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
editTextSubject=(EditText)findViewById(R.id.editTextSubject);
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 Subject=editTextSubject.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals("")||Subject.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;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password, Subject);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
startActivity(myIntent);
}
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
}
Contact.java
public class Contact {
String uname;
String pass;
String subject;
public Contact(String uname,String pass,String subject)
{
this.uname=uname;
this.pass=pass;
this.subject=subject;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
First thing you should do - to browse you sqlite database data. There are different tools that can help you in that (DB Browser for example). Without that you can only guess what is the source of your problem.
There are several possible scenarios you can get analysing your problem test-case:
There are no rows in your table with the username you test. Since your save-login code has no mistakes (it seemed so), this is probably not the case.
There is only one row with the username and saved password differs. If it's so, you're searching for the black cat in black room :-)
There is only one row with the username and saved password the same as you're trying to test. According to your code I think it can't be.
There are several rows with the same username. Technically it can be because you haven't put some check to prevent keeping one username with different passwords. By the way, you have method "updateEntry", but you don't use it anywhere, just "insertEntry". May be it's time to use it?
My sixth sense tell me that variant 4 will be the winner

signup button linked to sqlite database

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();
}
});
}
}

Cant validate Login on Android app using a SQLite db

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.

Categories