chennaione / sugar Goto Github PK
View Code? Open in Web Editor NEWInsanely easy way to work with Android Database.
Home Page: http://satyan.github.com/sugar/
License: MIT License
Insanely easy way to work with Android Database.
Home Page: http://satyan.github.com/sugar/
License: MIT License
I am getting a lot of this crashes in my recently released app:
java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.
at android.database.sqlite.SQLiteConnectionPool.throwIfClosedLocked(SQLiteConnectionPool.java:962)
at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:599)
at android.database.sqlite.SQLiteConnectionPool.acquireConnection(SQLiteConnectionPool.java:348)
at android.database.sqlite.SQLiteSession.acquireConnection(SQLiteSession.java:894)
at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:752)
at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
at android.database.sqlite.SQLiteDatabase.delete(SQLiteDatabase.java:1550)
at com.orm.SugarRecord.delete()
at com.npi.muzeiflickr.api.FlickrSource.onTryUpdate(FlickrSource.java:155)
at com.google.android.apps.muzei.api.RemoteMuzeiArtSource.onUpdate(RemoteMuzeiArtSource.java:105)
at com.google.android.apps.muzei.api.MuzeiArtSource.processHandleCommand(MuzeiArtSource.java:639)
at com.google.android.apps.muzei.api.MuzeiArtSource.onHandleIntent(MuzeiArtSource.java:545)
at com.npi.muzeiflickr.api.FlickrSource.onHandleIntent(FlickrSource.java:520)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:158)
at android.os.HandlerThread.run(HandlerThread.java:60)
This one is on a .delete() call, but I also get the same crashes for .save() and so on.
Has anyone experienced this? Am I doing something wrong?
If you write a migration like this:
alter table FOO add column BAR text;
it results in Sugar being unable to inflate any row in FOO, because of a NPE at https://github.com/satyan/sugar/blob/master/library/src/com/orm/SugarRecord.java#L245
or like this:
alter table FOO add column BAZ integer;
results in a NPE when baz is boolean at: https://github.com/satyan/sugar/blob/master/library/src/com/orm/SugarRecord.java#L252
Need database upgrade/versioning support.
Hey, when I list the datas with listAll(), the response is :
package.name@421d9f28,
package.name@421da700,
package.name@421dad40
My database contain :public Bets(Context context, int betid, int dicef, int dicet, int dices, int betamount, String worl)
How can I correct this ?
Thanks.
Purty please.
wouldn't it be nice to have a javadoc? Good documentation make a difference. Nice project, btw.
Causes exceptions when there are other libraries used.
I'm looking to provide a database of 'Achievements' of which are defined in a SQL database, i love the methods in Sugar and want to be able to access this sql file and add it as a table to the existing sugar DB for reading and writing?
I see that when an SQL error happens during a save()
it is eaten because insert()
is used instead of insertOrThrow()
(see https://github.com/satyan/sugar/blob/master/library/src/com/orm/SugarRecord.java#L192) and in some case it's not what we want.
Maybe is better to check for the return value and throw a SugarError
?
I'm confused with this issue and don't know how to resolve it.
I write the code like this (some not related code was erased) :
public void onReceive(Context context, Intent intent) {
Conversations conv = null;
conv = saveToDb(context, sender, body, cat, "R");
pushNotification(context, conv);
}
public static Conversations saveToDb(Context context,
String recipient, String body, String category, String type) {
String snippet = (body.length() > 30 ) ? body.substring(0, 30) + "..." : body;
String date = System.currentTimeMillis() + "";
List<Conversations> result = Conversations.find(
Conversations.class, "RECIPIENT = ?", new String[]{recipient});
Conversations conv = null;
if( result.size() == 0) {
conv = new Conversations(
context, snippet, recipient, date);
} else {
conv = result.get(0);
conv.recipient = recipient;
conv.snippet = snippet;
conv.date = date;
}
conv.save();
message = new Messages(context, body, date, category, type, conv);
message.save();
return conv;
}
private void pushNotification(Context context, Conversations c) {
Intent resultIntent = new Intent(context, MessagesActivity.class);
Bundle b = new Bundle();
b.putLong("conv_id", c.id); // c.id = null, then throw an nullpointerexception
b.putString("recipient", c.recipient);
resultIntent.putExtras(b);
}
In function saveToDb, if result.size() == 0 I create new record of Conversation class and then save it and return this object. And then I use the returned object to be parameter for function pushNotification. When function pushNotification read id of the object (c.id), it has value 0 and I get an error. I also have tried to debug this object value in each function and it shown that id has value 0 and others field have been filled with data I want to store in. In saveToDb function, I also save a new record of Messages class, and it has no error.
But if result.size is not 0, this all function is successfully done. what's wrong with my code ? why save a new record of Message class was successful but not for Conversation class ? :-/
Hi
Could you give some tips on how to create One To Many relationship?
For instance
public class Person {
private List cars;
}
I couldn't find anything on how Collections are stored, but documentation says "This would help with one-to-one and one-to-many relationships"
Thanks
project is simple java project in it's current state, convert it to Android library project for ease of use and easy upgrade of library from client side.
In SugarRecord.inflate(), the retrieved boolean value is compared with "true"
while SQLite stores the booleans as "0" or "1", which always returns false:
cursor.getString(cursor.getColumnIndex(colName)).equals("true"));
Should be:
cursor.getString(cursor.getColumnIndex(colName)).equals("1"));
Hi sugar team,
I just learnt about the sugar project and it looks very promising.
The only thing that bugs me is the mandatory inheritance on SugarRecord for POJO classes. This is quite a strong requirement in term of design and will block many potential adopters.
Don't you think it would be easier/cleaner to provide a standard DAO object to perform DB operations ?
BTW, is it mandatory to extend from SugarApp ?
both calendars and dates cannot be null when saving the domain entity or it will cause a NPE since current code assumes it is never null
Hi
I started testing the query feature. The query I tried is
searchResults = Select.from(Data.class)
.where(Condition.prop("PROPERTY_ONE").notEq(null)).list();
I was expecting to get all the records but got a null pointer exception. It looks like convertArgs function in the Select.class is doing a toString() operation which fails on the null.
Is there a keyword or symbol to get all the rows with only some properties are set. For example
searchResults = Select.from(Data.class)
.where(Condition.prop("PROPERTY_ONE").eq("property_one_value"),
Condition.prop("PROPERTY_TWO").eq("property_two_value"),
Condition.prop("PROPERTY_THREE").eq(ALL_ROWS)).list();
where ALL_ROWS is a wild card operator to signify all rows.
I understand that I can just skip property three but in the application, the conditions are provided from spinners. So it would be preferable to have a common query to which property values can be sent based on the spinner choice
Rails quotes columns all the time and puts ` around them
Customer has an Order table (came out of parsed JSON), so I get:
CREATE TABLE CUSTOMER ( ID INTEGER PRIMARY KEY AUTOINCREMENT , EMAIL TEXT, FIRST_NAME TEXT, FULL_NAME TEXT, LAST_NAME TEXT, MOBILE TEXT, ORDER INTEGER, TELEPHONE TEXT, TITLE TEXT )
Sqlite doesn't like order, if I try it in a shell and put a backtick on it, e.g.
CREATE TABLE CUSTOMER ( ID INTEGER PRIMARY KEY AUTOINCREMENT , EMAIL TEXT, FIRST_NAME TEXT, FULL_NAME TEXT, LAST_NAME TEXT, MOBILE TEXT, ORDER
INTEGER, TELEPHONE TEXT, TITLE TEXT )
I will see how much effort it it to fork and give the fix back to you.
Hi,
I am currently using the following hack to reset all sugar managed data in sqlite:
SugarDb db = new SugarDb(SugarApp.getSugarContext());
db.onUpgrade(db.getWritableDatabase(),-1,-1);
I am basically relying on the fact that Sugar deletes and recreates the DB if upgrading fails.
I was wondering if there is a better/proper way to do it?
Thanks
Dominik
SugarApp requires it to be set as application class but I am using my own class with more methods. Is there any way getting over this requirement?
Title says it all, perhaps an annotation for unique?
Hi. I have two classes that behave different. One return all values, all right when I use ListAll (or whatever other method). The other class return objects only with Id set, all other values null. I'm trying to figure out what is happening but I don't know.
Im using:
Here is the problematic class. The subject object relationed to it is coming with everything set too. I don't know what can be wrong π
public class Am extends SugarRecord<Am> {
private Float grade;
private Integer half;
private Subject subject;
public Am(Context context) {
super(context);
}
// getters and setters
}
Hi,
I wanted to know if there is any way to pre populate the sqlite database with data using Sugar before shipping the android application. Or maybe some other way to bulk insert the records from a JSON file or an array on first install. I have requirement where I need to have around a 1000 products in the database already for the user to use.
Hi,
it would be great if you could add Maven support.
If you check the description of Application#onTerminate [1], it says that it's never called on production device. Isn't that a problem? Because I was thinking about storing "GameClient" and "PlusClient" the same way, in Application, but I didn't know how/when to disconnect properly.
[1] - http://developer.android.com/reference/android/app/Application.html#onTerminate()
I can seem to find any method returns last_insert_rowid(), do I need to get it with raw query?
I need to use "last_insert_rowid" because i am trying to populate database at first run from a text file and there is ID relation of items
Thanks
https://github.com/satyan/sugar/blob/master/src/com/orm/SugarRecord.java#L71
id = (id == null)
? sqLiteDatabase.insert(getSqlName(), null, values)
: sqLiteDatabase.update(getSqlName(), values, "ID = ?", new String[]{String.valueOf(id)});
This is wrong because "update" returns number of updated records, not ID as insert does.
Suggested change:
if (id == null)
id = sqLiteDatabase.insert(getSqlName(), null, values);
else
sqLiteDatabase.update(getSqlName(), values, "ID = ?", new String[] { String.valueOf(id) });
Thanks for a great library!
My suggestion is to insert theTRANSIENT not serialized by Gson or Jackson.
I had problem to serialize more solves the transient, more Maybe you have another way to solve this issue I am hearing.
@ignore
private transient Context context;
@ignore
private transient SugarApp application;
@ignore
private transient Database database;
@ignore
transient String tableName = getSqlName();
protected transient Long id = null;
I have found that if a named attribute with CamelCase notation, the name of that column in database is transformed with '_'.
For example, if I have an attribute as:
String fullName;
In Database would create the column:
FULL_NAME
This influences the time to search, because you would typically look for FULLNAME, and if so does the query fails. The search should be done with FULL_NAME.
For example:
This fails:
List myUser = MyUser.find(MyUser.class, "FULLNAME=?", String[]{name});
How it works:
List myUser = MyUser.find(MyUser.class, "FULL_NAME=?", String[]{name});
At least it would be interesting to put it in the documentation, and I had to dowload the source code and debug it to see it did not work as I thought it should work. xDDD.
I hope this advice is useful for the future. =D
Take this opportunity to congratulate you for the great work done. Library is a very easy and intuitive to use.
For example
in
alter table RECORDING_FILE add ORIGINAL_SAMPLERATE TEXT;
alter table RECORDING_FILE add ORIGINAL_BITRATE TEXT;
only the first line executed. Sugar seems to proccess it file but on db.execSQL(text.toString()); in SugarDB.java only first column added
As far as I can tell Sugar doesn't handle doing a vacuum of the database.
Would be nice to have a static vacuum method we could call.
Is it possible to create a many-to-many relation?
public class User extends SugarRecord {
private List friends;
}
something like this?
thanks :)
Entity is not persisted if a constructor with context is not present.
Eg:
public class User extends SugarRecord<User> {
private String name;
private String surname;
private String date;
public User(Context context, String name, String surname)
{
super(context);
this.setAll(name, surname);
}
}
The above entity is not persisted. However, once the constructor is added, it works fine. for eg:
public class User extends SugarRecord<User> {
private String name;
private String surname;
private String date;
public User(Context context)
{
super(context);
}
public User(Context context, String name, String surname)
{
super(context);
this.setAll(name, surname);
}
}
My Class:
public class BankAccount extends SugarRecord{
String name;
String alias;
public BankAccount(Context context) {
super(context);
}
public BankAccount(Context context, String name) {
super(context);
this.name = name;
this.alias = name;
}
public BankAccount(Context context, String name, String alias) {
super(context);
this.name = name;
this.alias = alias;
}
I can create new entries (The logs are saying that):
BankAccount bankAccount = new BankAccount(context, sms.getAccount());
bankAccount.save();
But I when I try to get a list of all entries with:
List bankAccounts = BankAccount.listAll(BankAccount.class);
I get a list with all entries but this error, too:
05-15 19:22:37.977: ERROR/Sugar(13045): Class cannot be read from Sqlite3 database.
i can see that a boolean column is mapped internally by SqLite to an Integer DataType. no problem with that. but has anyone been able to use Sugar to query a boolean column?
one of my class has this variable:
boolean Sync;
when i try: MyRecord.find(MyRecord.class, "Sync = 0")
it returns no records, even though there are records there with Sync set to false. i've tried all variations on Sync=FALSE sync=false etc.
the strange thing is, if i query for "Sync > 0" i get all the records regardless of the True/False status of the records. can anyone shed some light on this? am i using the wrong syntax?
apologies in advance. new to Java...
Booleans are assigned INTEGER type affinity in table schema by QueryBuilder: https://github.com/satyan/sugar/blob/master/library/src/com/orm/QueryBuilder.java#L7
But when storing values in the database, booleans are saved as TEXT ([ "true" | "false" ]): https://github.com/satyan/sugar/blob/master/library/src/com/orm/SugarRecord.java#L73
I'd expect Sugar to map false to 0 and true to 1.
Hi, I just want to make sure if the code in StringUtil.toSQLName() changes all the sql names to uppercase? Because when I use find() method I need to write
Note.find(Note.class, "NAME = ? and TITLE = ?", "satya", "title1") instead of
Note.find(Note.class, "name = ? and title = ?", "satya", "title1");
if (isFirstChar || Character.isLowerCase(c) || Character.isDigit(c)) {
sb.append(Character.toUpperCase(c));
} else if (Character.isUpperCase(c)) {
if (Character.isLetterOrDigit(prevChar)) {
if (Character.isLowerCase(prevChar)) {
sb.append('_').append(Character.toUpperCase(c));
} else if (nextChar > 0 && Character.isLowerCase(nextChar)) {
sb.append('_').append(Character.toUpperCase(c));
} else {
sb.append(c);
}
}
else {
sb.append(c);
}
}
Hi there!
First time I am using this, so please bear with me if this is a dumb question :)
Getting this error when I try to add a record;
11-14 14:52:18.154: E/AndroidRuntime(7415): FATAL EXCEPTION: main
11-14 14:52:18.154: E/AndroidRuntime(7415): java.lang.ClassCastException: android.app.Application cannot be cast to com.orm.SugarApp
11-14 14:52:18.154: E/AndroidRuntime(7415): at com.orm.SugarRecord.<init>(Unknown Source)
The source code for Sugar does not contain any License information. What License is this project distributed under?
I don't really know where the issue may come from.
I'm getting this kind of crashes in my app:
android.database.sqlite.SQLiteException: no such column: SHADOWMONITOR (code 1): , while compiling: UPDATE USER SET SHADOWMONITOR=?,SHADOWKLASS=?,TOTAL=?,PAGE=?,CURRENT=?,USER_ID=?,USER_NAME=? WHERE ID = ?
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(SQLiteConnection.java)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1572)
at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1520)
at com.orm.SugarRecord.save()
at com.orm.SugarRecord.save()
at com.npi.muzeiflickr.db.User.incrementCurrent(User.java:76)
at com.npi.muzeiflickr.api.FlickrSource.onTryUpdate(FlickrSource.java:142)
at com.google.android.apps.muzei.api.RemoteMuzeiArtSource.onUpdate(RemoteMuzeiArtSource.java:105)
at com.google.android.apps.muzei.api.MuzeiArtSource.processHandleCommand(MuzeiArtSource.java:639)
at com.google.android.apps.muzei.api.MuzeiArtSource.onHandleIntent(MuzeiArtSource.java:545)
at com.npi.muzeiflickr.api.FlickrSource.onHandleIntent(FlickrSource.java:727)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
I tried to search for "SHADOWMONITOR" in both my app the library. I ended up by searching it on Google and I cannot find a reference to this.
Here is the line where the issue comes from: https://github.com/PomepuyN/muzei-flickr/blob/Development/MuzeiFlickr/src/main/java/com/npi/muzeiflickr/db/User.java?source=c#L76
Is the "User" word allowed for DB Tables? If yes, do you have an idea what happens here?
hi, i'm new to android development and finding the sugar library very helpful. a few things tripped me up starting off:
one of my data classes had fields for Address1, Address2, Address3, Address4.
when it came down to running the app the sugar library traced out some exceptions re: duplicate field names for ADDRESS. i changed the names to AddressOne, AddressTwo etc and there was no problem.
i also had an Integer field called ID. this conflicted with the internal Sugar 'id' field, so i had to rename this to ServerID. no problem then.
another field called RollNumber didn't work. i had to rename it to "Roll" instead and it worked. maybe the 'Number' got stripped out...
great library, thanks.
tim
Hi
I used the jar file in a project and the programs runs without any issue. But looking at the logs I see the error "Class cannot be read from Sqlite3 database".
I noticed that the sugarexample project also has the error in the logs. I traced this back to line 170 in sugarrecord.java
Would you know if this is a real issue or if this can be ignored ?
Community question..
Hi, great job!
Is possible to make a Count() from Sugar?
I think you can create a list and read how many items have, but this is a very heavy for DB
Thanks a lot.
CarlosJG
Hi
Is there a simple way to query the database with complicated "finders" than the ones shows in the "Extra sugar" example ? For example, how does one find objects which satisfy criteria over different member variables ? On a related note... are you planning to add query building features like this in another android orm
http://greendao-orm.com/documentation/queries/
Any help you provide is much appreciated.
Thank You
http://satyan.github.io/sugar/getting-started.html#entities says:
Sugar takes care of table creation for you.
But it's only the first time, or if you decide to drop all the data with every upgrade.
I don't see why couldn't Sugar take care of creating tables for any entities not yet present. Since it does it already on database creation, this could save the developers from writing "create table" queries in migration files, that Sugar is able to execute for them automatically.
Hi, I am new with Sugar. I have a simple android project with a single record named "Abonado". I have followed the wiki' steps but when I ran the project and I had the error: "android.database.sqlite.SQLiteException: no such table: ABONADO (code 1): , while compiling: SELECT * FROM ABONADO". Then I looked the db file created and itβs true, the table ABONADO does not exit.
Then I looked the master project SugarActivity and it does not make the tables either and I also had another similar error: "android.database.sqlite.SQLiteException: no such table: TEXT_NOTE (code 1): , while compiling: DELETE FROM TEXT_NOTE".
Have you experienced this issue before?Could you please help me? Thanks in advanced. Respectfully.
ohh I am using android 4.2
after retrieving a record from the database, a call to record.getId() returns null always rather then application's ID
FantasyStocksDB initalFunds = new FantasyStocksDB(getActivity(),stockSymbol,numShares,stockPrice );
initalFunds.save();
public class FantasyStocksDB extends SugarRecord {
String symbol;
int stockNum;
double lastBuyPrice;
public FantasyStocksDB(Context ctx, String symbol, int stockNum, double lastBuyPrice){
super(ctx);
this.symbol = symbol;
this.stockNum = stockNum;
this.lastBuyPrice = lastBuyPrice;
}
public String getStockSymbol()
{
return this.symbol;
}
public int getNoOfStocks()
{
return this.stockNum;
}
public double getLastBuyPrice()
{
return this.lastBuyPrice;
}
}
public class Book extends SugarRecord {
String ISBN_ID;
String title_string;
}
becomes below columns
ISBNID
TITLESTRING
it shouldn't touch property names should it?
Hello,
I followed the steps in the Getting Started section of the website. I get this error when I run the application (no build errors).
java.lang.RuntimeException: Unable to instantiate application com.orm.SugarApp: java.lang.ClassNotFoundException: com.orm.SugarApp
Am I doing something wrong? I added sugar-1.2.jar to the libs folder, and added it to the build path. I even see it under Referenced Libraries.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.