Quickly develop Android Internet clients that need to sync and save large amounts of data with Sugarorm

Source: Internet
Author: User
Tags log log sqlite database

A recently developed project has two main features, and these two points also need to focus on planning the solution before the project is developed:

    1. Requires a large amount of data to be requested and rest service side
    2. This data is also saved locally to the SQLite database
For the 1th, the current volley, Gson and other frameworks can solve the whole process of pulling JSON data from the server request data and parsing it into Java object. But for the 2nd, it's a bit of a headache. In accordance with the previous development model, we want to write some code to operate the SQLite database, and may also need to use what query database binding to the view of things, here think of a lot of Android provides classes: Sqlitedatabase, Datahelper,CursorAdapter or Contentresolver wait too much, even I can not make clear, every time to do here to check some of the original code and online information we know that long-term repetitive code is bound to be summed up as a simple framework. So, to save the database and take out the data,Is there a better, simpler way or framework? The answer is yes, it's the sugarorm framework. Sugarorm Introduction To say Sugarorm had to say ORM before. ORM (object-relational Mapping), an object-relational mapping model, is a common technique in Java development.its role is to make a mapping between the relational database and the business entity object, so that we do not need to deal with complex SQL statements when we operate the business objects, simply manipulate the properties and methods of the objects. Because Android development is also in the Java language, so the Android platform on the emergence of some Android ORM framework, such as Ormlite, Greendao, Sugarorm,ormlite is not built for Android, Greendao is said to have a high performance, but there are significant flaws, which will be said later. So the final selection of Sugarorm this framework, while the Sugarorm has been updated maintenance, it is recommended to use this framework. It has the following advantages:
    1. Create and manipulate data with simple APIs without having to write complex SQL statements
    2. You can reuse beans by simply adding small modifications to the original bean
    3. Simplified and straightforward database design and creation process while providing one-to-many support for tables
Sugarorm on GitHub's website is: http://satyan.github.io/sugar/index.htmloperation of the Sugarorm Import the Sugarorm by adding the following dependencies in Gradle:
' com.github.satyan:sugar:1.3 '
Also add the following meta-data in the application element in Androidmanifest.xml:
    <Applicationandroid:label= "@string/app_name"Android:icon= "@drawable/icon"Android:name= "COM.ORM.SUGARAPP">    .    . <Meta-dataandroid:name= "DATABASE"Android:value= "Sugar_example.db"/>    <Meta-dataandroid:name= "VERSION"Android:value= "2"/>    <Meta-dataandroid:name= "Query_log"Android:value= "true"/>    <Meta-dataandroid:name= "Domain_package_name"Android:value= "Com.example.bean"/>    .    . </Application>

The four meta-data respectively identified:
    1. The file name of the database DB created will create the corresponding file under/data/data/{your app package name}/databases
    2. Database version number
    3. Whether to allow Sugarorm log log
    4. Path to the package where the bean corresponding to the database table is created
