A brief analysis of the--litepal frame of the son of Aunt Guo (i.)

Source: Internet
Author: User
Tags sqlite database

Recently saw the Guo Shen of the litepal frame feel leng , Good, but also very curious how he realized , Curiosity kills the cat ! Follow the footsteps of the great God , See source .

1. When using the Litepal framework , Create a new litepal.xml under the project's assets directory File , including the name , version , and mapping of the database, So how does it go about mapping these things in ?

Paste the Litepal.xml code first:

<?xml version= "1.0" encoding= "Utf-8"?><litepal>    <!--database name--    <dbname value= "Demo" >    </dbname>    <!--database version    --<version value= "1" >    </version>    <!--mapping model-    <list>        <mapping class= "Com.sdufe.thea.guo.model.News" >        </mapping>    < /list></litepal>

The following is the property code in the litepal.xml corresponding function:

/* Copyright (C) Tony Green, Litepal Framework Open Source Project * * Licensed under the Apache License, Version 2.0 ( The "License"); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package Org.litepal.parser;import Java.util.arraylist;import Java.util.list;import Org.litepal.exceptions.invalidattributesexception;import Org.litepal.util.const;import Org.litepal.util.sharedutil;import android.text.textutils;/** * The object model for the Litepal.xml file. Once database connection happens, * Litepal'll try to analysis of the litepal.xml, and read all the AttriBute into * The LITEPALATTR model for further usage. * * @author Tony Green * @since 1.0 */public Final class Litepalattr {/** * static Litepalattr object. */private static L Itepalattr litepalattr;/** * The version of the database. */private Int version;/** * The name of the database. */private String dbname;/** * The case of table names and column names and SQL. */private String cases;/** * All the model classes this want to map in the database. Each class should * is given the full name including package name. */private list<string> classnames;/** * Do not allow new a Litepalattr object. Makes it a singleton class. */private litepalattr () {}/** * provide a to get the object of Litepalattr class. * * @return The Singleton object of litepalattr */public static litepalattr getinstance () {if (litepalattr = = null) {Sync Hronized (Litepalattr.class) {if (litepalattr = = null) {litepalattr = new litepalattr ();}}} return litepalattr;} public int getversion () {return version;} void Setversion (int version) {this.version = version;} Public String Getdbname () {return dbName;} void Setdbname (String dbName) {this.dbname = DbName;} /** * Get the class name list. Always add Table_schema as a value. * * @return the class name list. */public list<string> Getclassnames () {if (classnames = = null) {classnames = new arraylist<string> (); Classnames.add ("Org.litepal.model.Table_Schema");} else if (Classnames.isempty ()) {Classnames.add ("Org.litepal.model.Table_Schema");} return classnames;} /** * Add A class name into the current mapping model list. * * @param className * Full Package class name. */void addclassname (String className) {getclassnames (). Add (className);} Public String getcases () {return cases;} void Setcases (String cases) {this.cases = cases;} /** * Before application build the connection with database, check the fields * in Litepalattr. If All is passed, the connection would be * continued. If anyone of them doesn ' t pass, an exception would be throWn. * * @return If All of the fields is passed, return true. If dbname is * Undefined, or version was less than 1, or version was earlier than * current version, throw I Nvalidattributesexception * * @throws invalidattributesexception */public boolean checkselfvalid () {if ( Textutils.isempty (DbName)) {throw new Invalidattributesexception (invalidattributesexception.dbname_is_empty_or_ not_defined);} if (!dbname.endswith (Const.LitePal.DB_NAME_SUFFIX)) {dbName = DbName + Const.LitePal.DB_NAME_SUFFIX;} if (version < 1) {throw new Invalidattributesexception (Invalidattributesexception.version_of_database_less_than_ one);} if (Version < Sharedutil.getlastversion ()) {throw new Invalidattributesexception ( invalidattributesexception.version_is_earlier_than_current);} if (textutils.isempty (cases)) {cases = Const.LitePal.CASES_LOWER;} else {if (!cases.equals (Const.LitePal.CASES_UPPER) &&!cases.equals (Const.LitePal.CASES_LOWER) &&!cases.equals (Const.LitePal.CASES_KEEP){throw new Invalidattributesexception (cases+ invalidattributesexception.cases_value_is_invalid);}} return true;}}
This is the attribute in the corresponding XML file in the Guo Go code, so how do you map it? It should not be the same as the corresponding on the other, continue to see the source

There is a function in parsing the XML file:

/** * Analyze Litepal.xml, and store the analyzed result in Litepalparser. Use * Domparse to parse the configuration file as default. SAXParser and * Xmlpullparser are also optional, but not visible to developers. */public static void Parselitepalconfiguration () {if (parser = = NULL) {parser = new Litepalparser ();} Parser.usesaxparser ();}

From the function name guessed that the use of Sax parsing XML, can not be random guess, continue to see Guo Go source code,go to Usesaxparser () and see how it all came true.

/** * Use SAXParser to parse the Litepal.xml file. It'll get the parsed * result from Litepalcontenthandler and stored in the instance of * litepalattr. * * Note While analyzing litepal.xml file, Parseconfigurationfileexception * could is thrown. Be careful of writing Litepal.xml file, or Developer ' s * application is crash. */void Usesaxparser () {Litepalcontenthandler handler = null;try {SAXParserFactory factory = Saxparserfactory.newinstance (); XMLReader XMLReader = Factory.newsaxparser (). Getxmlreader (); handler = new Litepalcontenthandler (); Xmlreader.setcontenthandler (handler); Xmlreader.parse (New InputSource (Getconfiginputstream ())); return;} catch (Notfoundexception e) {throw new Parseconfigurationfileexception (Parseconfigurationfileexception.can_not_find _litepal_file);} catch (Saxexception e) {throw new Parseconfigurationfileexception (Parseconfigurationfileexception.file_format_is_ Not_correct);} catch (Parserconfigurationexception e) {throw new Parseconfigurationfileexception (Parseconfigurationfileexception.parse_config_failed);} catch (IOException e) {throw new parseconfigurationfileexception (parseconfigurationfileexception.io_exception);}}

Yes, you are not wrong, the above is the format of Sax parsing XML, using SAX parsing XML is almost this format, different in that handler, of course, the code of Guo Shen is quite normative, to the great God learning, Want to know how he resolved litepal.xml or continue to see the realization of handler it! Here only the main code, can not be made very long, long is not very good ha!

/** * Start Analysis the Litepal.xml file. Set all the parsed value into the * litepalattr model. */@Overridepublic void startelement (String uri, String localname, String qName, Attributes Attributes) throws saxexception {if (LitePalParser.NODE_DB_NAME.equalsIgnoreCase (LocalName)) {for (int i = 0; i < attributes.getlength () ; i++) {if (LitePalParser.ATTR_VALUE.equalsIgnoreCase (Attributes.getlocalname (i))) {Litepalattr.setdbname ( Attributes.getvalue (i). Trim ());}}} else if (LitePalParser.NODE_VERSION.equalsIgnoreCase (LocalName)) {for (int i = 0; i < attributes.getlength (); i++) {if (LitePalParser.ATTR_VALUE.equalsIgnoreCase (Attributes.getlocalname (i))) {litepalattr.setversion (Integer.parseint (Attributes.getvalue (i). Trim ()));}}} else if (LitePalParser.NODE_MAPPING.equalsIgnoreCase (LocalName)) {for (int i = 0; i < attributes.getlength (); i++) {if (LitePalParser.ATTR_CLASS.equalsIgnoreCase (Attributes.getlocalname (i))) {Litepalattr.addclassname (Attributes.getvalue (i). Trim ());}}} else IF (LitePalParser.NODE_CASES.equalsIgnoreCase (LocalName)) {for (int i = 0; i < attributes.getlength (); i++) {if (Litepal Parser.ATTR_VALUE.equalsIgnoreCase (Attributes.getlocalname (i))) {litepalattr.setcases (Attributes.getvalue (i)). Trim ());}}}
The above is handler parsing content, according to the starting element to explain the starting element, the personal guess, since it is using SAX parsing XML, you can have a number of lite tags, so I think you can use the Litepal framework can build multiple databases, But Litepal is inherited from the SQLite database, generally an app should not have a lot of databases, it is very small! Of course, the source code is also useful in the pull parsing XML, here also paste the code

/** * Use Xmlpullparser to parse the Litepal.xml file. It'll store the result * in the instance of Litepalattr. * * Note While analyzing litepal.xml file, Parseconfigurationfileexception * could is thrown. Be careful of writing Litepal.xml file, or Developer ' s * application is crash. */void Usepullparse () {try {litepalattr litepalattr = litepalattr.getinstance (); Xmlpullparserfactory factory = Xmlpullparserfactory.newinstance (); Xmlpullparser Xmlpullparser = Factory.newpullparser (); Xmlpullparser.setinput (Getconfiginputstream (), "UTF-8"); int EventType = Xmlpullparser.geteventtype (); while (eventtype! = xmlpullparser.end_document) {String NodeName = Xmlpullparser.getname (); switch (eventtype) {case Xmlpullparser.start_tag: {if (Node_db_name.equals (NodeName)) { String dbName = Xmlpullparser.getattributevalue ("", Attr_value); Litepalattr.setdbname (dbName);} else if (node_version.equals (NodeName)) {String VERSION = Xmlpullparser.getattributevalue ("", attr_value); Litepalattr.setversion (InteGer.parseint (version));} else if (node_mapping.equals (NodeName)) {String className = Xmlpullparser.getattributevalue ("", Attr_class); Litepalattr.addclassname (className);} else if (node_cases.equals (NodeName)) {String CASES = Xmlpullparser.getattributevalue ("", attr_value); Litepalattr.setcases (cases);} break;} Default:break;} EventType = Xmlpullparser.next ();}} catch (Xmlpullparserexception e) {throw new Parseconfigurationfileexception (Parseconfigurationfileexception.file_ Format_is_not_correct);} catch (IOException e) {throw new parseconfigurationfileexception (parseconfigurationfileexception.io_exception);}}

Of course know the analytic method, know the property corresponding function, then how did he find the litepal.xml? No hurry, let's keep looking.

/** * Iterates all files in the root of assets folder. If Find Litepal.xml, * Open this file and return the input stream. Or throw * parseconfigurationfileexception.  *  * @return The input stream of litepal.xml. * @throws ioexception */private inputstream Getconfiginputstream () throws IOException {Assetmanager Assetmanager = Litepalapplication.getcontext (). Getassets ();  string[] FileNames = Assetmanager.list (""); if (fileNames! = null && filenames.length > 0) {for (String fileName : fileNames) {if (Const.LitePal.CONFIGURATION_FILE_NAME.equalsIgnoreCase (FileName)) {return Assetmanager.open ( FileName, Assetmanager.access_buffer);}}} throw new Parseconfigurationfileexception (Parseconfigurationfileexception.can_not_find_litepal_file);}

This is the way he found local litepal.xml, through Getassets () read the local asset inside the file, the file name and Const.LitePal.CONFIGURATION_FILE_NAME contrast, The same words to the local documents, of course, I also have a question, whether I can make a name? Here of course, because asset can have a lot of files, he does not know which one to use, here Guo Go directly write dead, file name can only be called Litepal.xml

public static final String configuration_file_name = "Litepal.xml";
See this, you should probably connect to Guo Go is how to operate litepal.xml, rationale, first you use the Litepal framework to introduce the package, you need to build a litepal.xml file, Guo Go through Getasset () read to the local asset folder file name, By comparing with the Litepal.xml file name, get the content inside, use sax to parse the local file, get the contents of the file, assign value to litepalattr.

2. In the use of the Litepal Framework , it is necessary to configure the androidmanifest.xml Add android:name= "org.litepal.LitePalApplication" in Application Then we might as well start from litepalapplication.

public class Litepalapplication extends application {/** * Global application context. */private Static Context mcontext;/ * * Construct of litepalapplication. Initialize application Context. */public litepalapplication () {mcontext = this;} /** * Get the global application context.  *  * @return Application context. * @throws globalexception */public static Context GetContext () {if (Mcontext = = null) {throw new globalexception (Globalexception.application_context_is_null);} return mcontext;} @Overridepublic void Onlowmemory () {super.onlowmemory (); mcontext = Getapplicationcontext ();}}

Guo Go here in order to facilitate the user multiple callscontext,will beContextconfigured toandroidmanifest.xml , context Span style= "font-family: Arial" > assignment Notice here that Guo Go in order to prevent context empty So in onlowmemory context Assignment Span style= "font-family:arial". great God is worthy of the great god so witty protection measures

Today, to know how to funeral, please listen to the next explanation!








A brief analysis of the--litepal frame of the son of Aunt Guo (i.)

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.