Android生成テーブルに対応するクラスとアクセステーブルに対応するクラス


これまでの紙面でも、Androidを開発したプロジェクトの中で、手書き表に対応する種類と訪問表に対応する種類は、大量に重複した作業であり、属性、set方法、get方法、ラベルCurorからデータを取得して表の対応する対象に保存し、表の対応する対象をContentValuesに保存し、開発の中でこれらのコードに時間を浪費する必要はないと思います.だから、ネットで探しました.上記の二つの種類のツールを生成したかどうかを見ましたが、見つけられませんでした.そして、自分で3日間以上の時間をかけて自分で書きました.
主な実現メカニズムはXMLファイルをカスタマイズしています.このXMLには表、列などの属性があります.解析的に作成するために必要なものがあります.
カスタムXMLをより完璧にするために、自分でDMDを勉強しました.今書いたDMDは完璧ではないかもしれません.簡単な表を作るために必要な要素だけです.
コードを貼り付けて、みんなと共有して、みんなの助けのもとでこの東をもっと完璧にしたいです. 
 
package com.jingtuo.android.common.db;

import java.util.List;
import java.util.Map;

/**
 *    
 * @author JingTuo
 *
 */
public class JtSqlite {
	
	private String name;
	
	private List<Table> tables;
	
	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}
	

	public List<Table> getTables() {
		return tables;
	}


	public void setTables(List<Table> tables) {
		this.tables = tables;
	}

	/**
	 *  
	 * @author JingTuo
	 *
	 */
	public static class Table {
		
		private List<Column> columns;
		
		private Map<String, String> attributes;

		private String primarykey;
		
		public List<Column> getColumns() {
			return columns;
		}

		public void setColumns(List<Column> columns) {
			this.columns = columns;
		}

		public Map<String, String> getAttributes() {
			return attributes;
		}

		public void setAttributes(Map<String, String> attributes) {
			this.attributes = attributes;
		}


		public String getPrimarykey() {
			return primarykey;
		}

		public void setPrimarykey(String primarykey) {
			this.primarykey = primarykey;
		}


		/**
		 *   
		 * @author JingTuo
		 *
		 */
		public static class Column{
		
			private String javaType;
						
			private Map<String, String> attributes;
			
			public String getJavaType() {
				return javaType;
			}

			public void setJavaType(String javaType) {
				this.javaType = javaType;
			}

			public Map<String, String> getAttributes() {
				return attributes;
			}

			public void setAttributes(Map<String, String> attributes) {
				this.attributes = attributes;
			}

		}
	}
}
 
package com.jingtuo.android.common.db;

import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;

import com.jingtuo.android.common.db.JtSqlite.Table;
import com.jingtuo.android.common.db.JtSqlite.Table.Column;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 *          、       、        <br>
 *  Android   ,      <br>
 *  Web     (   Win32)   ,      ,       ,      sqlitejdbc.jar sqlitejdbc.dll。
 * 
 * @author JingTuo
 * 
 */
public class JtSqliteUtils {

	public static final String TAG_DB = "db";
	public static final String TAG_TABLE = "table";
	public static final String TAG_COLUMN = "column";
	public static final String TAG_PRIMARYKEY = "primary_key";

	public static final String ATTR_NAME = "name";
	public static final String ATTR_DATATYPE = "datatype";
	public static final String ATTR_COMMENT = "comment";
	public static final String ATTR_DEFAULT = "default";
	public static final String ATTR_CONSTRAINT = "constraint";
	public static final String ATTR_COLUMN = "column";

	private static String path;
	
	/**
	 *          
	 * @param path
	 */
	public static void setPath(String path) {
		JtSqliteUtils.path = path;
	}

