preventing duplicate table inserts using jdo in android connected appengine - android

I would like to know how to prevent duplicate inserts when doing an RPC call from an Android client connected to app engine. Below is my code and what I tried at the back-end but when I do this I get an "Internal Server Error".
public void createentity(userentity e) {
PersistenceManager pm = PMF.get().getPersistenceManager();
//to go through the records and and check for duplicates
Query q = pm.newQuery("select from" + userentity.class + "where Country=='" + e.getCCNumber() + "'");
List < userentity > s = (List < userentity > ) q.execute();
//if the size is equal to to null means there is no duplicate
if (s.size() == 0) {
//insert the value
try {
pm.makePersistent(e);
} finally {
pm.close();
}
}
}

A couple of potential issues I see. First you should also be checking that your list isn't null. If it's null, your attempt to access the size will result in a null pointer exception. Secondly, in your query string remove the double equals. You only need single equals there. And secondly, add a spaces at the end and beginnings of your string literals. You're creating an invalid string. For instance, "select from ". And lastly, you shouldn't need to wrap the e.getCCNumber() in string literals.
Query q = pm.newQuery("select from " + userentity.class + " where Country= " + e.getCCNumber());

Related

How can I define the parameters of a query using string values?

The query below should have only returned the numbers 0 through 8. However, the result are 0 thru 87. and 88 thru 99 are not shown. The next numbers shown are 100 thru 799. 800 thru 999 are not shown. So I see a pattern here, and it is that if the first number is within the range specified it is returned.
public Cursor getList(String user) {
String zero = "0";
String query = ("SELECT * FROM flavors WHERE inventory >= "+zero+" AND inventory <= "+user);
return mDb.rawQuery(query, null);
How can I keep the expected results withing the query parameters?
Thanks for all your efforts.
EDIT
For anyone that are looking for an answer as I was. Here is the final working statement.
Thanks to #FAT I was able to learn more about the sql query process from the links that where provided. Googling is an art it seems. I changed my code to meet my needs as follows.
public Cursor getList(String user) {
String zero = "0";
String query = ("SELECT * FROM flavors WHERE inventory != '' AND (cast(inventory as real)) >= " + zero + " AND (cast(inventory as real)) <= " + user);
return mDb.rawQuery(query, null);
}
The "cast" was the key to getting the string to be used to compare the two numbers. I also learned that you can exclude all null items. By adding "!= '', only the items that had an entry where returned in accordance with the statement. This even works for decimal numbers such as 5.5 or .5 etc.
You can't compare String value using >= or <=. Try using int value instead of string. For this case your column inventory should be int type.
Try this:
public Cursor getList(int user) {
int zero = 0;
String query = ("SELECT * FROM flavors WHERE inventory >= " + zero + " AND inventory <= " + user);
return mDb.rawQuery(query, null);
}
You can use BETWEEN like the following:
SELECT * FROM flavors WHERE inventory BETWEEN X AND Y

Delete the last row in a table SQLite android

I am developing an android app where I want to delete the last row in one of my database table. I have tried the code below, but its throwing a syntax error.
public void deletelatestprofilefromsystemsettings()
{
String maxid = System_id + "="+"SELECT MAX ("+System_id+") FROM" +TABLE_SYSTEM_SETTINGS;
getWritableDatabase().delete(TABLE_SYSTEM_SETTINGS, maxid ,null);
}
Please help! Thanks!
You are lacking a space after the FROM, and subqueries must be written in parentheses:
String maxid = System_id + "=" +
"(SELECT MAX("+System_id+") FROM " + TABLE_SYSTEM_SETTINGS + ")";
You are trying to execute a DELETE with a SELECT in the same query. AFAIK you shouldn't do it. You have to execute the SELECT query first, in order to retrieve the desired id, then execute the deletion. In other words, execute Cursor c = getWritableDatabase().query(), read the id from the cursor, then use it in getWritableDatabase().delete().
Also, add a space after ") FROM", so it becomes ") FROM " in order to avoid a syntax error.

Android: Having trouble updating a row in a database after determining what row I need to update

I have a table that contains a list of devices with catagories like type, manufacturer and model and a device ID. Another table called system uses the device id to point to the table with the devices. I have a edit system function that I am trying to get working where I can edit the device id field in a record on the system table to change which device in the devices table I am pointing too. I run the update command and it looks like it should work but the row does not get updated. Does anyone know what I am doing wrong?
Here is my update code routine.
SQLiteDatabase db = dbHelper.getWritableDatabase();
String UpdateDeviceName = txtEditDeviceName.getText().toString();
String UpdateDeviceIP = txtEditDeviceIP.getText().toString();
//get the new device id based off of the three spinner values
String dbQuery = "SELECT * FROM " + dbHelper.Devices_Table + ";";
Cursor c = db.rawQuery(dbQuery, null);
if (c.getCount() > 0)
{
while (c.moveToNext())
{
int iColumnID = c.getColumnIndex(dbHelper.Attribute_Device_ID);
int iColumnDeviceType = c.getColumnIndex(dbHelper.Attribute_Device_Type);
int iColumnDeviceManufacturer = c.getColumnIndex(dbHelper.Attribute_Device_Manufacturer);
int iColumnDeviceModel = c.getColumnIndex(dbHelper.Attribute_Device_Model);
String CheckDeviceType = c.getString(iColumnDeviceType);
if (CheckDeviceType.equals(DeviceType))
{
String CheckDeviceManufacturer = c.getString(iColumnDeviceManufacturer);
if (CheckDeviceManufacturer.equals(DeviceManufacturer))
{
String CheckDeviceModel = c.getString(iColumnDeviceModel);
if (CheckDeviceModel.equals(DeviceModel))
{
DeviceID = c.getString(iColumnID);
}
}
}
}
}
db.close();
c.close();
db = dbHelper.getWritableDatabase();
//with the device ID update the system
dbQuery = "UPDATE " + dbHelper.System_Table + " SET " + dbHelper.Attribute_Device_ID + " = " + DeviceID + ", " +
dbHelper.Attribute_Device_Name + " = '" + UpdateDeviceName + "', " +
dbHelper.Attribute_Device_IP + " = '" +
UpdateDeviceIP + "' WHERE " + dbHelper.Attribute_Device_ID + " = " + OrginalDeviceID + ";";
c = db.rawQuery(dbQuery, null);
Log.d("Database Dump", "Edit Device Query: " + dbQuery);
c.close();
db.close();
You closed the DB after the search:
db.close();
leave out this line, since the DB helper code prefers to keep the DB open until it is no longer used (use dbHelper.close() to close the DB when you are done with it).
The same applies after the update.
First of all any rawQuery statement must not contain the trailing semicolon! See the documentation of SQLiteDatabase.
Also you always must close cursors before closing the database. And you have to close the db when you get a new one for each query. Otherwise the system at some point later on will throw exceptions. While those only will be logged and do not cause a Force Close, you should still care about proper resource management.
Finally you should use the updateWithOnConflict method instead with using CONFLICT_REPLACE as the conflictAlgorithm. This simply ignores any UNIQUE constraints and overwrites conflicting rows. So be careful. If you do not want to overwrite existing rows you have to make sure that a constarint violation isn't causing your problem.
I found the answer. FIrst off I want to thank Henry and Wolfram Rittmeyer. You guys where very helpful. :)
For whatever reason the android SQLite does not like to use the update statement in raw sql query form. In researching what Wolfram Rittmeyer said about updateWithConflict I found the update method in the SQLiteOpenHelper object which my dbHelper extends. When I switched to that method I was able to update the database. My where conditions have been expanded on to include the device name as well in the event that the system has more then one device make and model of the same type and only one has to change.
For reference the working code to update the database is the following. I'm only posting the changed portion of the code. Everything in the if (c.getCount() > 0) block and above is unchanged.
c.close();
dbHelper.close();
db = dbHelper.getWritableDatabase();
//with the device ID update the system
ContentValues values = new ContentValues();
values.put(dbHelper.Attribute_Device_ID, DeviceID);
values.put(dbHelper.Attribute_Device_Name, UpdateDeviceName);
values.put(dbHelper.Attribute_Device_IP, UpdateDeviceIP);
String Where = dbHelper.Attribute_Device_ID + " = " + OrginalDeviceID + " AND " + dbHelper.Attribute_Device_Name + " = '" + OrginalDeviceName + "'";
db.update(dbHelper.System_Table, values, Where, null);
c.close();
dbHelper.close();
finish(); //this exits the activity and goes back to the calling activity

