Android/Java : Is my code correct? - java

I am trying to make a simple login System. And This is the coed in database class. Is my Method correct? It should return true if both username and password are correct and false if either one of them is wrong or not in the database(not registered)? Is there any simpler way to code this method?
public boolean getAccount(String name, String password) {
int test = 0;
database = getReadableDatabase();
String sql = "SELECT * FROM tbl_account WHERE username='name' AND password='password'";
Cursor c = database.rawQuery(sql, null);
if (c.moveToFirst()) {
do {
if (c.getString(0).isEmpty()) {
test = 0;
}
else if (c.getString(0).isEmpty() == false) {
if (name.equals(c.getString(0))) {
if (c.getString(1).isEmpty()) {
test = 0;
}
else if (password.equals(c.getString(1))) {
test = 1;
}
}
}
} while (c.moveToNext());
}
if (test == 0) {
return false;
} else {
return true;
}
}

Best practice is to use ? placeholders with selection arguments where you can:
String sql = "SELECT * FROM tbl_account WHERE username = ? AND password = ?";
Cursor c = database.rawQuery(sql, new String[] {name, password});
This avoids problems where the arguments themselves contain characters such as quotes and apostophes that could otherwise break your constructed SQL string.

I think your sql should be:
String sql = "SELECT * FROM tbl_account WHERE username='" + name +
"' AND password='" + password + "'";
try this sql. hope it will help.

Related

how to check if your query is empty using java

