I want to match password by enter user to database base password.Anybody Help me please.I am very Tired.
Adapter.java
public Cursor getUserInfo(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_FULLNAME, KEY_EMAILID, KEY_PASSWORD}, KEY_ROWID + "=" + rowId , null,
null, null, null, null);
if (mCursor.getCount()<1) {
return mCursor;
}
mCursor.moveToNext();
String dpassword = mCursor.getString(mCursor.getColumnIndex("PASSWORD"));
return mCursor;
}
Login.java
Error come in this Class that tell to create the a variable dpassword.
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
// get the user details email or password
String useremail = emailornumber.getText().toString();
String password = userpassword.getText().toString();
//fetch the password from the database
String storedPassword = databaseAdapter.getUserInfo(dpassword);
// check if password is match
if(userpassword.equals(storedPassword)){
Toast.makeText(LoginActivity.this, "You are Login", Toast.LENGTH_LONG).show();
Intent in = new Intent(LoginActivity.this, MainActivity.class);
}
else
{
Toast.makeText(LoginActivity.this, "Username and Password Does not match", Toast.LENGTH_LONG).show();
}
}
Your line of code:
String storedPassword = databaseAdapter.getUserInfo(dpassword);
is incorrect. You do not have a variable named dpassword and therefore cannot use that name. This is why you are receiving the error message you describe.
Try Lik this ,it will Solve your Problem
Calling the method
String storedPassword = DB.getSingleEntry(email);
Your Database Method
//checking email to Corresponding password
public String getSingleEntry(String email)
{
Cursor cursor=database.query(DataBaseConnector.TABLE_NAME, null, " email=?", new String[]{email}, null, null, null);
if(cursor.getCount()<1) // Email Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("Password"));
cursor.close();
return password;
}
Related
I'm confused and cannot figure out how I can send an SMS message using values stored on my database.
The SMS would appear like this: ('NAME'... Message content, etc..), the message would then be sent using the contact numbers entered by the user on the sqlite database.
Here's the code I've used to get the data during signup.
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, NAME text, C1 integer, C2 integer); ";
// 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 name, String cn1, String cn2) {
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("NAME",name);
newValues.put("C1", cn1);
newValues.put("C2", cn2);
// 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 getSingleEntry(String userName) {
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) { // username doesn't exist
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public boolean isExist (String userName) {
boolean exists;
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if (cursor.getCount()>0) { // username exists
exists = true;
cursor.close();
return exists;
}
return false;
}
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});
}}
And here is the SignUpActivity
public class SignUpActivity extends AppCompatActivity {
Button bSignup;
TextView tvSign;
EditText etUN, etPW, etPW2, etFN, etC1, etC2;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
bSignup = (Button)findViewById(R.id.bSignup);
tvSign = (TextView)findViewById(R.id.tvSign);
etUN = (EditText)findViewById(R.id.etUN);
etPW = (EditText)findViewById(R.id.etPW);
etPW2 = (EditText)findViewById(R.id.etPW2);
etFN = (EditText)findViewById(R.id.etFN);
etC1 = (EditText)findViewById(R.id.etC1);
etC2 = (EditText)findViewById(R.id.etC2);
bSignup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUN.getText().toString();
String password = etPW.getText().toString();
String password2 = etPW2.getText().toString();
String name = etFN.getText().toString();
String c1 = etC1.getText().toString();
String c2 = etC2.getText().toString();
// check if fields are vacant
if (username.equals("") || password.equals("") || password2.equals("") || name.equals("")
|| c1.equals("")|| c2.equals("")) {
Toast.makeText(getApplicationContext(), "Incomplete Data", Toast.LENGTH_SHORT).show();
return;
}
// check if passwords 1 and 2 match
if (!password.equals(password2)) {
Toast.makeText(getApplicationContext(), "Passwords don't match. Please try again.", Toast.LENGTH_LONG).show();
return;
}
//check is username is still available for use
if (loginDataBaseAdapter.isExist(username)){
Toast.makeText(getApplicationContext(),"Username already taken. Please try again.", Toast.LENGTH_LONG).show();
return;
}
else {
// allow data to be saved in the database
loginDataBaseAdapter.insertEntry(username, password, name, c1, c2);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
});
tvSign.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
}
Once I'm logged in, how can I get those values ("i.e. NAME, C1, and C2") and send an SMS by pushing a button?
Update
I've used this on my LoginDataBaseAdapter.
public HashMap<String, String> getUserDetails(){
HashMap <String,String> user = new HashMap <String,String> ();
String selectQuery = "SELECT * FROM " + "LOGIN";
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount()>0){
user.put("USERNAME", cursor.getString(1));
user.put("PASSWORD", cursor.getString(2));
user.put("NAME", cursor.getString(3));
user.put("C1", cursor.getString(4));
user.put("C2", cursor.getString(5));
}
cursor.close();
db.close();
// return user
return user;
}
Then this code at my HomeActivity:
tvHello = (TextView)findViewById(R.id.tvHello);
HashMap <String, String> details = loginDataBaseAdapter.getUserDetails();
String name_text = details.get("NAME");
tvHello.setText("Welcome " + name_text);
It seems that it can only get the first entry and not the current entry for the current user. Any ideas to fix this issue? Thank you very much.
Managed to get it right. So I'll answer my own question.
Create a editText area wherein you'll enter your name to retrieve. Then use this code to retrieve it
public String getData(String verif) {
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{verif}, null, null, null);
if(cursor.getCount()<1) {
cursor.close();
return "No records exist";
}
cursor.moveToFirst();
String get_name = cursor.getString(cursor.getColumnIndex("NAME"));
cursor.close();
return get_name;
}
Once retrieved, set the name in a TextView. Then convert it to string like so:
String myName = myTextView.getText().toString();
Then:
smsManager.sendTextMessage(number, null, "My name is "+ myName ,null,
null);
'number' is a String containing the contact number where you want to send your SMS
I am getting cursor index out of bounds "index 0 requested: with size 0". Its just a user registration and login application. When there is no user with matching Username and Password my application is getting crashed.
Below is the code:
MainActivity.java
final SUSQLiteHelper dbhelper = new SUSQLiteHelper(this);
LoginData login = dbhelper.readOneUser(loginuname.getText().toString(), loginpwd.getText().toString());
if(login.getUname().toString().equals(loginuname.getText().toString()) &&
login.getPwd().toString().equals(loginpwd.getText().toString()))
{
Toast.makeText(getApplicationContext(), "Login Successfull. Welcome " + login.getUname().toUpperCase() +" !".toString(),
Toast.LENGTH_LONG).show();
}
else if(login.getUname().toString().equals(loginuname.getText().toString()) &&
!login.getPwd().toString().equals(loginpwd.getText().toString()))
{
Toast.makeText(getApplicationContext(), "Login Failed. Incorrect password !",
Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(), "Login Failed. User doesn't exist !",
Toast.LENGTH_LONG).show(); //it never goes here if no username is found in the table
SUSQLiteHelper.java
public LoginData readOneUser(String uname, String pwd)
{
SQLiteDatabase loginUserDB = this.getReadableDatabase();
LoginData newLogin = null;
Cursor cursor = loginUserDB.query(TABLE_NAME, new String[]{TABLE_ROW_UNAME, TABLE_ROW_EMAIL, TABLE_ROW_PWD}, TABLE_ROW_UNAME + "=?",
new String[]{String.valueOf(uname)}, null, null, null);
if(cursor.moveToFirst())
{
newLogin = new LoginData(cursor.getString(0), cursor.getString(1), cursor.getString(2));
}
cursor.close();
loginUserDB.close();
return newLogin;
}
LoginData.java
This class has getter and setter methods for Uname, Pwd, Email fields and a constructor which takes these fields as arguments.
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
It means that cursor.moveToFirst() returns false and Cursor is empty. So try to add the snippet for checking whether cursor is null or not and depends upon that modify your logic.
public LoginData readOneUser(String uname, String pwd)
{
SQLiteDatabase loginUserDB = this.getReadableDatabase();
LoginData newLogin = null;
Cursor cursor = loginUserDB.query(TABLE_NAME, new String[]{TABLE_ROW_UNAME, TABLE_ROW_EMAIL,TABLE_ROW_PWD}, TABLE_ROW_UNAME + "=?",new String[]{String.valueOf(uname)}, null, null, null);
if(cursor!=null) //Check whether cursor is null or not
{
if(cursor.moveToFirst())
{
newLogin = new LoginData(cursor.getString(0), cursor.getString(1), cursor.getString(2));
}
}
cursor.close();
loginUserDB.close();
return newLogin;
}
LoginData login = dbhelper.readOneUser(loginuname.getText().toString(), loginpwd.getText().toString());
if(login!=null)
{
//check for incorrect username or password
}
else
{
//Notify that no Username available with these Username
}
In function readOneUser(), check:
if(cursor.moveToFirst() && !cursor.isAfterLast()) {
//
}
I need to get a Username and Password...I'm doing Password Recovery in my Application so here is my code for DB:
public String getEmailAddr() throws SQLException {
Cursor mCursor = db.rawQuery(
"SELECT Username, Passwords FROM " +
USERS_TABLE + " WHERE EmailNO=?",null);
if (mCursor != null) {
if(mCursor.getCount() > 0 {
//return obj1.getpassword();
}
}
//return false;
return obj1.getpassword();
}
And when the User enters an Email Address it must first check for existence and return Password and the username with using my Activity code for sending Email:
public void onClick(View v) {
String EmailAddress = txtEmailAddress.getText().toString();
try {
if(EmailAddress.length() > 0) {
DBAdapter dbUser = new DBAdapter (RecoverPassword.this);
dbUser.open();
if(dbUser.getEmailAddress(EmailAddress)) {
Toast.makeText(RecoverPassword.this,
"Email Successfully ",
Toast.LENGTH_LONG).show();
Toast.makeText String to =
txtEmailAddress.getText().toString();
//String subject = EmailAddress.getText().toString();
// String message = EmailAddress.getText().toString();
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
email.putExtra(Intent.EXTRA_SUBJECT, "Password Recovery");
email.putExtra(Intent.EXTRA_TEXT, dbUser.getEmailAddr());
//need this to prompts email client only
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "gmail :"));
}
else {
Toast.makeText(RecoverPassword.this,
"Invalid Email", Toast.LENGTH_LONG).show();
txtEmailAddress.setText("");
}
dbUser.close();
}
}
catch(Exception e) {
Toast.makeText(RecoverPassword.
this,e.getMessage(), Toast.LENGTH_LONG).show();
}
Please help me to check what is wrong...but there is no error but it cant return
username and password to the email sent
I'm confused from your code but when you want to get data from Cursor so
String[] whereArgs = new String[<data>];
Cursor mCursor = db.rawQuery("SELECT Username, Passwords FROM " + USERS_TABLE + " WHERE EmailNO = ?", whereArgs);
mCursor.moToFirst();
if(mCursor.getCount() > 0} {
String userName = mCursor.getString(0);
String password = mCursor.getString(1);
}
You must use getters that offers Cursor instance which return data from database.
EDIT:
I have not noticed that you using whereArgs so when you use WHERE clause, you have to specific whereArgs as String[] that contains data which will be replaced instead of ? char.
Fo close database you can use:
#Override
protected void onDestroy() {
super.onDestroy();
if (yourDatabase != null) {
yourDatabase.close();
}
}
Or after each work that opens your db you should close() db.
In
Cursor mCursor = db.rawQuery("SELECT Username, Passwords FROM " + USERS_TABLE + " WHERE
EmailNO=?",null);
You are not providing the value for EmailNO. Put the value in place of null.
Edit: I think your code should be like this:
public boolean getEmailAddress(String emailNo)
throws SQLException { //pass the EmailNo which you want in where clause
Cursor mCursor = db.rawQuery(
"SELECT Username, Passwords FROM sddashsd WHERE
EmailNO='"+emailNo+"'",null);
if (mCursor != null) {
if(mCursor.getCount() > 0)
return true;
else
return false;
}
}
And edit your code here:
public void onClick(View v) {
String EmailAddress =
txtEmailAddress.getText().toString();
try {
if(EmailAddress.length() > 0) {
DBAdapter dbUser = new DBAdapter (RecoverPassword.this);
dbUser.open();
if(dbUser.getEmailAddress(EmailAddress)) {
Toast.makeText(RecoverPassword.this,
"Email Successfully ", Toast.LENGTH_LONG).show();
String to = txtEmailAddress.getText().toString();
//String subject = EmailAddress.getText().toString();
// String message = EmailAddress.getText().toString();
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
email.putExtra(Intent.EXTRA_SUBJECT, "Password Recovery");
email.putExtra(Intent.EXTRA_TEXT, dbUser.getEmailAddr());
//need this to prompts email client only
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "gmail"));
}
else {
Toast.makeText(RecoverPassword.this,"Invalid Email",
Toast.LENGTH_LONG).show();
txtEmailAddress.setText("");
}
}
}
catch(Exception e) {
Toast.makeText(RecoverPassword.this,
e.getMessage(), Toast.LENGTH_LONG).show();
}
finally {
dbUser.close();
}
I want to use a log in system in Android with only the username. The code below works only for the first row ( For example my database has names : 1- Joseph 2 - Najib , if i input Joseph it works fine, but if i input Najib or some other value that does not exist in my DB the program apparently keeps looping and does not respond..How can I correct this code to return the message ( either the username being in the DB or an invalid username) accordingly? Do I have an error in the while statement?
public void checklogin() {
DatabaseHelper dbh = new DatabaseHelper(LoginActivity.this);
DatabaseAdapter dba = new DatabaseAdapter(LoginActivity.this);
db = dbh.getWritableDatabase();
TextView usernametry = (TextView) findViewById(R.id.usernametry);
String usertry = usernametry.getText().toString();
String[] allColumnsofuserstable = { dba.COLUMN_ID, dba.COLUMN_NAME,
dba.COLUMN_AGE, dba.COLUMN_GENDER, dba.COLUMN_WEIGHT,
dba.COLUMN_HEIGHT, dba.COLUMN_CALORIES };
Log.d("TAG", usertry);
Cursor mCursor = db.query(dba.TABLE_USERS,
new String[] { dba.COLUMN_NAME }, null, null, null, null, null,
mCursor.moveToNext();
while (!mCursor.isAfterLast()) {
String k = mCursor.getString(0);
if (k.equalsIgnoreCase(usertry)) {
Toast.makeText(LoginActivity.this,
"Logged in as " + mCursor.getString(0).toString(),
Toast.LENGTH_LONG).show();
mCursor.moveToNext();
} else
Toast.makeText(LoginActivity.this, "invalid username",
Toast.LENGTH_LONG).show();
}
mCursor.close();
dbh.close();
return;
}
The best would be to modify your query to look for string rather than getting all the results and loop through for a lookup.
Cursor mCursor = db.query(dba.TABLE_USERS,
new String[] { dba.COLUMN_NAME }, dba.COLUMN_NAME + "=?", new String[]{usertry},
null, null, null);
Your loop is broken because you only move the pointer in the cursor (mCursor.moveToNext();) in case that the username is found in the database. Cursor can't move after last item and while (!mCursor.isAfterLast()) never stops.
You need to make sure to always move the cursor. E.g. like so:
Cursor mCursor = db.query(dba.TABLE_USERS,
new String[] { dba.COLUMN_NAME }, null, null, null, null, null,
boolean loggedIn = false;
while (mCursor.moveToNext()) {
String k = mCursor.getString(0);
if (k.equalsIgnoreCase(usertry)) {
Toast.makeText(LoginActivity.this,
"Logged in as " + mCursor.getString(0).toString(),
Toast.LENGTH_LONG).show();
loggedIn = true;
break;
}
}
if (!loggedIn)
Toast.makeText(LoginActivity.this, "invalid username",
Toast.LENGTH_LONG).show();
Or you change your query (see #Waqas) to do the work for you (LIKE ? = equalsIgnoreCase, = ? = equals)
Cursor mCursor = db.query(dba.TABLE_USERS,
new String[] { dba.COLUMN_NAME }, dba.COLUMN_NAME + " LIKE ?", new String[]{usertry},
null, null, null);
if (mCursor.moveToFirst()) {
String k = mCursor.getString(0);
Toast.makeText(LoginActivity.this,
"Logged in as " + mCursor.getString(0).toString(),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "invalid username",
Toast.LENGTH_LONG).show();
}
I am trying do a sign up process. Where i have a method inside the DbAdaptor where i check if the username exists.
public Boolean checkUsername(String username) throws SQLException {
Cursor mCursor = db.query(TABLE_USERS, new String[] { ID,
KEY_NAME, KEY_USERNAME}, KEY_USERNAME + "="
+ username, null, null, null, null, null);
if (mCursor != null) {
return true;
}
return false;
}
From the Edit text i sent a value "harsha" as username to test it. but i am getting the following error
http://variable3.com/files/screenshots/2010-12-26_1215.png
the code inside the activity is this
DBAdapter db = new DBAdapter(RegisterActivity.this);
db.open();
if (db.checkUsername(username))
Toast.makeText(RegisterActivity.this, "Found",
Toast.LENGTH_LONG).show();
else
Toast.makeText(RegisterActivity.this, "Not Found",
Toast.LENGTH_LONG).show();
db.close();
you need to send the harsha as 'harsha' with single quote
public Boolean checkUsername(String username) throws SQLException {
Cursor mCursor = db.query(TABLE_USERS, new String[] { ID,
KEY_NAME, KEY_USERNAME}, KEY_USERNAME + "="
+"'"+username+"'", null, null, null, null, null);
if (mCursor != null) {
return true;
}
return false;
You're checking the cursor and not the moveToNext() result. The cursor is valid but does not return a result set.