I want to make a login option by verifying if the username and the password contain the same id. The problem is I don't know how to get the id value based on their column value (for example - player or 1234). The result i want to get is to compare between their id values so i can know if the username and the password are correct.
You could create a method in your SQLiteOpenhelper subclass to return true or false if the username and the password match e.g.
public boolean ifValidUserLogin(String username, String password) {
SQLitedarabase db = this.getWriteableDatabase();
Cursor csr = db.query(YOUR_TABLE_NAME,
null, // null equates to all columns
"username" + "=? AND " +
"password" + "=?", // the WHERE clause less WHERE
new String[]{username,password}, // the arguments that replace ?'s
null,null,null
};
boolean rv = (csr.getCount > 0);
csr.close();
return rv;
}
You then invoke this, probably in an activity, which would be along the lines of :-
MySQLiteOpenHelper myhlpr = new MySQLiteOpenhelper(this); // parms might be different
if (myhlpr.ifValidUserLogin(username_from_ui,password_from_ui)) {
// username and password match so do what you need to do here!
} else {
// mismatch so do what you need to do here!.
}
Notes
the call to the SQLiteDatabase query method equates to using the SQL SELECT * FROM table WHERE username=?????? AND password=??????? (??? denoting user input values)
YOUR_TABLE_NAME should be replaced by the name of the table as a String.
You may wish to have a look at query
If you wanted the id rather then you could use :-
public long getValidUserId(String username, String password) {
long rv = -1; // default to mismatch and thus no id (could use 0)
SQLitedarabase db = this.getWriteableDatabase();
Cursor csr = db.query(YOUR_TABLE_NAME,
null, // null equates to all columns
"username" + "=? AND " +
"password" + "=?", // the WHERE clause less WHERE
new String[]{username,password}, // the arguments that replace ?'s
null,null,null
};
if (csr.moveToFirst) {
rv = csr.getLong(csr.getColumnIndex("YOUR_ID_COLUMNNAME"));
}
csr.close();
return rv;
}
Obviously you'd call getValidUserId and check for a value > -1 for a match.
you can use query like :
"SELECT * FROM " + TABLE_EMP
+ " WHERE " + KEY_USERNAME + " = '" + userName + "'"
assuming your username must be unique to get the unique record.If you want more specific then you can add a condition for password too.
Why dont you simply check if your password match your username and forget about the id?
Related
I'm trying Official Documentation for Android this article. Creating Database, Table and inserting data is working fine. But I'm unable to get data from database. Here is the piece of code to retrieve data from table.
public Person searchDataInDB(String personCellString) {
SQLiteDatabase db = getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
PersonTable.COLUMN_NAME_ID,
PersonTable.COLUMN_NAME_NAME,
PersonTable.COLUMN_NAME_CELL_NO,
PersonTable.COLUMN_NAME_ADDRESS
};
// Filter results WHERE "cell#" = 'Person Cell #'
String selection = SQLiteDBHelper.PersonTable.COLUMN_NAME_CELL_NO + " = ?";
String[] selectionArgs = {"'" + personCellString + "'"};
// How you want the results sorted in the resulting Cursor
// String sortOrder = SQLiteDBHelper.PersonTable.COLUMN_NAME_ID + " DESC";
Cursor cursor = db.query(
SQLiteDBHelper.PersonTable.TABLE_NAME, // The table to query
null, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
String [] names = cursor.getColumnNames();
Log.e("SQLiteDB", "cursorCount = " + cursor.getCount() + ", cursorColumnCount = " + cursor.getColumnCount() + ", Column = " + names[0]);
Person person = null;
while (cursor.moveToNext()) {
int id = (int) cursor.getLong(
cursor.getColumnIndexOrThrow(PersonTable.COLUMN_NAME_ID));
Log.e("SQLiteDB", "moveToNext id = " + id);
String name = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_NAME));
Log.e("SQLiteDB", "moveToNext name = " + name);
String cellNo = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_CELL_NO));
Log.e("SQLiteDB", "moveToNext cell = " + cellNo);
String address = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_ADDRESS));
Log.e("SQLiteDB", "moveToNext address = " + address);
person = new Person(id, name, cellNo, address);
}
cursor.close();
return person;
}
It seems like my app does not enter in while loop i.e. while(cursor.moveToNext() So this method always returns initial value of person which is null. As a result, the first condition is always true from below code
Person person = dbHelper.searchDataInDB(personCellString);
if (person == null) {
Toast.makeText(mContext, "no such record exists in database!", Toast.LENGTH_LONG).show();
} else {
String personDetails = "Name = " + person.getName()
+ "Cell Number = " + person.getCellNumber()
+ "Address = " + person.getAddress();
personDetailsTV.setText(personDetails);
}
I'm using DB Browser for SQLite so I can see the records are successfully adding in the database.
What should I do with the above code to make it work?
What you are doing with this:
String[] selectionArgs = {"'" + personCellString + "'"};
is searching for the string value of personCellString enclosed inside single quotes and not for the actual value of the string personCellString.
Remove the single quotes:
String[] selectionArgs = {personCellString};
You don't have to worry about the string representation of personCellString in the final sql statement that will be constructed and executed which will contain them without explicitly setting them.
I need to get list of id, first name, last name, number(or numbers), email, website of an android device contacts. I know by getting id I can query about phone numbers this is not a big deal. But I don't know how I should make query to get all these columns correctly.
I supposed for names I need ContactsContract.CommonDataKinds.StructuredName for email I need ContactsContract.CommonDataKinds.Email.ADDRESS ,for id Contacts and for website ContactsContract.CommonDataKinds.Website.URL.
My code returns strange values like a single digit number for GIVEN_NAME, null for FAMILY_NAME, one of contact numbers for Email.ADDRESS.
However I think the problem is query URI, which one should I use?
ContentResolver cr = getActivity().getContentResolver();
String[] projection = new String[] {
Contacts._ID,
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
ContactsContract.CommonDataKinds.Website.URL,
ContactsContract.CommonDataKinds.Email.ADDRESS};
Cursor nameCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
null,
null,
null);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String email = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
Integer id= nameCur.getInt(nameCur.getColumnIndex(Contacts._ID));
String website = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
//do some work with strings...
}
The problem is that all the sub-tables you're trying to access (Email, Phone, Website, etc.) are actually all stored in a single big table called Data.
All those sub-tables share the same fields Data1-Data15, so by querying on the Phone.CONTENT_URI table, you're only getting Phone info, that's why trying to access StructuredName.GIVEN_NAME on the result is wrong.
Instead you query over the Data.CONTENT_URI table that contains all info, and you differentiate between rows of different data type via the value at Data.MIMETYPE.
See docs here: https://developer.android.com/reference/android/provider/ContactsContract.Data
I'm not sure if you needed the contact's info for all contacts on the device, or for a specific one.
Here's the code to get info of a single contact (you need to assign value to the contactId variable there)
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3};
// query only emails/phones/events
String selection = Data.CONTACT_ID + "=" + contactId + " AND " +
Data.MIMETYPE + " IN ('" + StructuredName.CONTENT_ITEM_TYPE + "', '" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE"', '" + Website.CONTENT_ITEM_TYPE + "')";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1); // full name
String mime = cur.getString(2); // type of data (phone / birthday / email)
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
String kind = "unknown";
switch (mime) {
case StructuredName.CONTENT_ITEM_TYPE:
String firstName = cur.getString(4);
String lastName = cur.getString(5);
Log.d(TAG, "got name: " + data + " - " + firstName + " " + lastName);
break;
case Phone.CONTENT_ITEM_TYPE:
Log.d(TAG, "got phone: " + data);
break;
case Email.CONTENT_ITEM_TYPE:
Log.d(TAG, "got email: " + data);
break;
case Website.CONTENT_ITEM_TYPE:
Log.d(TAG, "got website: " + data);
break;
}
}
cur.close();
To convert it to run over ALL contacts, simply remove the Data.CONTACT_ID + "=" + contactId part from the selection, and then you'll need to create some HashMap from contactId to an object containing the info about that contact (use the id variable for the key)
here is my solution:
first we need a query for getting all contact id in the table of "raw_contacts"
List<Integer> ret = new ArrayList<Integer>();
ContentResolver contentResolver = getActivity().getContentResolver();
// Row contacts content uri( access raw_contacts table. ).
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI;
// Return _id column in contacts raw_contacts table.
String queryColumnArr[] = {ContactsContract.RawContacts._ID};
// Query raw_contacts table and return raw_contacts table _id.
Cursor cursor = contentResolver.query(rawContactUri, queryColumnArr, null, null, null);
then we query table "data" for extra information for each contact id:
// Data content uri (access data table. )
Uri dataContentUri = ContactsContract.Data.CONTENT_URI;
// Build query columns name array.
List<String> queryColumnList = new ArrayList<String>();
// ContactsContract.Data.CONTACT_ID = "contact_id";
queryColumnList.add(ContactsContract.Data.CONTACT_ID);
// ContactsContract.Data.MIMETYPE = "mimetype";
queryColumnList.add(ContactsContract.Data.MIMETYPE);
queryColumnList.add(ContactsContract.Data.DATA1);
queryColumnList.add(ContactsContract.Data.DATA2);
queryColumnList.add(ContactsContract.Data.DATA3);
queryColumnList.add(ContactsContract.Data.DATA4);
queryColumnList.add(ContactsContract.Data.DATA5);
queryColumnList.add(ContactsContract.Data.DATA6);
queryColumnList.add(ContactsContract.Data.DATA7);
queryColumnList.add(ContactsContract.Data.DATA8);
queryColumnList.add(ContactsContract.Data.DATA9);
queryColumnList.add(ContactsContract.Data.DATA10);
queryColumnList.add(ContactsContract.Data.DATA11);
queryColumnList.add(ContactsContract.Data.DATA12);
queryColumnList.add(ContactsContract.Data.DATA13);
queryColumnList.add(ContactsContract.Data.DATA14);
queryColumnList.add(ContactsContract.Data.DATA15);
// Translate column name list to array.
String queryColumnArr[] = queryColumnList.toArray(new String[queryColumnList.size()]);
// Build query condition string. Query rows by contact id.
StringBuffer whereClauseBuf = new StringBuffer();
whereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID);
whereClauseBuf.append("=");
whereClauseBuf.append(rawContactId);
// Query data table and return related contact data.
Cursor cursor = contentResolver.query(dataContentUri, queryColumnArr, whereClauseBuf.toString(), null, null);
last cursor contains all the data of any contact and for get that data we need switch case:
String mimeType =cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
switch (mimeType) {
// Get email data.
case ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE:
// Email.ADDRESS == data1
String emailAddress = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
int emailType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
data.setDataType(emailType);
data.setDataValue(emailAddress);
ret1.add(data);
con.setEmailList(ret1);
break;
// Get organization data.
case ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE:
// Organization.COMPANY == data1
String company = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
con.setCompany(company);
break;
// Get phone number.
case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
// Phone.NUMBER == data1
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Phone.TYPE == data2
int phoneTypeInt = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
data.setDataType(phoneTypeInt);
data.setDataValue(phoneNumber);
ret1.add(data);
con.addPhoneList(ret1);
break;
// Get display name.
case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
// StructuredName.DISPLAY_NAME == data1
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
// StructuredName.GIVEN_NAME == data2
String givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
// StructuredName.FAMILY_NAME == data3
String familyName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
ret.add("Display Name : " + displayName);
ret.add("Given Name : " + givenName);
ret.add("Family Name : " + familyName);
break;
// Get website.
case ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE:
// Website.URL == data1
String websiteUrl = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
// Website.TYPE == data2
int websiteTypeInt = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.TYPE));
String websiteTypeStr = getEmailTypeString(websiteTypeInt);
ret.add("Website Url : " + websiteUrl);
ret.add("Website Type Integer : " + websiteTypeInt);
ret.add("Website Type String : " + websiteTypeStr);
break;
}
this is not my compelete code just for getting idea. hope this will help someone!
I am working on SQLite database. I have retrieved values using select query.
Now I have to save these values in variable for comparison with user entered email ans password.
How can I save it in a variable in Login.java
Query(MYSQLiteHelper.java)
public user_reg getemail(String ema) {
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_USERREGISTRATION, // a. table
COLUMNS, // b. column names
" email = ?", // c. selections
new String[] {
String.valueOf(ema)
}, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
user_reg user = new user_reg();
user.setEmail(cursor.getString(3));
user.setPassword(cursor.getString(4));
Log.d("getUser(" + ema + ")", user.toString());
// 5. return book
return user;
}
Login.java
MySQLiteHelper db = new MySQLiteHelper(getApplicationContext());
emailval= email.getText().toString();
db.getemail(emailval);
You can get data from cursor by this way :
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
user_reg user = new user_reg();
// I am expecting email and password as column name
user.setEmail(cursor.getString(cursor.getColumnIndex("email")));
user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
Log.d("getUser(" + ema + ")", user.toString());
// 5. return book
return user;
You need to check like this for your username if exist or not ..
if(ema.equals(cursor.getString(3))){
user.setEmail(cursor.getString(3));
user.setPassword(cursor.getString(4));
} else{
.....
}
I am making a app that incorporates login/register functionalities and I'm making a issue that I have been trying to solve.
When a user logins and the login is successful, I'd like to use the email that they signed in with to pass to the next activity using Intent (I checked that the email is in fact getting passed by displaying what is being passed through the intent) and then passing that email to a function in the Dbhelper that uses that email to look for the name of the person that signed in then displaying "Welcome (name of person)" in the current activity but I keep getting a null returned in the function which ultimately leads to the app crashing.
Here is where I'm calling the function in the activity where I want to display the name.
if(!session.loggedIn())
{
Logout();
}
else
{
Intent in = getIntent();
String email = in.getStringExtra("email");
Name.setText("Welcome " + db.findName(email));
}
And this is the function in my DbHelper.java where I'm looking for the name with a query and such.
public String findName(String user_email)
{
String query = "SELECT " + COLUMN_NAME + " FROM " + USER_TABLE + " WHERE " + COLUMN_EMAIL + " = " + "'" + user_email + "'";
SQLiteDatabase db = this.getWritableDatabase();
//reads for database
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
if(c.getCount() > 0) // if cursor is not empty
{
String n = c.getString(0);
return n;
}
else
{
return null;
}
}
As you can see, it's returning null. And yes there is entries in the database already. Also, I tried just passing the email to the function and returning what was passed and it still gave me an error.
Normally, to check for a value in a text column, you do not use the equal = sign, but rather WHERE Column LIKE '%text%'. Also, when saving to a database you should escape and "sanitize" strings. If you did this, then you should also be doing the same process when looking for them, else you won't find them.
I am telling you this since, even if you are sure there are entries in your table, the result of the query may be empty. You could just debug by printing the result of the c.getCount() call or something.
I have taken String value from a EditText and set it inside SELECT QUERY after WHERE condition
As
TextView tv = (TextView) findViewById(R.id.textView3);
EditTextet2 et = (EditText) findViewById(R.id.editText1);
String name = et.getText().toString();
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = '"+name+"'", null);
c.moveToNext();
tv.setText(c.getString(c.getColumnIndex("email")));
But it doesn't work. Any suggestions?
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst() like #thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
Try using the following statement:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = ?", new String[] {name});
Android requires that WHERE clauses compare to a ?, and you then specify an equal number of ? in the second parameter of the query (where you currently have null).
And as Nambari mentioned, you should use c.moveToFirst() rather than c.moveToNext()
Also, could there be quotations in name? That could screw things up as well.
Here is the below code.
String areaTyp = "SELECT " +AREA_TYPE + " FROM "
+ AREA_TYPE_TABLE + " where `" + TYPE + "`="
+ id;
where id is the condition on which result will be displayed.
public User searchUser(String name) {
User u = new User();
SQLiteDatabase db = this.getWritableDatabase(); //get the database that was created in this instance
Cursor c = db.rawQuery("select * from " + TABLE_NAME_User+" where username =?", new String[]{name});
if (c.moveToLast()) {
u.setUsername(c.getString(1));
u.setEmail(c.getString(1));
u.setImgUrl(c.getString(2));
u.setScoreEng(c.getString(3));
u.setScoreFr(c.getString(4));
u.setScoreSpan(c.getString(5));
u.setScoreGer(c.getString(6));
u.setLevelFr(c.getString(7));
u.setLevelEng(c.getString(8));
u.setLevelSpan(c.getString(9));
u.setLevelGer(c.getString(10));
return u;
}else {
Log.e("error not found", "user can't be found or database empty");
return u;
}
}
this is my code to select one user and one only
so you initiate an empty object of your class then
you call your writable Database
use a cursor in case there many and you need one
here you have a choice Use : 1-
if (c.moveToLast()) { } //it return the last element in that cursor
or Use : 2-
if(c.moveToFirst()) { } //return the first object in the cursor
and don't forget in case the database is empty you'll have to deal with that in my case i just return an empty object
Good Luck
Detailed answer:
String[] selectionArgs = new String[]{name};
Cursor c = db.rawQuery(
"SELECT * FROM " + tabl1 +
" WHERE " + name + " = ? ", selectionArgs
);
selectionArgs : this takes the 'name' you desire to compare with, as argrument.
Here note "A Cursor object, which is positioned before the first entry of the table you refer to".
So,to move to first entry :
c.moveToFirst();
getColumnIndex(String ColumnName) : this returns the zero-based column index for the given column name.
tv.setText(c.getString(c.getColumnIndex("email")));
In case, you want to go searching through multiple rows for a given name under 'name' column then use loop as below:
if (cursor.moveToFirst()){
do{
////go traversing through loops
}while(cursor.moveToNext());
}
This should solve the problem.