I'm using a spring framework and the code I'm using won't work or check if the query is null, though I used a .isEmpty() method it doesn't mean that the query is empty. I wanted to make sure that my query is empty because a part of my code does invoke an id in which case I didn't even though its null so please help me T.T
public List<Object> searchEmployee(EmployeeSearchDto data) {
Session session = sessionFactory.openSession();
final String CRITERIA_EMPLOYEEID = "emp.employeeID =:id";
final String CRITERIA_EMPLOYEEID2 = "emp.employeeID LIKE:id";
final String CRITERIA_POSITION= "emp.positionID =:posID";
final String CRITERIA_DEPARTMENT="emp.departmentID =:deptID";
final String CRITERIA_WORKPLACE = "emp.workplaceID =:workID";
Boolean selected_dept = false;
Boolean selected_pos = false;
Boolean selected_work = false;
Boolean input_empID = false;
Boolean input_empName = false;
firstName = "";
middleName = "";
lastName = "";
completeName = "";
firstLastName = "";
List<String> criteria = new ArrayList<>();
List<Object> employees = null;
// checking the fields if all the fields is empty
try{
//one by one check the select field
String query = "Select"
+ " emp.employeeID,"
+"emp.firstName,"
+"emp.middleName,"
+"emp.lastName,"
+"pos.positionName,"
+"dept.deptName,"
+"work.workplaceName"
+"from Employee emp "
+ "INNER JOIN Department dept "
+ "ON emp.departmentID = dept.deptID "
+ "INNER JOIN Position pos "
+ "ON emp.positionID = pos.positionID "
+ "INNER JOIN Workplace work "
+ "ON emp.workplaceID = work.workplaceID ";
if(!data.isEmpty()) {
query = query.concat("WHERE ");
if(data.getEmployeeID()!="" && data.getEmployeeID()!=null) {
criteria.add(CRITERIA_EMPLOYEEID2);
System.out.println("Employee IDs");
input_empID = true;
}
if(data.getEmployeeName()!="" && data.getEmployeeName()!=null){
criteria.add(nameCriteriaHelper(data.getEmployeeName()));
System.out.println("Employee Name AKOOO");
input_empName = true;
}
if(data.getDepartmentID()!=0) {
criteria.add(CRITERIA_DEPARTMENT);
System.out.println("Dept ID ");
selected_dept = true;
}
if(data.getPositionID()!=0) {
criteria.add(CRITERIA_POSITION);
System.out.println("POS ID ");
selected_pos = true;
}
if(data.getWorkplaceID()!=0) {
criteria.add(CRITERIA_WORKPLACE);
selected_work = true;
}
query = query.concat(String.join(" OR ", criteria));
}
query = query.concat(" ORDER BY emp.joinDate DESC");
System.out.println("QUERY: " + query);
Query q = session.createQuery(query);
if(input_empID) {
q.setParameter("id", "%" + data.getEmployeeID() + "%");
}
if(input_empName) {
if(searchbyOne)
q.setParameter("inputName", "%" + data.getEmployeeName() + "%");
if(searchbyFandL)
q.setParameter("firstLastName", "%" +firstLastName+ "%");
if(searchbyCompName)
q.setParameter("completeName", "%" +completeName+ "%");
}
if(selected_dept) {
q.setParameter("deptID", data.getDepartmentID());
}
if(selected_pos) {
q.setParameter("posID", data.getPositionID());
}
if(selected_work) {
q.setParameter("workID", data.getWorkplaceID());
}
employees = (List<Object>) q.list();
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
return employees;
}
public String nameCriteriaHelper(String name) {
searchbyOne = false;
searchbyFandL = false;
searchbyCompName = false;
final String noOfTokens_1 = "CONCAT(emp.lastName,' ',emp.firstName, ' ',emp.middleName) LIKE :inputName";
final String noOfTokens_2 = "(CONCAT(emp.lastName, ' ', emp.firstName) LIKE :firstLastName "
+ "OR CONCAT(emp.firstName, ' ', emp.lastName) LIKE :firstLastName)";
final String noOfTokens_3 = "CONCAT(emp.lastName,' ',emp.firstName, ' ',emp.middleName) LIKE :completeName";
StringTokenizer stringTokenizer = new StringTokenizer(name);
int no_of_tokens = stringTokenizer.countTokens();
switch(no_of_tokens) {
case 1: searchbyOne = true;
return noOfTokens_1;
case 2: firstName = stringTokenizer.nextToken();
lastName = stringTokenizer.nextToken();
firstLastName = lastName + " " + firstName;
searchbyFandL = true;
return noOfTokens_2;
default: int counter = 0;
while( counter < (no_of_tokens - 2)) {
firstName = firstName.concat(stringTokenizer.nextToken() + " ");
counter++;
}
firstName = stringTokenizer.nextToken();
middleName = stringTokenizer.nextToken();
lastName = stringTokenizer.nextToken();
completeName = lastName + " " + firstName + " " + middleName;
searchbyCompName = true;
return noOfTokens_3;
}
You're using wrong order and wrong function to compare string:
Replace:
data.getEmployeeID()!="" && data.getEmployeeID()!=null
With
data.getEmployeeID() != null && !data.getEmployeeID().equals("")
Comparing string must use equals(). And check for null should be done first, before accessing the equals method
You should correct other conditions as above too.
Actually, the logic that Mr. Nguyễn provided here is faulty. An object or variable cannot both be null and initialized to a default value (such as foo == "") at the same time.
At the time of the logic check, if the String is in fact null, the second half of the logic statement will engage, checking to see if the String is equal to "", which will throw a null pointer exception. Instead of checking for both at the same time, check for one and then check for the other like so:
//since two logic checks are being performed,
//it is advantageous to put the data from the query
//into memory so you don't have to get the
//same result twice
String foo = data.getEmployeeID();
if (foo != null)
{
if (!(foo.equals("")))
{
//the result is neither null or empty
}
else
{
//the result is not null but it is empty
}
}
else
{
//the result is null
}

Trying to hide null values from being printed

How do I hide null values from being printed? I have one Products table which has 5 columns. ID, Dairy, Fruit, Vegetables, Grains, and Protein.
When I search for dairy it brings up null values. Whats the best way to hide it?
public String dbToStringDairy() {
SQLiteDatabase db = getWritableDatabase();
String dbStringDairy = "";
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex(COLUMN_ID)) != null) {
dbStringDairy += " ";
dbStringDairy += c.getString(c.getColumnIndex(COLUMN_PRODUCT_DAIRY));
dbStringDairy += "\n";
}
c.moveToNext();
}
db.close();
return dbStringDairy;
}
The Simplest way to return something else instead of null, using an if else statement to check if the return result is null or not, if it is null store something else so that the program wont return and print null.
Here some simple example:
public String dbToStringDairy()
{
SQLiteDatabase db = getWritableDatabase();
String dbStringDairy = "";
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast())
{
if(c.getString(c.getColumnIndex(COLUMN_ID))!=null)
{
dbStringDairy += " ";
dbStringDairy += c.getString(c.getColumnIndex(COLUMN_PRODUCT_DAIRY));
dbStringDairy += "\n";
}
c.moveToNext();
}
db.close();
//Replace the `null` into other useful information
if(dbStringDairy==null){
dbStringDairy="No Results";
}
return dbStringDairy;
}
There are a lot of way to ensure your program won't print out null value. This method perform in the dbToStringDairy(), there is also way to do it during your Print Implementation.
Anywhere, hope this simple solution could help.

