Android db.update not work if use db.delete first - java

I have a strange problem to update a table in my database...forgive me if I can not explain well but I'm a bit confused...
The problem is this:
I created a table with values, I read this values in my listview..everything works for now..insert and delete values works without problem..now created a loop in a service why do I need to make a comparison between a value and a string of my database and when this comparison is true, I need to change a value in my table..
The real problem is this: my db.update works only if not use ... never, the command db.delete... if use it, the db.update not work anymore ..and to make it work again, i need to make a new AVD.
how is it possible?
my db.delete and id is this:
item.getMenuInfo();
id = getListAdapter().getItemId(info.position);
public void deleteReg(SQLiteDatabase db ,long id)
{
db.delete(TabRegistry.TABLE_NAME, TabRegistry._ID + "=" + id, null);
}
on activity:
databaseHelper.deleteReg(db, id);
my db.update is this: (positions is a value of getPositions(),for locate a positions with a cursor(always works, even when fails db.update))
public void updateReg(SQLiteDatabase db,int positions, String stat)
{
ContentValues v = new ContentValues();
v.put(TabRegistry.STATUS, stat);
db.update(TabRegistry.TABLE_NAME, v, TabRegistry._ID + " = " + positions, null);
}
on service:
databaseHelper.updateReg(db, positions, "SUCCESS");
if you need more code, tell me what I add now..thanks in advance

The SQLite api you are using is based off of CRUD operations (you should read this).
You are DELETE-ing the record from the database, therefore there is nothing to UPDATE when you attempt to update it. If you want to create a new record, or recreate the one you deleted then you would perform an INSERT instead of an UPDATE.
EDIT:
It also appears you are passing in position number to the update and delete. I assume that you are also using this value to place the record in your table? Is it possible that when you delete the record from the table and the database, that the other records now have an invalid position because they haven't been updated also? It's just a shot in the dark, figured I might as well ask.

Related

Spring: Not setting column value in table

I have the following table in which I have to set orderID against each itemName, my itemName set successfully but orderId sets null , When I print the value at console it prints right value.
Can anybody tell me what is the problem in my code?
List<String> items;
items=orderRequest.getOrderItem();
OrderItem orderItem=new OrderItem();
for (String temp : items) {
orderItem.setItemName(temp);
orderItem.setOrderId(order.getId());
System.out.println("Order Id " + order.getId());
orderItemRepo.save(orderItem);
}
Please check your field name and also attach a debugger to figure out the real problem
The first thing that comes to my mind is that you are looping over potentially multiple items and setting the order id of the single orderItem every time.
The best way to figure out these kind of problems and get a feeling for what your code is doing is to attach a debugger and step through the code.

Java: resultSet update does not update database

