前面写了一篇android对sqllite的快速保存博客,今天我们来看看android与webservice的交互,相信很多有经验的人自然就想到了soap。但是如果在小型项目中,具有大材小用之嫌。实际上java本身就提供了一套可以与webservice交付的功能,也十分简单。因此对于小型项目而言,我们何不封装一下该方法。
下面我们来看下我们要做的内容:
1)从远程站点上获取数据。
2) 判断数据是否是json格式的,如果是那么我们能不能通过转换将json格式的直接转换为entity返回。如果不是json格式的,那么我们能不能返还回该值。
首先我们来解决第一点,andoird对数据的处理,都是放在多线程上面去所以我们建立一个AsyncTask来管理。
private static class NewsGetTask extends AsyncTask<String, IredeemError, String> { private ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.getInstance()); pDialog.setMessage("Please waiting..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected String doInBackground(String... params) { String url = params[0]; if(!URLUtil.isValidUrl(url)) { return IredeemApplication.getInstance().getString("UnConnection"); } String data = null; if (requestCache != null) { data = requestCache.get(url); if (data != null) { return data; } } // initialize HTTP GET request objects BasicHttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, 5000); HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = null; try { // execute request try { httpResponse = httpClient.execute(httpGet); } catch (UnknownHostException e) { return e.getMessage(); // throw wsError; } catch (SocketException e) { return e.getMessage(); // throw wsError; } // request data HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream inputStream = httpEntity.getContent(); data = convertStreamToString(inputStream); // cache the result // todo: remove out the cash if (requestCache != null) { requestCache.put(url, data); } } } catch (ClientProtocolException e) { return e.getLocalizedMessage(); } catch (IOException e) { return e.getMessage(); } return data; } protected void onPostExecute(String message) { pDialog.dismiss(); } }
我们在线程中率先验证一下URL是不是可用,URLUtil主要就是一个字符串匹配严重是否合法。接着我们设置一下连接的超时时间,然后再Try catch里面去获取该数据,并返回。第一步便完成了。这时候我们需要写个类来调用:调用方法如下:
public static String doGet(String url) { try { return (new NewsGetTask().execute(url)).get(); } catch (InterruptedException e) { return e.getMessage(); } catch (ExecutionException e) { return e.getMessage(); } }
整合下第一步将全部代码传上来:
package com.iredeem.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.concurrent.ExecutionException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.json.JSONObject; import com.iredeem.IredeemApplication; import com.iredeem.activity.MainActivity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; import android.webkit.URLUtil; /** * @author xie */ public class Caller { /** * Cache for most recent request */ private static RequestCache requestCache = null; /** * Performs HTTP GET using Apache HTTP Client v 4 * * @param url * @return * @throws WSError */ public static String doGet(String url) { try { return (new NewsGetTask().execute(url)).get(); } catch (InterruptedException e) { return e.getMessage(); } catch (ExecutionException e) { return e.getMessage(); } } private static Boolean isConnection(String urlString) { try { URL url = new URL(urlString); HttpURLConnection urlc = (HttpURLConnection) url .openConnection(); urlc.setRequestProperty("User-Agent", "Android Application:***"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds urlc.connect(); if (urlc.getResponseCode() == 200) { return true; } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } private static class NewsGetTask extends AsyncTask<String, IredeemError, String> { private ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.getInstance()); pDialog.setMessage("Please waiting..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected String doInBackground(String... params) { String url = params[0]; if(!URLUtil.isValidUrl(url)) { return IredeemApplication.getInstance().getString("UnConnection"); } String data = null; if (requestCache != null) { data = requestCache.get(url); if (data != null) { return data; } } // initialize HTTP GET request objects BasicHttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, 5000); HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = null; try { // execute request try { httpResponse = httpClient.execute(httpGet); } catch (UnknownHostException e) { return e.getMessage(); // throw wsError; } catch (SocketException e) { return e.getMessage(); // throw wsError; } // request data HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream inputStream = httpEntity.getContent(); data = convertStreamToString(inputStream); // cache the result // todo: remove out the cash if (requestCache != null) { requestCache.put(url, data); } } } catch (ClientProtocolException e) { return e.getLocalizedMessage(); } catch (IOException e) { return e.getMessage(); } return data; } protected void onPostExecute(String message) { pDialog.dismiss(); } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + " "); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public static void setRequestCache(RequestCache requestCache) { Caller.requestCache = requestCache; } public static String createStringFromIds(int[] ids) { if (ids == null) return ""; String query = ""; for (int id : ids) { query = query + id + "+"; } return query; } }
接着我们来解决第二步:
我们先建立一个BaseEntity的基类。
public class BaseEntity implements Serializable { private static final long serialVersionUID = 1L; public static final String DB_NAME = IredeemApplication.DataInformation.DB_NAME; private static final String Tag = "Base Entity"; public<T extends Serializable> void set(Class<T> clazz, String fieldName,Object obj) { Class<? extends BaseEntity> cls = this.getClass(); Field filed = null; try { filed = cls.getField(fieldName); filed.set(this, As(clazz, obj)); } catch (Exception e) { e.printStackTrace(); } } public<T extends Serializable> T get(Class<T> clazz, String fieldName) { Class<? extends BaseEntity> cls = this.getClass(); Field filed = null; try { filed = cls.getField(fieldName); } catch (NoSuchFieldException e) { e.printStackTrace(); } try { return As(clazz, filed.get(this)); } catch (IllegalArgumentException e) { Log.i(Tag, "IllegalArgumentException"); } catch (IllegalAccessException e) { Log.i(Tag, "IllegalAccessException"); } catch (Exception e) { Log.i(Tag, "Exception"); } return DefaultAs(clazz); } @SuppressWarnings("unchecked") private <T> T DefaultAs(Class<T> clazz) { if(clazz==String.class) return (T)" "; if(clazz==double.class) return (T)"0"; if(clazz==int.class) return (T)"0"; if(clazz==Date.class) return (T)new java.util.Date(); return null; } @SuppressWarnings("unchecked") private <T> T As(Class<T> clazz, Object object) { if(clazz==String.class) { if(object==null) return null; return (T)object.toString(); } if(clazz==double.class) { if(object==null) object=0; object= Double.parseDouble(object.toString()); } return (T)object; } }
这个类可以不要任何东西,这里我是在项目中用到了部分方法,便于大家调试没有挪掉。接着我们建立一个JsonBuilder的接口,用来提供将json转换为entity或者由entity 转换为json。
public interface JSONDataBaseBuilder<TEntity extends BaseEntity> { public abstract ContentValues deconstruct(TEntity entity); public abstract TEntity jsonBuild(JSONObject jsonObject) throws JSONException; public interface DataBaseBuilder<TEntity extends BaseEntity> extends JSONDataBaseBuilder<BaseEntity> { public abstract TEntity build(Cursor query); public abstract String table(); public abstract TEntity jsonBuild(JSONObject jsonObject) throws JSONException; } }
再来提供一个entity将返回的entity或者message进行组合一下:
public class DBHelperEntity<TEntity extends BaseEntity> { public String message; public TEntity tEntity; public Boolean getIsJsonData() { if(tEntity==null) return false; return true; } public Boolean FormatEntity(String jsonString) { return true; } }
如果我们返回的是list,那么我们也需要一个entity来封装一下:
public class DBHelperList<TEntity extends BaseEntity> { public ArrayList<TEntity> list; public String jsonString; public String message=""; public Boolean isURLError = false; public DBHelperList(String jsonString) { this.jsonString = jsonString; list = new ArrayList<TEntity>(); } public Boolean getIsJSONList() { if(list!=null && list.size()>0) return true; return false; } }
最后我们来封装下service类:
public class JSONServiceBase<TEntity extends BaseEntity> { private JSONDataBaseBuilder<TEntity> mBuilder; private Activity activity; public JSONServiceBase(Activity activity,JSONDataBaseBuilder<TEntity> builder) { this.activity = activity; mBuilder = builder; } public DBHelperList<TEntity> searchJsonForEntity(String doGetString) { String jsonString = doGet(doGetString); return new DBHelperList<TEntity>(jsonString); // JSONArray jsonArrayEntry = new JSONArray(jsonString); // return jsonArrayEntry; } public DBHelperList<TEntity> getJSonList(String doGetString){ DBHelperList<TEntity> list = searchJsonForEntity(doGetString); try { JSONArray jsonArrayEntry = new JSONArray(list.jsonString); list.list = getJSonList(jsonArrayEntry); return list; } catch (JSONException e) { list.message = list.jsonString; return list; } } public DBHelperList<TEntity> getJSonList(String doGetString,Map<String,String> searchMap) { return getJSonList(ServiceHelper.getPath(searchMap, doGetString)); } public ArrayList<TEntity> getJSonList(JSONArray jsonArrayEntities) { int n = jsonArrayEntities.length(); ArrayList<TEntity> entities = new ArrayList<TEntity>(); for(int i=0; i < n; i++){ try { entities.add(mBuilder.jsonBuild(jsonArrayEntities.getJSONObject(i))); } catch (JSONException e) { e.printStackTrace(); } } return entities; } public DBHelperEntity<TEntity> getDbHelperEntity(String doGetString) { String jsonString = doGet(doGetString); JSONObject jObject; DBHelperEntity<TEntity> rtnEntity = new DBHelperEntity<TEntity>(); try { try { jObject = new JSONObject(jsonString); } catch (JSONException e) { rtnEntity.message = IredeemApplication.getInstance().getString(jsonString); return rtnEntity; } try { rtnEntity.tEntity = mBuilder.jsonBuild(jObject); } catch (JSONException e) { rtnEntity.message = e.getLocalizedMessage(); } } catch (Exception e) { rtnEntity.message=e.getMessage(); } return rtnEntity; } public DBHelperEntity<TEntity> getDbHelperEntity(String doGetString,Map<String, String> searchMap) { String jsonString = doGet(ServiceHelper.getPath(searchMap, doGetString)); JSONObject jObject; DBHelperEntity<TEntity> rtnEntity = new DBHelperEntity<TEntity>(); try { try { jObject = new JSONObject(jsonString); } catch (JSONException e) { rtnEntity.message = IredeemApplication.getInstance().getString(jsonString); return rtnEntity; } try { rtnEntity.tEntity = mBuilder.jsonBuild(jObject); } catch (JSONException e) { rtnEntity.message = e.getLocalizedMessage(); } } catch (Exception e) { rtnEntity.message=e.getMessage(); } return rtnEntity; } public TEntity SaveJson(String doGetString,TEntity entity) { return null; } public List<TEntity> SaveJson(String doGetString,String jsonString) { return null; } public List<TEntity> SaveJsonList(String doGetString,List<TEntity> list) { return null; } public List<TEntity> SaveJsonList(String doGetString,String jsonString) { return null; } private String doGet(String query) { if(!exists(IredeemApplication.DataInformation.getURL())) return "The web address can't be used!"; return Caller.doGet(IredeemApplication.DataInformation.getJSONServiceURL() + query); } private boolean exists(String URLName) { return URLUtil.isValidUrl(URLName); } }
这里几个Save方法没有实现,大家有兴趣的话,可以试着用post方法进行封装。
现在我们要做的就是提供一下数据源以及json跟Entity的具体转换类。
Entity:
public class Staff extends BaseEntity { public String CardSN; public String StaffName; public double MaximumTransaction; public Boolean Result; public String Message; }
Builder:
public class StaffBuilder implements JSONDataBaseBuilder<Staff> { @Override public ContentValues deconstruct(Staff entity) { ContentValues values = new ContentValues(); values.put("CardSN", entity.CardSN); values.put("StaffName", entity.StaffName); values.put("MaximumTransaction", entity.MaximumTransaction); values.put("Result", entity.Result); values.put("Message", entity.Message); return values; } @Override public Staff jsonBuild(JSONObject jsonObject) { Staff entity = new Staff(); try { entity.CardSN = jsonObject.getString("CardSN"); } catch (JSONException e) { } try { entity.StaffName = jsonObject.getString("StaffName"); } catch (JSONException e) { } try { entity.MaximumTransaction = jsonObject.getDouble("MaximumTransaction"); } catch (JSONException e) { Log.i("StaffBuilder", e.getMessage()); } try { entity.Result = jsonObject.getBoolean("Result"); } catch (JSONException e) { } try { entity.Message = jsonObject.getString("Message"); } catch (JSONException e) { } return entity; } }
现在我们准备工作就完成了。最后我们来调用一下:
获取一个列表。
public DBHelperList<Staff> getArrayList() { String url = “www.baidu.com" return service.getJSonList(url); }
传入参数:
public Boolean login(Staff staff, String password) { String url = “url”; Map<String, String> map = new HashMap<String, String>(); map.put("StaffId", staff.CardSN); map.put("password", password); DBHelperEntity<Staff> rtnStaff = service.getDbHelperEntity(url, map); if (rtnStaff.getIsJsonData()) { MainActivity.getInstance().AddMemberLoginScreen(); MainActivity.getInstance().RefreshMenu(rtnStaff.tEntity); return true; } return false; }
获得一个实例:
public DBHelperEntity<Terminal> ConfigureService(String serialNo) { String url = “Youweb site”; Map<String, String> map = new HashMap<String, String>(); map.put("serialNo", serialNo); return service.getDbHelperEntity(url, map); }
简单吧。估计有的读者会觉得在写entity和builder的时候会写大量的代码,那我们何不运用T4建立一个模板让它们自动生成。
<#@ template language="C#" debug="false" hostspecific="true"#> <#@ include file="EF.Utility.CS.ttinclude"#><#@ output extension=".cs"#><# CodeGenerationTools code = new CodeGenerationTools(this); MetadataLoader loader = new MetadataLoader(this); CodeRegion region = new CodeRegion(this, 1); MetadataTools ef = new MetadataTools(this); string inputFile = @"../Model.edmx"; EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile); string namespaceName = code.VsNamespaceSuggestion(); EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this); WriteHeader(fileManager); foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name)) { fileManager.StartNewFile(entity.Name + ".java"); #> package com.iredeem.db.api; import com.iredeem.db.BaseEntity; <#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#> class <#=code.Escape(entity)#> extends BaseEntity <#=code.StringBefore(" : ", code.Escape(entity.BaseType))#> { <# var propertiesWithDefaultValues = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity && p.DefaultValue != null); var collectionNavigationProperties = entity.NavigationProperties.Where(np => np.DeclaringType == entity && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); var complexProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == entity); if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any()) { #> public <#=code.Escape(entity)#>(){ } <# } var primitiveProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity); if (primitiveProperties.Any()) { foreach (var edmProperty in primitiveProperties) { if (edmProperty.Name == "Id") continue; WriteProperty(code, edmProperty); } } #> } <# EndNamespace(namespaceName); } foreach (var complex in ItemCollection.GetItems<ComplexType>().OrderBy(e => e.Name)) { fileManager.StartNewFile(complex.Name + ".java"); BeginNamespace(namespaceName, code); #> <#=Accessibility.ForType(complex)#> class <#=code.Escape(complex)#> { <# var complexProperties = complex.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == complex); var propertiesWithDefaultValues = complex.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == complex && p.DefaultValue != null); #> } <# EndNamespace(namespaceName); } if (!VerifyTypesAreCaseInsensitiveUnique(ItemCollection)) { return ""; } fileManager.Process(); #> <#+ string GetResourceString(string resourceName) { if(_resourceManager == null) { _resourceManager = new System.Resources.ResourceManager("System.Data.Entity.Design", typeof(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly); } return _resourceManager.GetString(resourceName, null); } System.Resources.ResourceManager _resourceManager; void WriteHeader(EntityFrameworkTemplateFileManager fileManager) { fileManager.StartHeader(); #> //------------------------------------------------------------------------------ // <auto-generated> // <#=GetResourceString("Template_GeneratedCodeCommentLine1")#> // // <#=GetResourceString("Template_GeneratedCodeCommentLine2")#> // <#=GetResourceString("Template_GeneratedCodeCommentLine3")#> // </auto-generated> //------------------------------------------------------------------------------ <#+ fileManager.EndBlock(); } void BeginNamespace(string namespaceName, CodeGenerationTools code) { namespaceName = namespaceName; CodeRegion region = new CodeRegion(this); if (!String.IsNullOrEmpty(namespaceName)) { #> namespace <#=code.EscapeNamespace(namespaceName)#> { <#+ PushIndent(CodeRegion.GetIndent(1)); } } void EndNamespace(string namespaceName) { if (!String.IsNullOrEmpty(namespaceName)) { PopIndent(); #> <#+ } } void WriteProperty(CodeGenerationTools code, EdmProperty edmProperty) { WriteProperty(PropertyVirtualModifier(Accessibility.ForProperty(edmProperty)), code.Escape(edmProperty.TypeUsage), code.Escape(edmProperty), code.SpaceAfter(Accessibility.ForGetter(edmProperty)), code.SpaceAfter(Accessibility.ForSetter(edmProperty))); } void WriteNavigationProperty(CodeGenerationTools code, NavigationProperty navigationProperty) { var endType = code.Escape(navigationProperty.ToEndMember.GetEntityType()); WriteProperty(PropertyVirtualModifier(Accessibility.ForProperty(navigationProperty)), navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType, code.Escape(navigationProperty), code.SpaceAfter(Accessibility.ForGetter(navigationProperty)), code.SpaceAfter(Accessibility.ForSetter(navigationProperty))); } void WriteProperty(string accessibility, string type, string name, string getterAccessibility, string setterAccessibility) { #> <#=accessibility#> <#=WriteJavaProperty(type)#> <#=name#>; <#+ } string WriteJavaProperty(string name) { switch(name) { case "string": return "String"; break; case "DateTime": return "Date"; break; case "bool": return "boolean"; break; case "decimal": return "float"; break; case "Nullable<System.DateTime>": case "System.DateTime": return "Date"; break; case "Nullable<int>": return "int"; break; case "System.Guid": return "String"; break; case "Nullable<double>": return "double"; break; case "Nullable<bool>": return "Boolean"; break; default: return name; break; } } string PropertyVirtualModifier(string accessibility) { return accessibility + (accessibility != "private" ? "" : ""); } bool VerifyTypesAreCaseInsensitiveUnique(EdmItemCollection itemCollection) { var alreadySeen = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); foreach(var type in itemCollection.GetItems<StructuralType>()) { if (!(type is EntityType || type is ComplexType)) { continue; } if (alreadySeen.ContainsKey(type.FullName)) { Error(String.Format(CultureInfo.CurrentCulture, "This template does not support types that differ only by case, the types {0} are not supported", type.FullName)); return false; } else { alreadySeen.Add(type.FullName, true); } } return true; } #>
<#@ template language="C#" debug="false" hostspecific="true"#> <#@ include file="EF.Utility.CS.ttinclude"#><#@ output extension=".cs"#><# CodeGenerationTools code = new CodeGenerationTools(this); MetadataLoader loader = new MetadataLoader(this); CodeRegion region = new CodeRegion(this, 1); MetadataTools ef = new MetadataTools(this); string inputFile = @"../Model.edmx"; EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile); string namespaceName = code.VsNamespaceSuggestion(); EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this); WriteHeader(fileManager); foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name)) { fileManager.StartNewFile(entity.Name + "Builder.java"); #> package com.iredeem.db.builder; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentValues; import com.iredeem.db.JSONDataBaseBuilder; import com.iredeem.db.api.<#=code.Escape(entity)#>; <#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>class <#=code.Escape(entity)#>Builder implements JSONDataBaseBuilder<<#=code.Escape(entity)#>> <#=code.StringBefore(" : ", code.Escape(entity.BaseType))#> { <# var propertiesWithDefaultValues = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity && p.DefaultValue != null); var collectionNavigationProperties = entity.NavigationProperties.Where(np => np.DeclaringType == entity && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); var complexProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == entity); if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any()) { #> public <#=code.Escape(entity)#>Builder(){ } <# } #> @Override public ContentValues deconstruct(<#=code.Escape(entity)#> entity) { ContentValues values = new ContentValues(); <# var primitiveProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity); if (primitiveProperties.Any()){ foreach (var edmProperty in primitiveProperties){if (edmProperty.Name == "Id") continue; #> values.put("<#=edmProperty.Name#>", entity.<#=edmProperty.Name#>); <#} } #> return values; } @Override public <#=code.Escape(entity)#> jsonBuild(JSONObject jsonObject) { <#=code.Escape(entity)#> entity = new <#=code.Escape(entity)#>(); <# foreach (var edmProperty in primitiveProperties) { #> try { entity.<#=edmProperty.Name#> = jsonObject.<#=WriteJavaProperty(edmProperty,edmProperty.Name)#>("<#=edmProperty.Name#>"); } catch (JSONException e) { } <#} #> return entity; } } <# EndNamespace(namespaceName); } foreach (var complex in ItemCollection.GetItems<ComplexType>().OrderBy(e => e.Name)) { fileManager.StartNewFile(complex.Name + ".java"); BeginNamespace(namespaceName, code); #> <#=Accessibility.ForType(complex)#> class <#=code.Escape(complex)#> { <# var complexProperties = complex.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == complex); var propertiesWithDefaultValues = complex.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == complex && p.DefaultValue != null); #> } <# EndNamespace(namespaceName); } if (!VerifyTypesAreCaseInsensitiveUnique(ItemCollection)) { return ""; } fileManager.Process(); #> <#+ string GetResourceString(string resourceName) { if(_resourceManager == null) { _resourceManager = new System.Resources.ResourceManager("System.Data.Entity.Design", typeof(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly); } return _resourceManager.GetString(resourceName, null); } System.Resources.ResourceManager _resourceManager; void WriteHeader(EntityFrameworkTemplateFileManager fileManager) { fileManager.StartHeader(); #> //------------------------------------------------------------------------------ // <auto-generated> // <#=GetResourceString("Template_GeneratedCodeCommentLine1")#> // // <#=GetResourceString("Template_GeneratedCodeCommentLine2")#> // <#=GetResourceString("Template_GeneratedCodeCommentLine3")#> // </auto-generated> //------------------------------------------------------------------------------ <#+ fileManager.EndBlock(); } void BeginNamespace(string namespaceName, CodeGenerationTools code) { namespaceName = namespaceName; CodeRegion region = new CodeRegion(this); if (!String.IsNullOrEmpty(namespaceName)) { #> namespace <#=code.EscapeNamespace(namespaceName)#> { <#+ PushIndent(CodeRegion.GetIndent(1)); } } void EndNamespace(string namespaceName) { if (!String.IsNullOrEmpty(namespaceName)) { PopIndent(); #> <#+ } } string WriteJavaProperty(System.Data.Metadata.Edm.EdmProperty ent,string name) { CodeGenerationTools code = new CodeGenerationTools(this); var typeName = code.Escape(ent.TypeUsage); string rtnVal; switch(typeName) { case "string": rtnVal= "String"; break; case "DateTime": rtnVal= "Date"; break; case "bool": rtnVal= "boolean"; break; case "decimal": rtnVal= "Long"; break; case "Nullable<System.DateTime>": case "System.DateTime": rtnVal= "Date"; break; case "Nullable<int>": rtnVal= "Int"; break; case "System.Guid": rtnVal= "string"; break; case "Nullable<bool>": rtnVal="Boolean"; break; case "Nullable<double>": rtnVal="Double"; break; default: rtnVal= typeName; break; } rtnVal = rtnVal.Substring(0,1).ToUpper()+rtnVal.Substring(1,rtnVal.Length-1); return "get"+rtnVal; } string PropertyVirtualModifier(string accessibility) { return accessibility + (accessibility != "private" ? "" : ""); } bool VerifyTypesAreCaseInsensitiveUnique(EdmItemCollection itemCollection) { var alreadySeen = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); foreach(var type in itemCollection.GetItems<StructuralType>()) { if (!(type is EntityType || type is ComplexType)) { continue; } if (alreadySeen.ContainsKey(type.FullName)) { Error(String.Format(CultureInfo.CurrentCulture, "This template does not support types that differ only by case, the types {0} are not supported", type.FullName)); return false; } else { alreadySeen.Add(type.FullName, true); } } return true; } #>
当然如果你说我不用保存到web service,而只是保存在sqllite里面,那么你只需要修改的是call.java其他的就完全不用修改了,方便吧。
到这里对数据保存是不是就不在用过多的去配置了?