JSP - How to write a valid search form

I have a problem with a search form in a JSP project. In particular an user can subscribe to an event and the admin must be able to search all the members of that event.
I write a form like this:
out.println("<fieldset><legend>Search</legend><form action=\"cercaIscritti.jsp\" method=\"post\">"
+ "Name: <input name=\"name\" type=\"text\"><br>Surname: <input name=\"surname\" type=\"text\"><br>"
+ "Belonging: <input name=\"belonging\" type=\"text\"><br>Countr: <input name=\"country\" type=\"text\"><br>"
+ "<input type=\"submit\" value=\"Cerca\"></fieldset></form>");
(If it isn't readable: there are four <input>, one for each column in the table user and a <input> for submit).
I would like all the fields to be optional so that the admin can fill what it wants, but how do I build the query?
I tried something like this :
public ResultSet searchSubs(String name, String surname, String belonging, String country) {
try {
boolean n = false, s = false, b = false, c = false;
String query = "SELECT * FROM user WHERE ";
if (!isEmpty(name)) {
query += "firstName = ?";
n = true;
}
if (!isEmpty(surname)) {
if (n) {
query += " AND lastName = ?";
} else {
query += "lastName = ?";
}
s = true;
}
if (!isEmpty(belonging)) {
if (n || s) {
query += " AND belonging = ?";
} else {
query += "belonging = ?";
}
b = true;
}//and go on
But how can I add the values with the PreparedStatement? Is this the correct way? If it's not, how can I do something like that?
The booleans are there in the middle only for test, I thought I would use them in some way but I do not know how.
Here is a way you can follow to search with multiples values :
public ResultSet searchSubs(String name, String surname, String belonging, String country){
try {
String query = "SELECT * FROM user WHERE 1=1";
//---------------------------------------^^^
int index = 1;
if (!name.isEmpty()) {
query += " AND firstName = ?";
}
if (!surname.isEmpty()) {
query += " AND surname = ?";
}
if (!belonging.isEmpty()) {
query += " AND belonging = ?";
}
if (!country.isEmpty()) {
query += " AND country = ?";
}
PreparedStatement ps = connection.prepareStatement(query);
if (!name.isEmpty()) {
ps.setString(index++, name);
}
if (!surname.isEmpty()) {
ps.setString(index++, surname);
}
if (!belonging.isEmpty()) {
ps.setString(index++, belonging);
}
if (!country.isEmpty()) {
ps.setString(index++, country);
}
ResultSet rs = ps.executeQuery();
//...
The idea is simple :
In the Where clause use 1=1 to not get an error if the user not enter any value(in this case your query is SELECT * FROM user WHERE 1=1 and it will return every thing)
The first part if to fill the query with the non empty fields
The second if to fill the prepared statement with the right values.
finally execute the prepared statement and get the results.

Java SQLite cannot find column when column exists

I'm working a project(Full source code here) and as part of the project, I've created a Database class to make interfacing with the SQLite database easier and cleaner. I'm currently attempting to write a method that will use SELECT along with the given parameters to return a string array containing the results. The issue that I'm having is that when I run the program to test it, Eclipse throws java.sql.SQLException: no such column: 'MOVES'
But, when I look at the database in a GUI, it clearly shows the column that I'm trying to access, and when I execute just the sql in the same program, it's able to return the data.
This is the method that I've written so far:
public String[] get(String what, String table, String[] conds) {
try {
if (what.equals("*")) {
throw new Exception("'*' selector not supported");
}
c.setAutoCommit(false);
stmt = c.createStatement();
String sql = "SELECT " + what.toUpperCase() + " FROM " + table.toUpperCase();
if (conds.length > 0) {
sql += " where ";
for (int i = 0; i < conds.length; i++) {
if (i == conds.length - 1) {
sql += conds[i];
break;
}
sql += conds[i] + " AND ";
}
}
sql += ";";
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
if (table.toUpperCase().equals("DEX")) {
String id = "";//rs.getInt("id") + "";
String species = rs.getString("species");
String type1 = rs.getString("type1");
String type2 = rs.getString("type2");
String hp = rs.getInt("hp") + "";
String atk = rs.getInt("atk") + "";
String def = rs.getInt("def") + "";
String spa = rs.getInt("spa") + "";
String spd = rs.getInt("spd") + "";
String spe = rs.getInt("spe") + "";
String ab1 = rs.getString("ab1");
String ab2 = rs.getString("ab2");
String hab = rs.getString("hab");
String weight = rs.getString("weight");
return new String[] { id, species, type1, type2, hp, atk, def, spa, spd, spe, ab1, ab2, hab,
weight };
} else if (table.toUpperCase().equals("MOVES")) {
String name = rs.getString("NAME");
String flags = rs.getString("FLAGS");
String type = rs.getString("TYPE");
String full = rs.getString("LONG");
String abbr = rs.getString("SHORT");
String acc = rs.getInt("ACCURACY") + "";
String base = rs.getInt("BASE") + "";
String category = rs.getInt("CATEGORY") + "";
String pp = rs.getInt("PP") + "";
String priority = rs.getInt("PRIORITY") + "";
String viable = rs.getInt("VIABLE") + "";
return new String[] { name, acc, base, category, pp, priority, flags, type, full, abbr, viable };
} else if (table.toUpperCase().equals("LEARNSETS")) {
String species = rs.getString("SPECIES");
String moves = rs.getString("MOVES");
return new String[] { species, moves };
} else {
throw new Exception("Table not found");
}
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return null;
}
Screencaps:
UPDATE:
I wanted to double-check that the database viewer I was using wasn't messed up, so I opened up the terminal and ran
sqlite3 git/Pokemon/data.db
pragma table_info(MOVES);
Receiving this in response:
0|SPECIES|TEXT|0||0
1|MOVES|TEXT|0||0
Finally figured it out, for anybody else having this issue, make sure that the data you're trying to get from the result set is actually included in it. For example, if I call SELECT SPECIES FROM DEX; the result set won't contain other things like id, type, or any of those other columns, it will ONLY contain the species column. I'm not sure why it took me so long to figure this out, but there you have it.

SQLite Check if column exist or not

I want to check columns (not value) at agregasi table, if columns exist do something, but if columns does not exist show/print message 'Column does not exist'.
I could run code below while columns exist:
String keywords1={'pesawat','terbang'};
String sql1 = "SELECT " + keywords + " FROM agregasi"; //columns exist at agregasi table
Cursor c1 = myDbHelper.rawQuery(sql1, null);
if (c1.moveToFirst()) {
// i can do something (no problem)
}
But i have problem when columns name i change on purpose (to check). What should i do to print error message (in android/java way)?
**String keywords2={'psawat','terang'};**
String sql2 = "SELECT " + keywords + " FROM agregasi"; //columns does not exist at table
Cursor c2 = myDbHelper.rawQuery(sql2, null);
// what should i do get error message and show/print using toast
You're looking for getColumnIndex(String columnName).
int index = c2.getColumnIndex("someColumnName");
if (index == -1) {
// Column doesn't exist
} else {
...
}
Here's a general method you can use to check whether a particular column exists in a particular table:
public boolean isColumnExists(SQLiteDatabase sqliteDatabase,
String tableName,
String columnToFind) {
Cursor cursor = null;
try {
cursor = sqLiteDatabase.rawQuery(
"PRAGMA table_info(" + tableName + ")",
null
);
int nameColumnIndex = cursor.getColumnIndexOrThrow("name");
while (cursor.moveToNext()) {
String name = cursor.getString(nameColumnIndex);
if (name.equals(columnToFind)) {
return true;
}
}
return false;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Try this it works fine :)
Cursor res = db.rawQuery("PRAGMA table_info("+tableName+")",null);
int value = res.getColumnIndex(fieldName);

Categories

Resources