how to compare data of two nodes in Firebase on Android - android

I want to make sure that time is not same.
It's an appointment booking app, so it cannot be the same.
public void clients()
{
String name=t2.getText().toString().trim();
String gender=t1.getText().toString().trim();
String barber=t4.getText().toString().trim();
String dt=t5.getText().toString().trim();
String concerng=t6.getText().toString().trim();
if(!TextUtils.isEmpty(name) || !TextUtils.isEmpty(gender) || !TextUtils.isEmpty(barber) || !TextUtils.isEmpty(dt) || !TextUtils.isEmpty(concerng))
{
String id=databaseReference.push().getKey();
client client=new client(id,name,gender,barber,dt,concerng);
databaseReference.child(id).setValue(client);
Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Something Went Wrong Please Check Again", Toast.LENGTH_SHORT).show();
}

To be able to compare two dates, you need to store the values of the cdatetime property as a timestamp and not as a String, as I see in your database now. Here you can find how to add and retrieve a timestamp from a Firebase database. If you follow those steps, you'll be able to compare very easy two long primitives.

Related

How to remove unwanted characters from SQLite insert in android studio

When I was passing data from my server via JSON. I have got this error.
android.database.sqlite.SQLiteException: near "rusitha": syntax error (code 1): , while compiling: INSERT INTO customer (id, name,nic,areaId,tp,address) VALUES ('583', 's.p.m.j.ilangasinghe.', '805250666v','18','0716090398','no.79,'rusitha',nuwarapara,maradankadawala.');
This is the code that I used.
for(i = 0;i<customerId.length();i++){
sqlite.execSQL("INSERT INTO customer (id, name,nic,areaId,tp,address) VALUES ('"+customerId.get(i).toString()+"', '"+customerName.get(i).toString()+"', '"+customerNIC.get(i).toString()+"','"+customerAreaId.get(i).toString()+"','"+customerTp.get(i).toString()+"','"+customerAddress.get(i).toString()+"');");
}
The issue is that 'no.79, doesn't have a closing single quote.This is because rushita is enclosed in single quotes and is preceeded by a comma. In short the address is not being escaped properly so the single quotes around rushita are confusing SQLite.
Your options are to either replace the single quotes in the address with 2 single quotes e.g.
customerAddress.get(i).toString().replace("'","''")
Or to let this be done on your behalf by using bindings by using the extended signature execSQL method. e.g
sqlite.execSQL("INSERT INTO customer (id, name,nic,areaId,tp,address) VALUES (?,?,?,?,?,?)"), newString[]{customerId.get(i).toString(),customerName.get(i).toString(),customerNIC.get(i).toString(),customerAreaId.get(i).toString(),customerTp.get(i).toString(),customerAddress.get(i).toString()});
binding would be recommended over the previous method.
An alternative would be to use the insert convenience method e.g
ContentValues cv = new ContentValues();
cv.put("id",customerId.get(i).toString());
cv.put("name",customerName.get(i).toString());
cv.put("nic",customerNIC.get(i).toString());
cv.put("areaId",customerAreaId.get(i).toString());
cv.put("tp",customerTp.get(i).toString());
cv.put("address",customerAddress.get(i).toString());
long insertedId = sqlite.insert("customer",null,cv);
This would be the most recommended way.
It builds the SQL on your behalf,
binds the values,
returns the rowid of the inserted row
and as it binds the values it, like the extended execSQL, protects against SQL injection.
Note the above code is in-principle code and has not been checked, tested or run, so there may be some small errors.
you can escape Character properly for the JSON data you got before using them:
// JSON Escape Utility
public static String crunchifyJSONEscapeUtil(String crunchifyJSON) {
final StringBuilder crunchifyNewJSON = new StringBuilder();
// StringCharacterIterator class iterates over the entire String
StringCharacterIterator iterator = new StringCharacterIterator(crunchifyJSON);
char myChar = iterator.current();
// DONE = \\uffff (not a character)
while (myChar != StringCharacterIterator.DONE) {
if (myChar == '\"') {
crunchifyNewJSON.append("\\\"");
} else if (myChar == '\t') {
crunchifyNewJSON.append("\\t");
} else if (myChar == '\f') {
crunchifyNewJSON.append("\\f");
} else if (myChar == '\n') {
crunchifyNewJSON.append("\\n");
} else if (myChar == '\r') {
crunchifyNewJSON.append("\\r");
} else if (myChar == '\\') {
crunchifyNewJSON.append("\\\\");
} else if (myChar == '/') {
crunchifyNewJSON.append("\\/");
} else if (myChar == '\b') {
crunchifyNewJSON.append("\\b");
} else {
// nothing matched - just as text as it is.
crunchifyNewJSON.append(myChar);
}
myChar = iterator.next();
}
return crunchifyNewJSON.toString();
}
code originally from this site

How to compare a String with a database table name?

I have a database table in my android app. I want to compare database table name with a particular string.
Here is my code
if(branchName == TABLE_NAME)
{
}
else
{
Toast.makeText(this,"table not available",Toast.LENGTH_LONG).show();
}
Here branchName is the string.TABLE_NAME is a static string and it is the name of the table.
Whenever I run this code, control goes to else part and shows the toast message.
Why? How can I fix that?
for comparing two string you must use equal or equalsIgnoreCase ... ...
if (branchName.equalsIgnoreCase(TABLE_NAME) ){
// do sth
}
else{
Toast.makeText(this,"table not available",Toast.LENGTH_LONG).show();
}
try this way.

Backendless - Clearing Tables

