Android 与 Webservice 的快速保存
前面写了一篇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 + "\n");
- }
- } 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其他的就完全不用修改了,方便吧。
到这里对数据保存是不是就不在用过多的去配置了?
Android 与 Webservice 的快速保存的更多相关文章
- 黎活明8天快速掌握android视频教程--12_文件的保存与读取
1.当前是把文件保存当前手机的app的data目录下 我们来看看操作保存文件的业务类 package contract.test.savafileapplication; import android ...
- Android平台调用WebService详解
上篇文章已经对Web Service及其相关知识进行了介绍(Android开发之WebService介绍 ),相信有的朋友已经忍耐不住想试试在Android应用中调用Web Service.本文将通过 ...
- 网摘Android调用WebService
这边特别注意调用的.net WCF 接口的绑定方式.以前一直用的wxHttpbinding,一直连不上.改成BasicHTTPbinding就能连上了 上篇文章已经对Web Service及其相关知识 ...
- Android调用WebService(转)
Android调用WebService WebService是一种基于SOAP协议的远程调用标准,通过 webservice可以将不同操作系统平台.不同语言.不同技术整合到一块.在Android SD ...
- android loginDemo +WebService用户登录验证
android loginDemo +WebService用户登录验证 本文是基于android4.0下的loginActivity Demo和android下的Webservice实现的.l ...
- 解决android开发webservice的发布与数据库连接的问题
由于app后续开发的需要,移植了两次webservice和数据库,遇到了不少问题,也花费了很多时间,实践告诉我要学会寻找问题的根源,这样才能在开发中节省时间,尽快解决问题!好,废话不多说,转入正题…… ...
- Android GIS +webservice
Android新手经典入门教程 Android开发教程(完全免费版) Android SDK v3.1.0 Android定位功能(一) Android定位功能(二) Android 百度地图开发(一 ...
- 如何解析android访问webservice返回的SoapObject数据(可用)
怎么解析android访问webservice返回的SoapObject数据 本帖最后由 kkDragon123 于 2013-03-26 15:50:07 编辑 我的数据如下:mingdanResp ...
- 纠正网上乱传的android调用Webservice方法。
1.写作背景: 笔者想实现android调用webservice,可是网上全是不管对与错乱转载的文章,结果不但不能解决问题,只会让人心烦,所以笔者决定将自己整理好的能用的android调用webser ...
随机推荐
- 通过uiview动画来放大图片
UIImage *image=[UIImage imageNamed:"]; UIImageView *imageView=[[UIImageView alloc]init]; imageV ...
- java cpu load
$ps -Lp 179093 cu | more USER PID LWP %CPU NLWP %MEM VSZ RSS TTY STAT START TIME COMMAND admin 17909 ...
- iOS 设计模式之单例
设计模式:单例 一. 单例模式是一种常用的软件设计模式.在它的核心结构中只包含一个被称为单例类的特殊类.通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并 ...
- mysql_DML_delete
delete from 表名 删除表里的数据 可以配合where试用
- 一路踩过的坑 php
1.数据表唯一索引 (两列字段,组合索引) 遇到的情形:项目搭建新测试环境(其实就是所谓的灰度 与线上一致的一个环境):从线上拉回来代码搭建的,数据也是来自于线上数据,但是由于线上数据有部分为机密数 ...
- 第四节 数据格式化和ModelAttribute注解的介绍
从来都不坦荡,情绪都写在脸上:不开心的时候,不爱说话,笑也勉强. 课堂笔记,如果这么写,不仅仅是手速,还要有语速, 这样不太适合! --胖先生 关于数据传递: 客户端传递数据到服务端: 1.使用普通的 ...
- List<T>.Sort() 排序的用法
List<T> 可以通过 .Sort()进行排序,但是当 T 对象为自定义类型时(比如自定义模型),就需要 IComparable接口重写其中的方法来实现,实现代码如下: class Pr ...
- 洛谷P1717 钓鱼
P1717 钓鱼 41通过 116提交 题目提供者该用户不存在 标签贪心 难度提高+/省选- 提交该题 讨论 题解 记录 最新讨论 暂时没有讨论 题目描述 话说发源于小朋友精心设计的游戏被电脑组的童鞋 ...
- [Excel操作]Microsoft Office Excel 不能访问文件
最近,客户服务器迁移,因操作系统环境变化而引起的的环境问题一堆,遇到的问题并解决方法在“[Excel]操作”类别会体现. Microsoft Office Excel 不能访问文件“C:\\LMSEx ...
- 【JS Note】undefined与null
在Javascript中有这两种原始类型: Undefined与Null.而这两种原始类型都各自只有一个值,分别是undefined,null. undefined: 1.变量声明后未赋值,则变量会被 ...