Android rawQuery GUI to check query

Having a confounding problem with a query that worked for a while and then stopped working. With a try and catch, there is no error it just returns a null cursor?
Is there a GUI where you can run the query to check the result first or see an error, perhaps it is something subtle like keys? I have confirmed the data types but don't know where else to look. I have concerns going forward on how to debug this type of issue so would appreciate any direction you can offer.
Thanks in advance.
The code set works fine on a single table but when I join 2 tables it now fails (worked yesterday)
Working:
String selectQuery =
SELECT ou.*,"name" as Orchard_Name FROM " + TABLE_TP_ORCHARD_USER ou ;
not working in this case a joined query :
String selectQuery = "SELECT ou.tp_orchard_user_Orchard_ID as
tp_orchard_user_Orchard_ID,ou.tp_orchard_user_User_ID as
tp_orchard_user_User_ID,sd.Orchard_Name as Orchard_Name FROM " +
TABLE_TP_ORCHARD_USER + " ou JOIN " + TABLE_SD_ORCHARD + " sd on
ou.tp_orchard_user_Orchard_ID=sd.Orchard_Id" ;
I have run this code in mysql on another DB and it is fine; it seems maybe there is another error that eclipse can't display? Or I don't know how?
My code sample is:
SQLiteDatabase db = this.getReadableDatabase();
Cursor daCursor = db.rawQuery(selectQuery,null);
if (daCursor != null) {
if( daCursor.moveToFirst() ){
do{
// String Orchard_ID =
daCursor.getString(daCursor.getColumnIndex("Orchard_Id"));
String Orchard_ID = daCursor.getString(0);
Log.i("dbhandler fetchAllOrchards cursor Orchard_ID",
Orchard_ID);
Log.i("dbhandler fetchAllOrchards cursor Orchard_ID",
Orchard_Name);
} while (daCursor.moveToNext());
} else{
Log.i("cursor is false","fail");
}
}