Does anyone know if it is possible to programmatically clear all of the data in a Backendless table at once? I found this article that shows how to remove individual objects one at a time but nothing on clearing the whole table at once: https://backendless.com/documentation/data/android/data_deleting_data_objects.htm
I figured out a way to do it but I don't know how efficient it is. Basically, I have a Class called LocalPhoneNum, which make up the objects that will be saved in my app table. The class contains a userID, name and phone num. I query the table to find a user with a specific email (right now there's just one user), then use the foundContacts variable in a loop to delete each object one by one.
String whereClause = "userEmailID = mark";
BackendlessDataQuery dataQuery = new BackendlessDataQuery();
dataQuery.setWhereClause( whereClause );
Backendless.Persistence.of(LocalPhoneNum.class).find(dataQuery, new AsyncCallback<BackendlessCollection<LocalPhoneNum>>(){
#Override
public void handleResponse( BackendlessCollection<LocalPhoneNum> foundContacts )
{
for (LocalPhoneNum temp : foundContacts.getData()){
Backendless.Persistence.of( LocalPhoneNum.class ).remove( temp, new AsyncCallback<Long>()
{
public void handleResponse( Long response )
{
Toast.makeText(getActivity(), "DELETED", Toast.LENGTH_LONG).show();
}
public void handleFault( BackendlessFault fault )
{
Toast.makeText(getActivity(), "NOT DELETED "+fault, Toast.LENGTH_LONG).show();
}
} );
}
Please let me know if there is a better solution or if this one is fine. Thank you!
Use the "bulk delete" operation with the 'where' query like "objectId is not null":
https://backendless.com/documentation/data/rest/data_deleting_data_objects.htm

android Edit text with special characters

I have a register form. i need to save the content in db. my data are saved successfully. but when i use space or some special characters my datas are not stored in db. what should i use to store the special characters and space in db,
if (Name.getText().toString().equals("")) {
Name.setError("Enter your name");
Name.requestFocus();
} else if (Dob.getText().toString().equals("")) {
Dob.setError("Enter Date of Birth");
Dob.requestFocus();
} else if (Collegeid.getText().toString().equals("")) {
Collegeid.setError("Enter your CollegeID");
Collegeid.requestFocus();
}
else {
String sname = Name.getText().toString();
String dob = Dob.getText().toString().trim();
String cid = Collegeid.getText().toString().trim();
}
Refer the screenshot above
Try to use [] brackets in the SQLite statements. It allow to you to add anything what you want.

Boolean Logical Syntax and MYSQL syntax Issue

Am not a learner to boolean expressions but this seems to be giving me a bit of an headache.
In my app when i search for a user,I am recieving certain values from my datase using this MYSQL statement.
SELECT `u3`.`username`,
CASE WHEN `u3`.`username` IS NULL THEN 'Not Existing'
ELSE 'Existing' END is_following
FROM `userinfo` `u3` WHERE `u3`.`username` LIKE '%".mysql_real_escape_string($data)."%' OR `u3`.`email` LIKE '%".mysql_real_escape_string($data)."%'
UNION
SELECT `u2`.`username`,
CASE WHEN `u2`.`username` IS NULL THEN 'Follow'
ELSE 'Following' END is_following
FROM
`userinfo` `u1` LEFT JOIN `followers` `f`
ON `u1`.`username` = `f`.`source_id`
LEFT JOIN `userinfo` `u2`
ON `f`.`destination_id` = `u2`.`username`
AND (`u2`.`username` LIKE '%".mysql_real_escape_string($data)."%' OR `u2`.`email` LIKE '%".mysql_real_escape_string($data)."%')
WHERE
`u1`.`username` = '$name'
Now the syntax above would return these set of values, a username and My own metadata. For example it would return
set of values 1: (davies and Existing)[if davies is in the userinfo table] AND (davies and Following)[if davies is following halex in the followers table]
OR
set of values 2: (null and Not Existing)[if davies is not in the userinfo table] AND (null and not followed)[davies does not exist]
OR
set of values 3: (davies and Existing)[if davies is in the userinfo table] AND (null and Not Following)[if davies is not following halex]
These are the set of values i recieve and i need an if statement to sieve through so i can display to my users this simple information
davies and Following OR davies and Follow[if davies is not following halex] OR User Does not Exist
Now am not sure if i should change the structure of my SOL statement or i could get a better way of handling this logic with if and else statements
This was the structure of my if else statement but it doesn't seem to work the way i want it to
if(username != null && metadata.contains("Existing"))//user exist
{
value = username;
//user exists but skip
}else
{
if(username != null)
{
map = new HashMap<String, String>();
map.put(TAG_USERNAME, value);
map.put(TAG_METADATA, metadata);
listvalue.add(map);
}else
{
//user does not exist
Log.i("search ", "user does not exist");
}
}
The codes above belongs to android.
Thanks any suggestion is appreciated. Thanks again in Advance.
What if you split your query into two parts? Querying for one set of information at a time will make things simpler and easier to debug.
I could imagine doing something that looks like this (in pseudo-code):
query = "SELECT username
FROM `userinfo` `u3`
WHERE `u3`.`username` LIKE '%".mysql_real_escape_string($data)."%'
OR `u3`.`email` LIKE '%".mysql_real_escape_string($data)."%'"
var result = db.execute(query);
// set to true if the above query returns at least one row
bool user_exists = (result.RowCount() > 0)
var username = (user_exists)? result.GetRow().GetField("username") : null;
if(user_exists)//user exist
{
value = username;
//user exists but skip
} // ....
(I've only replicated the functionality pertaining to your UNION's first SELECT statement; the logic associated with the second statement can be similarly rewritten.)

Categories

Resources