Sugar ORM单条记录更新失败求助:代码执行后数据库未更新
Hey there! Let's dig into why your record update isn't showing up in the database. I've worked with Sugar ORM before, so let's break down possible fixes for your code.
First, Simplify Your Query (Avoid Manual SQL When Possible)
Your current code uses a raw SQL query to fetch the first record, but Sugar ORM has built-in methods that handle entity state management more reliably. Try replacing your query with findFirst() instead:
// Fetch the first PagingSelected record directly PagingSelected record = PagingSelected.findFirst(PagingSelected.class); if (record != null) { record.setNext(true); record.update(); }
This method ensures the returned entity is properly tracked by Sugar ORM, so calling update() should persist the changes correctly.
If You Must Use Raw SQL: Check Entity Tracking
If you need to stick with findWithQuery, sometimes the returned objects aren't fully managed by Sugar ORM. A quick fix here is to call save() instead of update()—Sugar will automatically handle inserts or updates based on whether the record exists:
List<PagingSelected> finds = (List<PagingSelected>) PagingSelected.findWithQuery(PagingSelected.class, "Select * from "+NamingHelper.toSQLNameDefault("PagingSelected")+" LIMIT 1"); if (!finds.isEmpty()) { PagingSelected record = finds.get(0); record.setNext(true); record.save(); // Use save() instead of update() }
Critical Checks to Rule Out Basics
Before diving deeper, make sure these fundamentals are in place:
- Your entity extends SugarRecord: Double-check that
PagingSelectedextendsSugarRecord<PagingSelected>(or the non-genericSugarRecordfor older versions). Without this, Sugar ORM can't interact with your entity properly. - Manifest Configuration: Verify your AndroidManifest.xml has the required Sugar ORM meta-data under the
<application>tag, like database name and version:<meta-data android:name="DATABASE" android:value="your_db_name.db" /> <meta-data android:name="VERSION" android:value="1" /> <meta-data android:name="QUERY_LOG" android:value="true" /> <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="com.your.package" /> - Check Logcat for Errors: Filter logcat for "Sugar" or SQL-related messages—you might find clues like a missing column, permission issue, or query syntax error that's failing silently.
Final Test: Verify the Update Actually Runs
Add a quick log statement after the update to confirm the object's value changed in memory, even if it's not hitting the database:
Log.d("SugarORM", "Updated record next value: " + record.getNext());
If the log shows true but the database still doesn't reflect it, the issue is definitely with how Sugar is persisting the change—sticking with findFirst() and update() should resolve that.
内容的提问来源于stack exchange,提问作者behzad