Retrieving Data From SQLite Database

I am creating a user login application . I want to show account information of a user when he logs in in textviews of a layout . Here is the image of a layout .
Here is my code for getting data of a user when he logs in :
public Cursor getUserData(String username){
Cursor UserDataCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER_TABLE_NAME + " WHERE " +
USER_NAME + "='" + username+"'", null);
return UserDataCursor;
Here is the code for retrieving data with that class :
String email2 = cursor.getString(cursor.getColumnIndex("email"));
String name2 = cursor.getString(cursor.getColumnIndex("name"));
String pass2 = cursor.getString(cursor.getColumnIndex("pass"));
String gender2 = cursor.getString(cursor.getColumnIndex("gender"));
String date2 = cursor.getString(cursor.getColumnIndex("date"));
String country2 = cursor.getString(cursor.getColumnIndex("country"));
String reg2 = cursor.getString(cursor.getColumnIndex("reg"));
data+=email2+" "+name2+" "+pass2+" "+gender2+" "+date2+" "+country2+" "+reg2+"\n" ;
cursor.moveToNext();
}
It's giving a null pointer exception . What's the problem here ? How can i fix it ?
I think you're making things much harder for yourself by not using the database adapter pattern.
Take a look here for an example of how to set up more abstraction and error handling for your database:
http://www.devx.com/wireless/Article/40842/1954
It is difficult to verify your code, since it is data-dependent. Your column names could be wrong (or one could be missing). Your data type could be wrong. You might be getting a cursor back with NO rows, which you need to check for.
BTW, are you doing cursor.moveToFirst() before starting?
Also, we don't know what's on line 70, where the error occurred, because line numbers are lost in the posting.

Categories

Resources