	/**
	 * 
	 * @param path
	 * @param sqls
	 */
	public static void createDB(String path, List<String> sqls) {
		SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null, null);
		if (sqls != null && sqls.size() >= 1) {
			for (int i = 0; i < sqls.size(); i++) {
				db.execSQL(sqls.get(i));
			}
		}
		JtSqliteUtils.path = path;
	}

	/**
	 *        
	 * 
	 * @return
	 */
	public static SQLiteDatabase getRoDb() {
		return SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
	}

	/**
	 *        
	 * 
	 * @return
	 */
	public static SQLiteDatabase getRwDb() {
		return SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);
	}

	/**
	 *   xmlpullparser       
	 * 
	 * @param xmlPath
	 * @return
	 */
	public static JtSqlite getDB(Context context, int xmlId) {
		JtSqlite db = new JtSqlite();
		try {
			XmlPullParser parser = context.getResources().getXml(xmlId);
			int eventType = parser.getEventType();
			String startTag = null;
			String endTag = null;
			List<Table> tables = new ArrayList<Table>();
			Table table = null;
			Column column = null;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					eventType = parser.next();
					break;
				case XmlPullParser.START_TAG:
					startTag = parser.getName();
					if (startTag.equals(TAG_DB)) {//      
						db.setName(getValue(parser, ATTR_NAME));
					} else if (startTag.equals(TAG_TABLE)) {//    
						table = new Table();
						Map<String, String> map = new HashMap<String, String>();
						for (int i = 0; i < parser.getAttributeCount(); i++) {
							map.put(parser.getAttributeName(i), parser.getAttributeValue(i));
						}
						table.setAttributes(map);
						table.setColumns(new ArrayList<Column>());
					} else if (startTag.equals(TAG_COLUMN)) {//     
						column = new Column();
						Map<String, String> map = new HashMap<String, String>();
						for (int i = 0; i < parser.getAttributeCount(); i++) {
							map.put(parser.getAttributeName(i), parser.getAttributeValue(i));
						}
						column.setAttributes(map);
						table.getColumns().add(column);
					} else if (startTag.equals(TAG_PRIMARYKEY)) {
						String name = parser.getAttributeName(0);
						if (name.equals(ATTR_COLUMN)) {
							table.setPrimarykey(parser.getAttributeValue(0));
						}
					} else {//         

					}
					eventType = parser.next();
					break;
				case XmlPullParser.END_TAG:
					endTag = parser.getName();
					if (endTag.equals(TAG_TABLE)) {
						tables.add(table);
					}
					eventType = parser.next();
					break;
				case XmlPullParser.TEXT:
					eventType = parser.next();
					break;
				default:
					break;
				}
			}
			db.setTables(tables);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return db;
	}

	/**
	 *   dom         
	 * 
	 * @param xmlPath
	 * @return
	 */
	public static JtSqlite getDBbyDomParser(String xmlPath) {
		JtSqlite db = new JtSqlite();
		try {
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(new File(xmlPath));
			Element root = document.getDocumentElement();
			db.setName(root.getAttribute(ATTR_NAME));
			List<Table> tables = new ArrayList<Table>();
			NodeList tableList = root.getChildNodes();
			Node tableNode = null;
			Node child = null;
			if (tableList != null && tableList.getLength() >= 1) {
				for (int i = 0; i < tableList.getLength(); i++) {
					tableNode = tableList.item(i);
					if (TAG_TABLE.equals(tableNode.getNodeName())) {
						Table table = new Table();
						//     
						table.setAttributes(getAttributes(tableNode));
						//     
						NodeList columnList = tableNode.getChildNodes();
						List<Column> columns = new ArrayList<Column>();
						if (columnList != null && columnList.getLength() >= 1) {
							for (int j = 0; j < columnList.getLength(); j++) {
								child = columnList.item(j);
								if (TAG_COLUMN.equals(child.getNodeName())) {
									Column column = new Column();
									column.setAttributes(getAttributes(child));
									column.setJavaType(toJavaType(column.getAttributes().get(ATTR_DATATYPE)));
									columns.add(column);
								} else if (TAG_PRIMARYKEY.equals(child.getNodeName())) {
									table.setPrimarykey(getAttributes(child).get(ATTR_COLUMN));
								} else {
									continue;
								}
							}
						}
						table.setColumns(columns);
						tables.add(table);
					} else {
						continue;
					}
				}
			}
			db.setTables(tables);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return db;
	}

	/**
	 *   xml id       sql
	 * 
	 * @param file
	 */
	public static List<String> createSQL(JtSqlite db) {
		List<String> list = new ArrayList<String>();
		try {
			StringBuilder stringBuilder = null;
			List<Table> tables = db.getTables();
			if (tables != null && tables.size() >= 1) {
				for (int i = 0; i < tables.size(); i++) {
					Table table = tables.get(i);
					stringBuilder = new StringBuilder();
					stringBuilder.append("CREATE TABLE IF NOT EXISTS " + table.getAttributes().get(ATTR_NAME) + "(");
					List<Column> columns = table.getColumns();
					if (columns != null && columns.size() >= 1) {
						for (int j = 0; j < columns.size(); j++) {
							Column column = columns.get(j);
							//    
							String name = column.getAttributes().get(ATTR_NAME);
							if (name != null) {
								stringBuilder.append(name);
							}
							//     
							String type = column.getAttributes().get(ATTR_DATATYPE);
							if (type != null) {
								stringBuilder.append(" " + type);
							}
							//     
							String constraint = column.getAttributes().get(ATTR_CONSTRAINT);
							if (constraint != null) {
								if (constraint.equals("NOTNULL")) {
									constraint = "NOT NULL";
								}
								stringBuilder.append(" " + constraint);
							}
							String def = column.getAttributes().get(ATTR_DEFAULT);
							if (def != null) {
								stringBuilder.append(" DEFAULT(" + def + ")");
							}
							stringBuilder.append(",");
						}
					}
					String sql = null;
					if (table.getPrimarykey() != null) {
						stringBuilder.append("PRIMARY KEY(" + table.getPrimarykey() + ")");
						stringBuilder.append(")");
						sql = stringBuilder.toString();
					} else {
						sql = stringBuilder.toString();
						sql = sql.substring(0, sql.length() - 1) + ")";
					}
					list.add(sql);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/**
	 *                       ,          
	 * 
	 * @param xmlPath
	 * @param srcPath
	 * @param packageName
	 */
	public static void createClass(String xmlPath, String srcPath, String packageName) {
		try {
			String packagePath = null;
			File packageFile = null;
			if (srcPath.endsWith("\\") || srcPath.endsWith("/")) {
				srcPath = srcPath.substring(0, srcPath.length() - 1);
			}
			if (packageName != null) {
				packagePath = srcPath + "/" + packageName.replaceAll("\\.", "/");
			} else {
				packagePath = srcPath;
			}
			packageFile = new File(packagePath);
			if (!packageFile.exists()) {//        
				packageFile.mkdirs();
			} else {//       ,         
				File[] files = packageFile.listFiles();
				for (int i = 0; i < files.length; i++) {
					if (files[i].exists()) {
						files[i].delete();
					}
				}
			}
			//     
			File tableFolder = new File(packageFile, "table");
			File accessFolder = new File(packageFile, "access");
			tableFolder.mkdir();
			accessFolder.mkdir();

			JtSqlite db = getDBbyDomParser(xmlPath);
			List<Table> tables = db.getTables();
			if (tables == null || tables.size() <= 0) {
				return;
			}

			//        
			for (int i = 0; i < tables.size(); i++) {
				Table table = tables.get(i);
				Map<String, String> tableAttributes = table.getAttributes();
				String tableName = tableAttributes.get(ATTR_NAME);
				String className = firstUpperCase(tableName) + "Base";
				String comment = tableAttributes.get(ATTR_COMMENT);
				if (comment == null) {
					comment = "";
				}

				//      -- 
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append("package " + packageName + ".table;

"); stringBuilder.append("/**
"); stringBuilder.append(" * primary key(" + table.getPrimarykey() + ")
"); stringBuilder.append(" * " + comment + "
"); stringBuilder.append(" * @author JingTuo
"); stringBuilder.append(" */
"); stringBuilder.append("public class " + className + " {

"); List<Column> columns = table.getColumns(); if (columns != null && columns.size() >= 1) { for (int j = 0; j < columns.size(); j++) { Column column = table.getColumns().get(j); Map<String, String> columnAttributes = column.getAttributes(); String columnName = columnAttributes.get(ATTR_NAME); // comment = columnAttributes.get(ATTR_COMMENT); if (comment == null) { comment = ""; } // String def = columnAttributes.get(ATTR_DEFAULT); if (def == null) { if ("String".equals(column.getJavaType()) || "byte[]".equals(column.getJavaType())) { def = "null"; } else if ("int".equals(column.getJavaType())) { def = "0"; } else if ("float".equals(column.getJavaType())) { def = "0.0f"; } else { def = "null"; } } stringBuilder.append("\t/**
"); stringBuilder.append("\t *" + comment + "
"); stringBuilder.append("\t */
"); stringBuilder.append("\tprivate " + column.getJavaType() + " " + columnName + " = " + def + ";

"); stringBuilder.append("\tpublic void set" + firstUpperCase(columnName) + "(" + column.getJavaType() + " " + columnName + "){
"); stringBuilder.append("\t\tthis." + columnName + " = " + columnName + ";
"); stringBuilder.append("\t}

"); stringBuilder.append("\tpublic " + column.getJavaType() + " get" + firstUpperCase(columnName) + "(){
"); stringBuilder.append("\t\treturn this." + columnName + ";
"); stringBuilder.append("\t}

"); } } stringBuilder.append("}"); File tableFile = new File(tableFolder, className + ".java"); packageFile.createNewFile(); FileWriter fileWriter = new FileWriter(tableFile); fileWriter.write(stringBuilder.toString()); fileWriter.flush(); fileWriter.close(); // -- stringBuilder = new StringBuilder(); stringBuilder.append("package " + packageName + ".access;

"); stringBuilder.append("import com.jingtuo.android.common.db.JtSqliteUtils;
"); stringBuilder.append("import com.jingtuo.android.db.table." + className + ";
"); stringBuilder.append("import android.content.ContentValues;
"); stringBuilder.append("import android.database.Cursor;
"); stringBuilder.append("import android.database.sqlite.SQLiteDatabase;
"); stringBuilder.append("import java.util.ArrayList;
"); stringBuilder.append("import java.util.List;

"); String accessClassName = firstUpperCase(tableName) + "AccessBase"; stringBuilder.append("
"); stringBuilder.append("/**
"); stringBuilder.append(" *
"); stringBuilder.append(" * @author JingTuo
"); stringBuilder.append(" */
"); stringBuilder.append("public class " + accessClassName + " {

"); String objName = firstLowerCase(tableName); // find stringBuilder.append("\tpublic static " + className + " find("); String primarykey = table.getPrimarykey(); String[] array = primarykey.split(","); String temp = ""; for (int j = 0; j < array.length; j++) { temp += getJavaType(array[j], table.getColumns()) + " " + array[j] + ","; } temp = temp.substring(0, temp.length() - 1); stringBuilder.append(temp + "){
"); stringBuilder.append("\t\t" + className + " " + objName + " = null;
"); stringBuilder.append("\t\tSQLiteDatabase db = null;
"); stringBuilder.append("\t\tCursor cursor = null;
"); stringBuilder.append("\t\ttry{
"); stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRoDb();
"); stringBuilder.append("\t\t\tcursor = db.query(\"" + tableName + "\",null,\""); // String where = ""; for (int j = 0; j < array.length; j++) { where += array[j] + "=? and "; } where = where.substring(0, where.length() - 5); stringBuilder.append(where + "\", new String[]{"); // temp = ""; for (int j = 0; j < array.length; j++) { temp += array[j] + " + \"\","; } temp = temp.substring(0, temp.length() - 1); stringBuilder.append(temp + "},null,null,null);
"); stringBuilder.append("\t\t\tif(cursor!=null&&cursor.moveToNext()){
"); stringBuilder.append("\t\t\t\t" + objName + " = toObject(cursor);
"); stringBuilder.append("\t\t\t}
"); stringBuilder.append("\t\t}catch(Exception e){
"); stringBuilder.append("\t\t\te.printStackTrace();
"); stringBuilder.append("\t\t}finally{
"); stringBuilder.append("\t\t\tif(cursor!=null){
"); stringBuilder.append("\t\t\t\tcursor.close();
"); stringBuilder.append("\t\t\t}
"); stringBuilder.append("\t\t\tif(db!=null){
"); stringBuilder.append("\t\t\t\tdb.close();
"); stringBuilder.append("\t\t\t}
"); stringBuilder.append("\t\t}
"); stringBuilder.append("\t\treturn " + objName + ";
"); stringBuilder.append("\t}

"); // stringBuilder.append("\tpublic static List<" + className + "> find(String where, String[] whereValues){
"); stringBuilder.append("\t\t" + className + " " + objName + " = null;
"); stringBuilder.append("\t\tSQLiteDatabase db = null;
"); stringBuilder.append("\t\tCursor cursor = null;
"); stringBuilder.append("\t\tList<" + className + "> result = new ArrayList<" + className + ">();
"); stringBuilder.append("\t\ttry{
"); stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRoDb();
"); stringBuilder.append("\t\t\tcursor = db.query(\"" + tableName + "\",null,where,whereValues,null,null,null);
"); stringBuilder.append("\t\t\twhile(cursor!=null&&cursor.moveToNext()){
"); stringBuilder.append("\t\t\t\t" + objName + " = toObject(cursor);
"); stringBuilder.append("\t\t\t\tresult.add(" + objName + ");
"); stringBuilder.append("\t\t\t}
"); stringBuilder.append("\t\t}catch(Exception e){
"); stringBuilder.append("\t\t\te.printStackTrace();
"); stringBuilder.append("\t\t}finally{
"); stringBuilder.append("\t\t\tif(cursor!=null){
"); stringBuilder.append("\t\t\t\tcursor.close();
"); stringBuilder.append("\t\t\t}
"); stringBuilder.append("\t\t\tif(db!=null){
"); stringBuilder.append("\t\t\t\tdb.close();
"); stringBuilder.append("\t\t\t}
"); stringBuilder.append("\t\t}
"); stringBuilder.append("\t\treturn result;
"); stringBuilder.append("\t}

"); // insert stringBuilder.append("\tpublic static void insert(" + className + " " + objName + "){
"); stringBuilder.append("\t\tSQLiteDatabase db = null;
"); stringBuilder.append("\t\ttry{
"); stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRwDb();
"); stringBuilder.append("\t\t\tdb.beginTransaction();
"); stringBuilder.append("\t\t\tdb.insert(\"" + tableName + "\", null, toValues(" + objName + "));
"); stringBuilder.append("\t\t\tdb.setTransactionSuccessful();
"); stringBuilder.append("\t\t}catch(Exception e){
"); stringBuilder.append("\t\t\te.printStackTrace();
"); stringBuilder.append("\t\t}finally{
"); stringBuilder.append("\t\t\tif(db!=null){
"); stringBuilder.append("\t\t\t\tdb.endTransaction();
"); stringBuilder.append("\t\t\t\tdb.close();
"); stringBuilder.append("\t\t\t}
"); stringBuilder.append("\t\t}
"); stringBuilder.append("\t}

"); // update stringBuilder.append("\tpublic static void update(" + className + " " + objName + "){
"); stringBuilder.append("\t\tSQLiteDatabase db = null;
"); stringBuilder.append("\t\ttry{
"); stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRwDb();
"); stringBuilder.append("\t\t\tdb.beginTransaction();
"); String whereValues = ""; for (int j = 0; j < array.length; j++) { whereValues += objName + ".get" + firstUpperCase(array[j]) + "() + \"\","; } whereValues = whereValues.substring(0, whereValues.length() - 1); stringBuilder.append("\t\t\tdb.update(\"" + tableName + "\", toValues(" + objName + "), \"" + where + "\", new String[]{" + whereValues + "});
"); stringBuilder.append("\t\t\tdb.setTransactionSuccessful();
"); stringBuilder.append("\t\t}catch(Exception e){
"); stringBuilder.append("\t\t\te.printStackTrace();
"); stringBuilder.append("\t\t}finally{
"); stringBuilder.append("\t\t\tif(db!=null){
"); stringBuilder.append("\t\t\t\tdb.endTransaction();
"); stringBuilder.append("\t\t\t\tdb.close();
"); stringBuilder.append("\t\t\t}
"); stringBuilder.append("\t\t}
"); stringBuilder.append("\t}

"); // delelte stringBuilder.append("\tpublic static void delete(String where, String[] whereValues){
"); stringBuilder.append("\t\tSQLiteDatabase db = null;
"); stringBuilder.append("\t\ttry{
"); stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRwDb();
"); stringBuilder.append("\t\t\tdb.beginTransaction();
"); stringBuilder.append("\t\t\tdb.delete(\"" + tableName + "\", where, whereValues);
"); stringBuilder.append("\t\t\tdb.setTransactionSuccessful();
"); stringBuilder.append("\t\t}catch(Exception e){
"); stringBuilder.append("\t\t\te.printStackTrace();
"); stringBuilder.append("\t\t}finally{
"); stringBuilder.append("\t\t\tif(db!=null){
"); stringBuilder.append("\t\t\t\tdb.endTransaction();
"); stringBuilder.append("\t\t\t\tdb.close();
"); stringBuilder.append("\t\t\t}
"); stringBuilder.append("\t\t}
"); stringBuilder.append("\t}

"); // toObject stringBuilder.append("\tpublic static " + className + " toObject(Cursor cursor){
"); stringBuilder.append("\t\t" + className + " " + objName + " = new " + className + "();
"); if (columns != null && columns.size() >= 1) { for (int j = 0; j < columns.size(); j++) { Column column = columns.get(j); String columnName = column.getAttributes().get(ATTR_NAME); stringBuilder.append("\t\t" + objName + ".set" + firstUpperCase(columnName) + "(cursor.get"); if (column.getJavaType().equals("byte[]")) { stringBuilder.append("Blob"); } else { stringBuilder.append(firstUpperCase(column.getJavaType())); } stringBuilder.append("(cursor.getColumnIndex(\"" + columnName + "\")));
"); } } stringBuilder.append("\t\treturn " + objName + ";
"); stringBuilder.append("\t}

"); // toValues stringBuilder.append("\tpublic static ContentValues toValues(" + className + " " + objName + "){
"); stringBuilder.append("\t\tContentValues values = new ContentValues();
"); stringBuilder.append("\t\tif(" + objName + "!=null){
"); if (columns != null && columns.size() >= 1) { for (int j = 0; j < columns.size(); j++) { Column column = columns.get(j); String columnName = column.getAttributes().get(ATTR_NAME); stringBuilder.append("\t\t\tvalues.put(\"" + columnName + "\", " + objName + ".get" + firstUpperCase(columnName) + "());
"); } } stringBuilder.append("\t\t}
"); stringBuilder.append("\t\treturn values;
"); stringBuilder.append("\t}

"); stringBuilder.append("}
"); File accessFile = new File(accessFolder, accessClassName + ".java"); fileWriter = new FileWriter(accessFile); fileWriter.write(stringBuilder.toString()); fileWriter.flush(); fileWriter.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * * * @param node * @return */ public static Map<String, String> getAttributes(Node node) { Map<String, String> map = new HashMap<String, String>(); if (node != null) { NamedNodeMap namedNodeMap = node.getAttributes(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Node attr = namedNodeMap.item(i); map.put(attr.getNodeName(), attr.getNodeValue()); } } return map; } /** * name * * @param parser * @param name * @return */ public static String getValue(XmlPullParser parser, String name) { if (parser != null && name != null && !name.equals("")) { for (int i = 0; i < parser.getAttributeCount(); i++) { if (name.equals(parser.getAttributeName(i))) { return parser.getAttributeValue(i); } } } return ""; } /** * Java * * @param dataType * @return */ public static String toJavaType(String dataType) { // String javaType = null; if ("TEXT".equals(dataType)) { javaType = "String"; } else if ("INTEGER".equals(dataType)) { javaType = "int"; } else if ("REAL".equals(dataType)) { javaType = "float"; } else if ("BLOB".equals(dataType)) { javaType = "byte[]"; } else { javaType = "Object"; } return javaType; } /** * Java * * @param columnName * @param columns * @return */ public static String getJavaType(String columnName, List<Column> columns) { if (columnName != null && !columnName.equals("") && columns != null && columns.size() >= 1) { for (int i = 0; i < columns.size(); i++) { if (columnName.equals(columns.get(i).getAttributes().get(ATTR_NAME))) { if (columns.get(i).getJavaType() == null) { return "Object"; } else { return columns.get(i).getJavaType(); } } } } return "Object"; } /** * * * @param source * @return */ public static String firstUpperCase(String source) { String result = null; if (source != null && !source.equals("")) { if (source.length() == 1) { result = source.substring(0, 1).toUpperCase(Locale.getDefault()); } else { result = source.substring(0, 1).toUpperCase(Locale.getDefault()) + source.substring(1); } } else { result = source; } return result; } /** * * * @param source * @return */ public static String firstLowerCase(String source) { String result = null; if (source != null && !source.equals("")) { if (source.length() == 1) { result = source.substring(0, 1).toLowerCase(Locale.getDefault()); } else { result = source.substring(0, 1).toLowerCase(Locale.getDefault()) + source.substring(1); } } else { result = source; } return result; } /** * * @param dbFilePath * * @param xmlPath * xml */ public static void createDbByJDBC(String dbFilePath, String xmlPath) { File dbFile = new File(dbFilePath); if (dbFile.exists()) { dbFile.delete(); } try { dbFile.createNewFile(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } JtSqlite db = getDBbyDomParser(xmlPath); Connection connection = null; Statement statement = null; List<String> sqls = createSQL(db); try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:" + dbFilePath); connection.setAutoCommit(true); statement = connection.createStatement(); statement.execute("CREATE TABLE IF NOT EXISTS android_metadata(locale TEXT)"); for (int i = 0; i < sqls.size(); i++) { statement.execute(sqls.get(i)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { File file = new File(""); System.out.println(file.getAbsolutePath()); JtSqliteUtils.createClass(file.getAbsolutePath() + "/res/xml/cq.xml", file.getAbsolutePath() + "/src", "com.jingtuo.android.db"); } }
 
 
<?xml version="1.0" encoding="UTF-8"?>

<!ENTITY % datatypes "(TEXT|INTEGER|REAL|BLOB)">
<!ENTITY % constraints "(NOTNULL|NULL|UNIQUE|COLLATE|CHECK)">

<!ELEMENT db  ( table+ )>
<!ATTLIST db
name CDATA #REQUIRED
>

<!ELEMENT table  ( column+ , primary_key?, foreign_key? )>
<!ATTLIST table
name CDATA #REQUIRED
comment CDATA #IMPLIED
>

<!ELEMENT primary_key  EMPTY>
<!ATTLIST primary_key
column CDATA #REQUIRED
>

<!ELEMENT foreign_key  EMPTY>
<!ATTLIST primary_key
column CDATA #REQUIRED
>

<!ELEMENT column  EMPTY>
<!ATTLIST column
name CDATA #REQUIRED
datatype %datatypes; #REQUIRED
constraint %constraints; #IMPLIED
default CDATA #IMPLIED
comment CDATA #IMPLIED
>
 
 
使用手順:
<1>DMDファイルを使ってデータベースxmlファイルを生成します.
<2>Jt SqlityUtils類のcreateClassを使って実体類を生成する