For the 4th need to emphasize some, sugarorm is through a bean file to create a table, such as you want to Sugar_ Create a table called goods in example.db, then you need to create a Goods.java bean file in the Com.example.bean you specified above, and then you will automatically create this empty table in db when you compile and run. Here are the specifics: for example, your Goods.java needs to write:
 Public classGoodsextendsSugarrecordImplementsSerializable {/*** Item Number*/@Column (Name= "sku_id", unique =true) @ExposePrivateString skuId; /*** Product number*/@ExposePrivateString Spuid; /*** Specifications*/@Expose @IgnorePrivateString Specvalue; /*** Item Name*/@ExposePrivateString name; /*** Item No.*/@ExposePrivateString bn; /*** cost price, input price*/@ExposePrivateBigDecimal cost; /*** Price*/@ExposePrivateBigDecimal Price;  PublicString Getskuid () {returnskuId; }     Public voidSetskuid (String skuId) { This. SkuId =skuId; }     PublicString Getspuid () {returnSpuid; }     Public voidSetspuid (String spuid) { This. Spuid =Spuid; }     PublicString Getspecvalue () {returnSpecvalue; }     Public voidSetspecvalue (String specvalue) { This. Specvalue =Specvalue; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString getbn () {returnbn; }     Public voidsetbn (String bn) { This. bn =bn; }     PublicBigDecimal Getcost () {returnCost ; }     Public voidsetcost (BigDecimal cost) { This. Cost =Cost ; }     PublicBigDecimal GetPrice () {returnPrice ; }     Public voidSetprice (BigDecimal price) { This. Price =Price ; }}

This is a description of a commodity Bean,sugar will be automatically created in the DB goods this table, the fields in the table and the property names in the Goods.java correspond, here are the points to note:
  1. The Bean's property name is named after the hump, and the uppercase letters are converted to underscores in the created table. For example, Spuid This property corresponds to a field in the table named spu_id
  2. Serializable is implemented because the bean serves not only to create tables for sugarorm in the code, Also to be able to pass in the Android components (such as handler in the Message.obj) and use, so here and the official website directly inherit from sugarrecord<t> different, recommend everybody use my this way
  3. @Column This note means that you want to force the name of the corresponding field in the table according to your specified name, so the field name of the Skuid in the goods table is not the default sku_id, but your own sku_id
  4. @Expoes is an annotation from Gson, which will be said later
  5. @Ignore This annotation emphasizes that this property does not create a corresponding field in the table
Sugarorm simplifies database additions and deletions by using save (), delete (), T.findbyid (), T.listall () and more: Add a single piece of data:
New Goods (); Good.setname ("Coffee"); Good.setcost (new BigDecimal); GOOD.SETBN ( "123456"); Good.save ();
Query one piece of data:
Goods Loadgood =goods.findbyid (Goods.  Class, 1);
To query the entries in all tables:
List<goods> Goods =goods.listall (Goods.  Class);

Update One piece of data :
Goods good2 = Goods.findbyid (Goods.  Class, 1); Good2.setname ("Rice"); Good2.save () ;

Delete a piece of data:
Goods good2 = Goods.findbyid (Goods.  Class, 1); Good2.delete ();
Delete all entries in the table:
Goods.deleteall (Goods.  Class);
conditional query operation for Sugarorm Queries can be made directly from the provided find and Findwithquery:
Goods.find (Goods.  Class, "name =?" and skuId =? "," Coffee "," 123 ");

If you have other operations such as GroupBy, order by, limit, and so on, the specific find interface format is:
Find (class<t> type, string whereclause, string[] Whereargs, String groupBy, string-by-clause, string limit)
Query via Findwithquery interface:
List<note> notes = Note.findwithquery (Note.  Class, "select * from Note where name =?", "Satya");

Sugarorm also provides the API for conditional queries, called Query Builder, which is currently in the beta version:
Select.from (Testrecord.  Class). WHERE (Condition.prop ("test"). EQ ("Satya"), Condition.prop ("prop"). EQ (2)). List ( );
Sugarorm One-to-many use Usually in development, one of the fields in a table corresponds to another table, which in the Java class is a pair of related relationships, Sugarorm is also supported here. For example, there is a operator field in the goods table, which shows the person responsible for this product
 Public classOperatorextendsSugarrecordImplementsSerializable {String userName;    String gender;  PublicString GetUserName () {returnUserName; }     Public voidsetusername (String userName) { This. UserName =UserName; }     PublicString Getgender () {returngender; }     Public voidSetgender (String gender) { This. Gender =gender; }}

This operator attribute can be added to the Goods.java, so the goods table will also add such a field
 Public class extends Implements Serializable {    ...         Private Operator Operator;      Public Operator Getoperator () {        return  Operator;    }      Public void setoperator (Operator Operator) {        this. Operator= Operator;    } ...}

Here's how to query:
list<goods> Goods = Goods.find (Goods.  Classnew String{operator.getname ()});
Or
Goods good = Goods.findbyid (Goods.  Class, 1= Good.getoperator ();

Bean Reusable Gson bean in Sugarorm The biggest benefit of sugarorm is that the bean used to create the table is something you can define, which is self-evident relative to Greendao. Greendao automatically helps you create a bean class, but if you need to parse the JSON data that the network pulls down, then there is a problem. We know that Gson also parses JSON data through bean objects, but Gson supports adding annotations to attributes in the bean (such as the @expose annotation). So here you might think that the bean used to parse the JSON and the beans used to store the database can be shared, so the bean that stores the database will not have the ORM framework automatically generated because it needs to add some gson or other frame annotations. So, Geendao can't use it.areas of attention in development
    • Command issues
    • Issues with Database changes
The first issue is the one mentioned at the beginning of this articleThe name of the Bean is used for hump naming, so uppercase letters are converted to underscores in the created table."This problem, from Sugarorm published in the source can see it is added to the" _ "and not a bug, here may be to want to and Java Web Some development way to be consistent, This is probably the strategy introduced to circumvent the various problems that SQLite is sensitive to case sensitivity. So developers should be aware of the naming changes when using Sugarorm. You write a property name in the Bean, and the field name in the database is not. Of course, this can be done by @column annotations . The second problem is a habitual one. In development due to the need not to directly manipulate sqlitedatabase this type of class, so many people at the same time when the development of a person to commit the code only modified the corresponding bean structure of the table he is responsible for, and this time you update the code after reinstalling the APK will find an error, For example, you cannot find the wrong field for a table. This is because the table structure is changed, so you have to uninstall the original app and reinstall the APK. So it's best to develop a habit when people develop: someone modifies a bean (that is, the table structure is updated) make sure to notify others



Quickly develop Android Internet clients that need to sync and save large amounts of data with Sugarorm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.