I am developing a Java app, as a learning tool for myself mainly, using a java database tutorial, and for some reason, the resultSet update is not actually updating my database.
Details about the project: I am using the Netbeans IDE and connecting to a Derby database with 5 tables (each with between 3 and 6 columns). The database viewer window is supposed to load all of the records into resultSet's and set the text in each blank in the window to those stored records. This process and the buttons to move the cursor to First, Previous, Next, and Last all work perfectly. The part I am currently working on is making the Update button get the text in the blanks and update the records in the database, accordingly.
Now to the problem: the records don't update. When I run the project and change a value, then press Update, the value doesn't revert back to the original value or anything (since I'm not setting the text again in the updateButton method), but when I click next and then previous, the text is back to its original value. Additionally, the values are not updated when I close the application and query the records in the database. I also don't get any exceptions, and Netbeans tells me the build is successful.
Relevant code for the update method (and yes, I'm aware it's probably inefficient, but I'm trying to just get it working before I break it trying to make it look better):
private void btnUpdateRecordActionPerformed(java.awt.event.ActionEvent evt) {
try {
// get text from fields and convert to appropriate data type
// in times
String wakeTime = fieldWakeTime.getText();
Time wakeTimeTm = java.sql.Time.valueOf(wakeTime);
String outTime = fieldOutTime.getText();
Time outTimeTm = java.sql.Time.valueOf(outTime);
String inTime = fieldOutTime.getText();
Time inTimeTm = java.sql.Time.valueOf(inTime);
String sleepTime = fieldOutTime.getText();
Time sleepTimeTm = java.sql.Time.valueOf(sleepTime);
// in weights
String morningPre = fieldPreWeight.getText();
double morningPreDoub = Double.parseDouble(morningPre);
String morningPost = fieldPostWeight.getText();
double morningPostDoub = Double.parseDouble(morningPost);
String nightWeight = FieldNightWeight.getText();
double nightWeightDoub = Double.parseDouble(nightWeight);
// in meals
String fullMeals = fieldFullMeals.getText();
int fullMealsInt = Integer.parseInt(fullMeals);
String snacks = fieldSnacks.getText();
int snacksInt = Integer.parseInt(snacks);
String sodas = fieldSodas.getText();
int sodasInt = Integer.parseInt(sodas);
String alcohol = fieldAlcohol.getText();
double alcoholDoub = Double.parseDouble(alcohol);
String desserts = fieldDesserts.getText();
int dessertsInt = Integer.parseInt(desserts);
// in ratings
String morningMood = fieldMorningMood.getText();
double morningMoodDoub = Double.parseDouble(morningMood);
String nightMood = fieldNightMood.getText();
double nightMoodDoub = Double.parseDouble(nightMood);
String activityRating = fieldActivityRating.getText();
double activityRatingDoub = Double.parseDouble(activityRating);
// uses rs's to update db columns
// in times
rsTimes.updateTime("WAKE_TIME", wakeTimeTm);
rsTimes.updateTime("OUT_TIME", outTimeTm);
rsTimes.updateTime("IN_TIME", inTimeTm);
rsTimes.updateTime("SLEEP_TIME", sleepTimeTm);
// in weights
rsWeights.updateDouble("MORNING_PRE", morningPreDoub);
rsWeights.updateDouble("MORNING_POST", morningPostDoub);
rsWeights.updateDouble("NIGHT_WEIGHT", nightWeightDoub);
// in meals
rsMeals.updateInt("FULL_MEALS", fullMealsInt);
rsMeals.updateInt("SNACKS", snacksInt);
rsMeals.updateInt("SODAS", sodasInt);
rsMeals.updateDouble("ALCOHOL", alcoholDoub);
rsMeals.updateInt("DESSERTS", dessertsInt);
// in ratings
rsRatings.updateDouble("MORNING_MOOD", morningMoodDoub);
rsRatings.updateDouble("NIGHT_MOOD", nightMoodDoub);
rsRatings.updateDouble("ACTIVITY_RATING", activityRatingDoub);
// updates rows
rsTimes.updateRow();
rsRatings.updateRow();
rsWeights.updateRow();
rsMeals.updateRow();
} catch (SQLException err) {
JOptionPane.showMessageDialog(this, err.getMessage());
}
}
When searching out solutions to this problem I've come across a great deal of variations on suggestions to con.setAutoCommit(false); and then commit the changes at the end of the method block, which I have tried, as well as explicitly con.setAutoCommit(true); to see if it wasn't defaulting to that for some reason, neither of which worked. (For reference, I did an earlier version of this app using, following the tutorial much more closely and using just 1 of the resultSet's and 1 of my tables and was able to get the update button working.) Also, my prepared statements have the resultSet's set to TYPE_SCROLL_INSENSITIVE and CONCUR_UPDATABLE, which I believe to be the correct options.
Link to the github repository of the project: link. The relevant file is MetrikaViewer.java, not DataManip.java, and the README (if you happened to need more information I didn't give you or like self-deprecating snark) is in the master branch, which is not where the rest of the code is (the Metrika branch) because of some problems I had using git (with an almost 100% chance of being caused by my own stupidity).
Really, as a still very new Java learner, I would not be at all surprised if this was caused by some weird misunderstanding of how something works on my part, but after a week of scratching my head, I just can't seem to find it.
Edit: As per Axel, I added updateRow's to the method. Now the changes update within the app while running, but it does not update the database. (I've updated the code above, accordingly, and the github repo should reflect the changes made.)
I have never used these updateXXX() methods, but as I understand the documentation, you have to issue a call to either rs.updateRow() or rs.insertRow() after updating the columns.
Also, you have to make sure to create your statement with ResultSet.CONCUR_UPDATABLE (since by default, readonly is used).

Can I make this request more efficient using index?

I have this bean/table "Userinfo" with columns id, username, and twitchChannel.
For most userinfo the twitchChannel column will be null. I'm going through every userinfo entity in the table and search the column twitchChannel, if the column is not null I put the twitchChannel in an array.
this is what my request looks like:
"SELECT ui FROM Userinfo ui WHERE ui.iduserinfo=:id"
It is very inefficient because I'm going through every single entity even those which have a null twitchChannel and I'm not interested in those.
This is java but I commented every line so it's easy to understand for those who don't know it.
while (true) { // I'm going through the table in an infinite loop
int id = 0; //id that is incremented for searches
Userinfo ui; // this will be an object that will hold the result of my query
do {
ui = ups.getUserInfo(id); // this execute the query I posted above
id++; //incrementing id for next search
if (ui.getTwitch() != null) { // if the search didn't return null
twitchChannels.add(ui.getTwitch()); // put my twitch in an array
}
} while (ui != null);
}
So at the moment I'm going through every entity in my table even those with a null twitch. To my understanding it's possible to speed up the process with indexes.
CREATE INDEX twitchChannel
ON Userinfo (twitchChannel)
So something like that would have a table with not null twitchChannel. How I loop through this table like above ?
Will it work the same way with java persistence?
Change the query to:
SELECT ui
FROM Userinfo ui
WHERE twitchChannel IS NOT NULL
This will benefit from an index on Userinfo(twitchChannel) (assuming there really are very few values that are filled in). At the very least, this reduces the amount of data passed from the database to the application, even if an index is not used.
If I've understood your question correctly. You have a table containing numerical id's. And you are searching the space of real numbers to see if any of those correspond to an id in your table ('twitch' id ?)
Assuming you have less than infinity users, I would have thought you can reverse this logic.
Change your query to :
SELECT iduserinfo FROM Userinfo ORDER BY iduserinfo
Then your java code will be something along the lines of :
uiResult = ups.getUserInfo(id); // this executes the new query
while (uiResult.next()) {
twitchChannels.add(uiResult.getTwitch()); // put my twitch in an array
}
(Apologies, its been a long time since I've used jdbc).
Sorry If I've misunderstood the question.

Android SQLite Delete not changing anything

I have the following method in my SQL class:
public void deleteEntry(int idnum) {
dbSQL.delete(DATABASE_TABLE, KEY_ROWID + " = 0", null);
}
I usually give it an idnum but for testing purposes I've just put a 0 there. Syntax wise, is there any reason why this wouldn't work? I've tried everthing.
Assuming that KEY_ROWID is an autoincrementing primary key, the first record you enter will have value 1, not 0.
That being said, the reason why your delete method isn't working is most likely because there is no record with value 0.
Edit #1:
If I were you, I would uninstall and re-install your app and start from scratch. Either that, or use adb to analyze the contents of your SQLite database (using the emulator, if you don't have a rooted device). You can find the database file on the disk at /data/data/[package name]/databases/database_name.db (or something like that).
The best way to figure out why things aren't working at this point is to analyze the contents of the database. Otherwise you will just be guessing and checking until something appears to work... and even then you probably won't know for sure if your implementation is 100% correct.
Edit #2:
As an alternative to analyzing the database file using the emulator and/or your rooted device, you could perform a query for ALL data in the database, and then use the dumpCursor method provided in the DatabaseUtils class to print the contents of the Cursor to System.out.
You should use this version,
public void deleteEntry(int idnum) {
dbSQL.delete(DATABASE_TABLE, KEY_ROWID + " = ?", new String[] {"0"});
}
With 0 it will probably not work because if the column is INTEGER and AUTOINCREMENT it will start counting at a value greater then 0 so there isn't a row with the KEY_ROWID 0 to delete.
Change it to,
public void deleteEntry(int idnum) {
dbSQL.delete(DATABASE_TABLE, KEY_ROWID+"=?", new Integer[]{idnum});
}
if your KEY_ROWID column is string than you have to use
public void deleteEntry(int idnum) {
dbSQL.delete(DATABASE_TABLE, KEY_ROWID + " = '0'", null);
}
Thanks for the help everyone, but I had some luck by just using a method I had built that took the id and returned the name associated with that entry and it successfully deletes corresponding items now.

What is wrong with this GeoTools FeatureId?

Using the GeoTools WFS-T plugin, I have created a new row, and after a commit, I have a FeatureId whos .getId() returns an ugly string that looks something like this:
newmy_database:my_table.9223372036854775807
Aside from the fact that the word "new" at the beginning of "my_database" is a surprise, the number in no way reflects the primary key of the new row (which in this case is "23"). Fair enough, I thought this may be some internal numbering system. However, now I want a foreign key in another table to get the primary key of the new row in this one, and I'm not sure how to get the value from this FID. Some places suggest that you can use an FID in a query like this:
Filter filter = filterFactory.id(Collections.singleton(fid));
Query query = new Query(tableName, filter);
SimpleFeatureCollection features = simpleFeatureSource.getFeatures(query);
But this fails at parsing the FID, at the underscore of all places! That underscore was there when the row was created (I had to pass "my_database:my_table" as the table to add the row to).
I'm sure that either there is something wrong with the id, or I'm using it incorrectly somehow. Can anyone shed any light?
It appears as if a couple things are going wrong - and perhaps a bug report is needed.
The FeatureId with "new" at the beginning is a temporary id; that should be replaced with the real result once commit has been called.
There are a number of way to be aware of this:
1) You can listen for a BatchFeatureEvent; this offers the information on "temp id" -> "wfs id"
2) Internally this information is parsed from the Transaction Result returned from your WFS. The result is saved in the WFSTransactionState for you to access. This was before BatchFeatureEvent was invented.
Transaction transaction = new transaction("insert");
try {
SimpleFeatureStore featureStore =
(SimpleFeatureStore) wfs.getFeatureSource( typeName );
featureStore.setTransaction( transaction );
featureStore.addFeatures( DataUtilities.collection( feature ) );
transaction.commit();
// get the final feature id
WFSTransactionState wfsts = (WFSTransactionState) transaction.getState(wfs);
// In this example there is only one fid. Get it.
String result = wfsts.getFids( typeName )[0];
}
finally {
transaction.close();
}
I have updated the documentation with the above example:
http://docs.geotools.org/latest/userguide/library/data/wfs.html

Categories