前面写了一篇android对sqllite的快速保存博客,今天我们来看看android与webservice的交互,相信很多有经验的人自然就想到了soap。但是如果在小型项目中,具有大材小用之嫌。实际上java本身就提供了一套可以与webservice交付的功能,也十分简单。因此对于小型项目而言,我们何不封装一下该方法。

下面我们来看下我们要做的内容:

1)从远程站点上获取数据。

2) 判断数据是否是json格式的,如果是那么我们能不能通过转换将json格式的直接转换为entity返回。如果不是json格式的,那么我们能不能返还回该值。

首先我们来解决第一点,andoird对数据的处理,都是放在多线程上面去所以我们建立一个AsyncTask来管理。

  1. private static class NewsGetTask extends
  2. AsyncTask<String, IredeemError, String> {
  3.  
  4. private ProgressDialog pDialog;
  5.  
  6. @Override
  7. protected void onPreExecute() {
  8. super.onPreExecute();
  9. pDialog = new ProgressDialog(MainActivity.getInstance());
  10. pDialog.setMessage("Please waiting...");
  11. pDialog.setIndeterminate(false);
  12. pDialog.setCancelable(true);
  13. pDialog.show();
  14. }
  15.  
  16. /*
  17. * (non-Javadoc)
  18. *
  19. * @see android.os.AsyncTask#doInBackground(Params[])
  20. */
  21. @Override
  22. protected String doInBackground(String... params) {
  23.  
  24. String url = params[0];
  25.  
  26. if(!URLUtil.isValidUrl(url))
  27. {
  28. return IredeemApplication.getInstance().getString("UnConnection");
  29. }
  30.  
  31. String data = null;
  32.  
  33. if (requestCache != null) {
  34. data = requestCache.get(url);
  35. if (data != null) {
  36. return data;
  37. }
  38. }
  39. // initialize HTTP GET request objects
  40. BasicHttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established.
  41. HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data.
  42. HttpConnectionParams.setSoTimeout(httpParameters, 5000);
  43.  
  44. HttpClient httpClient = new DefaultHttpClient(httpParameters);
  45. HttpGet httpGet = new HttpGet(url);
  46. HttpResponse httpResponse = null;
  47.  
  48. try {
  49. // execute request
  50. try {
  51. httpResponse = httpClient.execute(httpGet);
  52. } catch (UnknownHostException e) {
  53. return e.getMessage();
  54. // throw wsError;
  55. } catch (SocketException e) {
  56. return e.getMessage();
  57. // throw wsError;
  58. }
  59.  
  60. // request data
  61. HttpEntity httpEntity = httpResponse.getEntity();
  62.  
  63. if (httpEntity != null) {
  64. InputStream inputStream = httpEntity.getContent();
  65. data = convertStreamToString(inputStream);
  66. // cache the result
  67.  
  68. // todo: remove out the cash
  69. if (requestCache != null) {
  70. requestCache.put(url, data);
  71. }
  72. }
  73.  
  74. } catch (ClientProtocolException e) {
  75. return e.getLocalizedMessage();
  76. } catch (IOException e) {
  77. return e.getMessage();
  78. }
  79. return data;
  80. }
  81.  
  82. protected void onPostExecute(String message) {
  83. pDialog.dismiss();
  84. }
  85. }

我们在线程中率先验证一下URL是不是可用,URLUtil主要就是一个字符串匹配严重是否合法。接着我们设置一下连接的超时时间,然后再Try catch里面去获取该数据,并返回。第一步便完成了。这时候我们需要写个类来调用:调用方法如下:

  1. public static String doGet(String url) {
  2. try {
  3. return (new NewsGetTask().execute(url)).get();
  4. } catch (InterruptedException e) {
  5. return e.getMessage();
  6. } catch (ExecutionException e) {
  7. return e.getMessage();
  8. }
  9. }

整合下第一步将全部代码传上来:

  1. package com.iredeem.util;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.SocketException;
  10. import java.net.URL;
  11. import java.net.UnknownHostException;
  12. import java.util.concurrent.ExecutionException;
  13.  
  14. import org.apache.http.HttpEntity;
  15. import org.apache.http.HttpResponse;
  16. import org.apache.http.client.ClientProtocolException;
  17. import org.apache.http.client.HttpClient;
  18. import org.apache.http.client.methods.HttpGet;
  19. import org.apache.http.impl.client.DefaultHttpClient;
  20. import org.apache.http.params.BasicHttpParams;
  21. import org.apache.http.params.HttpConnectionParams;
  22. import org.json.JSONObject;
  23.  
  24. import com.iredeem.IredeemApplication;
  25. import com.iredeem.activity.MainActivity;
  26.  
  27. import android.app.ProgressDialog;
  28. import android.os.AsyncTask;
  29. import android.util.Log;
  30. import android.webkit.URLUtil;
  31.  
  32. /**
  33. * @author xie
  34. */
  35. public class Caller {
  36.  
  37. /**
  38. * Cache for most recent request
  39. */
  40. private static RequestCache requestCache = null;
  41.  
  42. /**
  43. * Performs HTTP GET using Apache HTTP Client v 4
  44. *
  45. * @param url
  46. * @return
  47. * @throws WSError
  48. */
  49. public static String doGet(String url) {
  50. try {
  51. return (new NewsGetTask().execute(url)).get();
  52. } catch (InterruptedException e) {
  53. return e.getMessage();
  54. } catch (ExecutionException e) {
  55. return e.getMessage();
  56. }
  57. }
  58.  
  59. private static Boolean isConnection(String urlString) {
  60. try {
  61.  
  62. URL url = new URL(urlString);
  63. HttpURLConnection urlc = (HttpURLConnection) url
  64. .openConnection();
  65.  
  66. urlc.setRequestProperty("User-Agent",
  67. "Android Application:***");
  68.  
  69. urlc.setRequestProperty("Connection", "close");
  70.  
  71. urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
  72.  
  73. urlc.connect();
  74.  
  75. if (urlc.getResponseCode() == 200) {
  76.  
  77. return true;
  78. }
  79.  
  80. } catch (MalformedURLException e1) {
  81.  
  82. e1.printStackTrace();
  83.  
  84. } catch (IOException e) {
  85.  
  86. e.printStackTrace();
  87. }
  88. return false;
  89. }
  90.  
  91. private static class NewsGetTask extends
  92. AsyncTask<String, IredeemError, String> {
  93.  
  94. private ProgressDialog pDialog;
  95.  
  96. @Override
  97. protected void onPreExecute() {
  98. super.onPreExecute();
  99. pDialog = new ProgressDialog(MainActivity.getInstance());
  100. pDialog.setMessage("Please waiting...");
  101. pDialog.setIndeterminate(false);
  102. pDialog.setCancelable(true);
  103. pDialog.show();
  104. }
  105.  
  106. /*
  107. * (non-Javadoc)
  108. *
  109. * @see android.os.AsyncTask#doInBackground(Params[])
  110. */
  111. @Override
  112. protected String doInBackground(String... params) {
  113.  
  114. String url = params[0];
  115.  
  116. if(!URLUtil.isValidUrl(url))
  117. {
  118. return IredeemApplication.getInstance().getString("UnConnection");
  119. }
  120.  
  121. String data = null;
  122.  
  123. if (requestCache != null) {
  124. data = requestCache.get(url);
  125. if (data != null) {
  126. return data;
  127. }
  128. }
  129. // initialize HTTP GET request objects
  130. BasicHttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established.
  131. HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data.
  132. HttpConnectionParams.setSoTimeout(httpParameters, 5000);
  133.  
  134. HttpClient httpClient = new DefaultHttpClient(httpParameters);
  135. HttpGet httpGet = new HttpGet(url);
  136. HttpResponse httpResponse = null;
  137.  
  138. try {
  139. // execute request
  140. try {
  141. httpResponse = httpClient.execute(httpGet);
  142. } catch (UnknownHostException e) {
  143. return e.getMessage();
  144. // throw wsError;
  145. } catch (SocketException e) {
  146. return e.getMessage();
  147. // throw wsError;
  148. }
  149.  
  150. // request data
  151. HttpEntity httpEntity = httpResponse.getEntity();
  152.  
  153. if (httpEntity != null) {
  154. InputStream inputStream = httpEntity.getContent();
  155. data = convertStreamToString(inputStream);
  156. // cache the result
  157.  
  158. // todo: remove out the cash
  159. if (requestCache != null) {
  160. requestCache.put(url, data);
  161. }
  162. }
  163.  
  164. } catch (ClientProtocolException e) {
  165. return e.getLocalizedMessage();
  166. } catch (IOException e) {
  167. return e.getMessage();
  168. }
  169. return data;
  170. }
  171.  
  172. protected void onPostExecute(String message) {
  173. pDialog.dismiss();
  174. }
  175. }
  176.  
  177. private static String convertStreamToString(InputStream is) {
  178.  
  179. BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  180. StringBuilder sb = new StringBuilder();
  181.  
  182. String line = null;
  183. try {
  184. while ((line = reader.readLine()) != null) {
  185. sb.append(line + "\n");
  186. }
  187. } catch (IOException e) {
  188. e.printStackTrace();
  189. } finally {
  190. try {
  191. is.close();
  192. } catch (IOException e) {
  193. e.printStackTrace();
  194. }
  195. }
  196.  
  197. return sb.toString();
  198. }
  199.  
  200. public static void setRequestCache(RequestCache requestCache) {
  201. Caller.requestCache = requestCache;
  202. }
  203.  
  204. public static String createStringFromIds(int[] ids) {
  205. if (ids == null)
  206. return "";
  207.  
  208. String query = "";
  209.  
  210. for (int id : ids) {
  211. query = query + id + "+";
  212. }
  213.  
  214. return query;
  215. }
  216.  
  217. }

接着我们来解决第二步:

我们先建立一个BaseEntity的基类。

  1. public class BaseEntity implements Serializable {
  2.  
  3. private static final long serialVersionUID = 1L;
  4.  
  5. public static final String DB_NAME = IredeemApplication.DataInformation.DB_NAME;
  6.  
  7. private static final String Tag = "Base Entity";
  8.  
  9. public<T extends Serializable> void set(Class<T> clazz, String fieldName,Object obj)
  10. {
  11. Class<? extends BaseEntity> cls = this.getClass();
  12. Field filed = null;
  13. try {
  14. filed = cls.getField(fieldName);
  15. filed.set(this, As(clazz, obj));
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. }
  19. }
  20.  
  21. public<T extends Serializable> T get(Class<T> clazz, String fieldName)
  22. {
  23. Class<? extends BaseEntity> cls = this.getClass();
  24. Field filed = null;
  25. try {
  26. filed = cls.getField(fieldName);
  27. } catch (NoSuchFieldException e) {
  28. e.printStackTrace();
  29. }
  30. try {
  31. return As(clazz, filed.get(this));
  32. } catch (IllegalArgumentException e) {
  33. Log.i(Tag, "IllegalArgumentException");
  34. } catch (IllegalAccessException e) {
  35. Log.i(Tag, "IllegalAccessException");
  36. }
  37. catch (Exception e) {
  38. Log.i(Tag, "Exception");
  39. }
  40. return DefaultAs(clazz);
  41. }
  42.  
  43. @SuppressWarnings("unchecked")
  44. private <T> T DefaultAs(Class<T> clazz)
  45. {
  46. if(clazz==String.class)
  47. return (T)" ";
  48. if(clazz==double.class)
  49. return (T)"0";
  50. if(clazz==int.class)
  51. return (T)"0";
  52. if(clazz==Date.class)
  53. return (T)new java.util.Date();
  54. return null;
  55. }
  56.  
  57. @SuppressWarnings("unchecked")
  58. private <T> T As(Class<T> clazz, Object object) {
  59. if(clazz==String.class)
  60. {
  61. if(object==null) return null;
  62. return (T)object.toString();
  63. }
  64. if(clazz==double.class)
  65. {
  66. if(object==null) object=0;
  67. object= Double.parseDouble(object.toString());
  68. }
  69. return (T)object;
  70. }
  71. }

这个类可以不要任何东西,这里我是在项目中用到了部分方法,便于大家调试没有挪掉。接着我们建立一个JsonBuilder的接口,用来提供将json转换为entity或者由entity 转换为json。

  1. public interface JSONDataBaseBuilder<TEntity extends BaseEntity> {
  2.  
  3. public abstract ContentValues deconstruct(TEntity entity);
  4.  
  5. public abstract TEntity jsonBuild(JSONObject jsonObject)
  6. throws JSONException;
  7.  
  8. public interface DataBaseBuilder<TEntity extends BaseEntity> extends
  9. JSONDataBaseBuilder<BaseEntity> {
  10.  
  11. public abstract TEntity build(Cursor query);
  12.  
  13. public abstract String table();
  14.  
  15. public abstract TEntity jsonBuild(JSONObject jsonObject) throws JSONException;
  16.  
  17. }
  18. }

再来提供一个entity将返回的entity或者message进行组合一下:

  1. public class DBHelperEntity<TEntity extends BaseEntity> {
  2. public String message;
  3. public TEntity tEntity;
  4. public Boolean getIsJsonData()
  5. {
  6. if(tEntity==null) return false;
  7. return true;
  8. }
  9.  
  10. public Boolean FormatEntity(String jsonString)
  11. {
  12. return true;
  13. }
  14. }

如果我们返回的是list,那么我们也需要一个entity来封装一下:

  1. public class DBHelperList<TEntity extends BaseEntity> {
  2. public ArrayList<TEntity> list;
  3. public String jsonString;
  4. public String message="";
  5. public Boolean isURLError = false;
  6. public DBHelperList(String jsonString)
  7. {
  8. this.jsonString = jsonString;
  9. list = new ArrayList<TEntity>();
  10. }
  11.  
  12. public Boolean getIsJSONList()
  13. {
  14. if(list!=null && list.size()>0) return true;
  15. return false;
  16. }
  17. }

最后我们来封装下service类:

  1. public class JSONServiceBase<TEntity extends BaseEntity> {
  2.  
  3. private JSONDataBaseBuilder<TEntity> mBuilder;
  4. private Activity activity;
  5.  
  6. public JSONServiceBase(Activity activity,JSONDataBaseBuilder<TEntity> builder)
  7. {
  8. this.activity = activity;
  9. mBuilder = builder;
  10. }
  11.  
  12. public DBHelperList<TEntity> searchJsonForEntity(String doGetString) {
  13. String jsonString = doGet(doGetString);
  14. return new DBHelperList<TEntity>(jsonString);
  15. // JSONArray jsonArrayEntry = new JSONArray(jsonString);
  16. // return jsonArrayEntry;
  17. }
  18.  
  19. public DBHelperList<TEntity> getJSonList(String doGetString){
  20. DBHelperList<TEntity> list = searchJsonForEntity(doGetString);
  21. try {
  22. JSONArray jsonArrayEntry = new JSONArray(list.jsonString);
  23. list.list = getJSonList(jsonArrayEntry);
  24. return list;
  25. } catch (JSONException e) {
  26. list.message = list.jsonString;
  27. return list;
  28. }
  29. }
  30.  
  31. public DBHelperList<TEntity> getJSonList(String doGetString,Map<String,String> searchMap)
  32. {
  33. return getJSonList(ServiceHelper.getPath(searchMap, doGetString));
  34. }
  35.  
  36. public ArrayList<TEntity> getJSonList(JSONArray jsonArrayEntities) {
  37.  
  38. int n = jsonArrayEntities.length();
  39. ArrayList<TEntity> entities = new ArrayList<TEntity>();
  40.  
  41. for(int i=0; i < n; i++){
  42. try {
  43. entities.add(mBuilder.jsonBuild(jsonArrayEntities.getJSONObject(i)));
  44. } catch (JSONException e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. return entities;
  49. }
  50.  
  51. public DBHelperEntity<TEntity> getDbHelperEntity(String doGetString)
  52. {
  53. String jsonString = doGet(doGetString);
  54. JSONObject jObject;
  55. DBHelperEntity<TEntity> rtnEntity = new DBHelperEntity<TEntity>();
  56. try {
  57. try {
  58. jObject = new JSONObject(jsonString);
  59. } catch (JSONException e) {
  60. rtnEntity.message = IredeemApplication.getInstance().getString(jsonString);
  61. return rtnEntity;
  62. }
  63.  
  64. try {
  65. rtnEntity.tEntity = mBuilder.jsonBuild(jObject);
  66. } catch (JSONException e) {
  67. rtnEntity.message = e.getLocalizedMessage();
  68. }
  69. } catch (Exception e) {
  70. rtnEntity.message=e.getMessage();
  71. }
  72.  
  73. return rtnEntity;
  74. }
  75.  
  76. public DBHelperEntity<TEntity> getDbHelperEntity(String doGetString,Map<String, String> searchMap)
  77. {
  78. String jsonString = doGet(ServiceHelper.getPath(searchMap, doGetString));
  79. JSONObject jObject;
  80. DBHelperEntity<TEntity> rtnEntity = new DBHelperEntity<TEntity>();
  81. try {
  82. try {
  83. jObject = new JSONObject(jsonString);
  84. } catch (JSONException e) {
  85. rtnEntity.message = IredeemApplication.getInstance().getString(jsonString);
  86. return rtnEntity;
  87. }
  88. try {
  89. rtnEntity.tEntity = mBuilder.jsonBuild(jObject);
  90. } catch (JSONException e) {
  91. rtnEntity.message = e.getLocalizedMessage();
  92. }
  93. } catch (Exception e) {
  94. rtnEntity.message=e.getMessage();
  95. }
  96. return rtnEntity;
  97. }
  98.  
  99. public TEntity SaveJson(String doGetString,TEntity entity)
  100. {
  101. return null;
  102. }
  103.  
  104. public List<TEntity> SaveJson(String doGetString,String jsonString)
  105. {
  106. return null;
  107. }
  108.  
  109. public List<TEntity> SaveJsonList(String doGetString,List<TEntity> list)
  110. {
  111. return null;
  112. }
  113.  
  114. public List<TEntity> SaveJsonList(String doGetString,String jsonString)
  115. {
  116. return null;
  117. }
  118.  
  119. private String doGet(String query)
  120. {
  121. if(!exists(IredeemApplication.DataInformation.getURL()))
  122. return "The web address can't be used!";
  123.  
  124. return Caller.doGet(IredeemApplication.DataInformation.getJSONServiceURL() + query);
  125. }
  126.  
  127. private boolean exists(String URLName) {
  128. return URLUtil.isValidUrl(URLName);
  129. }
  130.  
  131. }

这里几个Save方法没有实现,大家有兴趣的话,可以试着用post方法进行封装。

现在我们要做的就是提供一下数据源以及json跟Entity的具体转换类。

Entity:

  1. public class Staff extends BaseEntity
  2. {
  3. public String CardSN;
  4. public String StaffName;
  5. public double MaximumTransaction;
  6. public Boolean Result;
  7. public String Message;
  8.  
  9. }

Builder:

  1. public class StaffBuilder implements JSONDataBaseBuilder<Staff>
  2. {
  3.  
  4. @Override
  5. public ContentValues deconstruct(Staff entity) {
  6. ContentValues values = new ContentValues();
  7. values.put("CardSN", entity.CardSN);
  8. values.put("StaffName", entity.StaffName);
  9. values.put("MaximumTransaction", entity.MaximumTransaction);
  10. values.put("Result", entity.Result);
  11. values.put("Message", entity.Message);
  12. return values;
  13. }
  14.  
  15. @Override
  16. public Staff jsonBuild(JSONObject jsonObject) {
  17. Staff entity = new Staff();
  18. try {
  19. entity.CardSN = jsonObject.getString("CardSN");
  20. }
  21. catch (JSONException e) {
  22. }
  23.  
  24. try {
  25. entity.StaffName = jsonObject.getString("StaffName");
  26. }
  27. catch (JSONException e) {
  28. }
  29.  
  30. try {
  31. entity.MaximumTransaction = jsonObject.getDouble("MaximumTransaction");
  32. }
  33. catch (JSONException e) {
  34. Log.i("StaffBuilder", e.getMessage());
  35. }
  36.  
  37. try {
  38. entity.Result = jsonObject.getBoolean("Result");
  39. }
  40. catch (JSONException e) {
  41. }
  42.  
  43. try {
  44. entity.Message = jsonObject.getString("Message");
  45. }
  46. catch (JSONException e) {
  47. }
  48.  
  49. return entity;
  50. }
  51. }

现在我们准备工作就完成了。最后我们来调用一下:

获取一个列表。

  1. public DBHelperList<Staff> getArrayList() {
  2.  
  3. String url = www.baidu.com"
  4. return service.getJSonList(url);
  5. }

传入参数:

  1. public Boolean login(Staff staff, String password) {
  2. String url = url”;
  3. Map<String, String> map = new HashMap<String, String>();
  4. map.put("StaffId", staff.CardSN);
  5. map.put("password", password);
  6. DBHelperEntity<Staff> rtnStaff = service.getDbHelperEntity(url, map);
  7. if (rtnStaff.getIsJsonData()) {
  8. MainActivity.getInstance().AddMemberLoginScreen();
  9. MainActivity.getInstance().RefreshMenu(rtnStaff.tEntity);
  10. return true;
  11. }
  12. return false;
  13. }

获得一个实例:

  1. public DBHelperEntity<Terminal> ConfigureService(String serialNo)
  2. {
  3. String url = Youweb site”;
  4. Map<String, String> map = new HashMap<String, String>();
  5. map.put("serialNo", serialNo);
  6. return service.getDbHelperEntity(url, map);
  7. }

简单吧。估计有的读者会觉得在写entity和builder的时候会写大量的代码,那我们何不运用T4建立一个模板让它们自动生成。

  1. <#@ template language="C#" debug="false" hostspecific="true"#>
  2. <#@ include file="EF.Utility.CS.ttinclude"#><#@
  3. output extension=".cs"#><#
  4.  
  5. CodeGenerationTools code = new CodeGenerationTools(this);
  6. MetadataLoader loader = new MetadataLoader(this);
  7. CodeRegion region = new CodeRegion(this, 1);
  8. MetadataTools ef = new MetadataTools(this);
  9.  
  10. string inputFile = @"../Model.edmx";
  11. EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
  12. string namespaceName = code.VsNamespaceSuggestion();
  13.  
  14. EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
  15. WriteHeader(fileManager);
  16.  
  17. foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
  18. {
  19. fileManager.StartNewFile(entity.Name + ".java");
  20.  
  21. #>
  22. package com.iredeem.db.api;
  23.  
  24. import com.iredeem.db.BaseEntity;
  25.  
  26. <#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#> class <#=code.Escape(entity)#> extends BaseEntity <#=code.StringBefore(" : ", code.Escape(entity.BaseType))#>
  27. {
  28. <#
  29.  
  30. var propertiesWithDefaultValues = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity && p.DefaultValue != null);
  31. var collectionNavigationProperties = entity.NavigationProperties.Where(np => np.DeclaringType == entity && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
  32. var complexProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == entity);
  33.  
  34. if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any())
  35. {
  36. #>
  37. public <#=code.Escape(entity)#>(){ }
  38.  
  39. <#
  40. }
  41.  
  42. var primitiveProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity);
  43. if (primitiveProperties.Any())
  44. {
  45. foreach (var edmProperty in primitiveProperties)
  46. {
  47. if (edmProperty.Name == "Id") continue;
  48. WriteProperty(code, edmProperty);
  49. }
  50. }
  51.  
  52. #>
  53. }
  54. <#
  55. EndNamespace(namespaceName);
  56. }
  57.  
  58. foreach (var complex in ItemCollection.GetItems<ComplexType>().OrderBy(e => e.Name))
  59. {
  60. fileManager.StartNewFile(complex.Name + ".java");
  61. BeginNamespace(namespaceName, code);
  62. #>
  63.  
  64. <#=Accessibility.ForType(complex)#> class <#=code.Escape(complex)#>
  65. {
  66. <#
  67. var complexProperties = complex.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == complex);
  68. var propertiesWithDefaultValues = complex.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == complex && p.DefaultValue != null);
  69. #>
  70.  
  71. }
  72. <#
  73. EndNamespace(namespaceName);
  74. }
  75.  
  76. if (!VerifyTypesAreCaseInsensitiveUnique(ItemCollection))
  77. {
  78. return "";
  79. }
  80.  
  81. fileManager.Process();
  82.  
  83. #>
  84. <#+
  85. string GetResourceString(string resourceName)
  86. {
  87. if(_resourceManager == null)
  88. {
  89. _resourceManager = new System.Resources.ResourceManager("System.Data.Entity.Design", typeof(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly);
  90. }
  91.  
  92. return _resourceManager.GetString(resourceName, null);
  93. }
  94. System.Resources.ResourceManager _resourceManager;
  95.  
  96. void WriteHeader(EntityFrameworkTemplateFileManager fileManager)
  97. {
  98. fileManager.StartHeader();
  99. #>
  100. //------------------------------------------------------------------------------
  101. // <auto-generated>
  102. // <#=GetResourceString("Template_GeneratedCodeCommentLine1")#>
  103. //
  104. // <#=GetResourceString("Template_GeneratedCodeCommentLine2")#>
  105. // <#=GetResourceString("Template_GeneratedCodeCommentLine3")#>
  106. // </auto-generated>
  107. //------------------------------------------------------------------------------
  108.  
  109. <#+
  110. fileManager.EndBlock();
  111. }
  112.  
  113. void BeginNamespace(string namespaceName, CodeGenerationTools code)
  114. {
  115. namespaceName = namespaceName;
  116. CodeRegion region = new CodeRegion(this);
  117. if (!String.IsNullOrEmpty(namespaceName))
  118. {
  119. #>
  120. namespace <#=code.EscapeNamespace(namespaceName)#>
  121. {
  122. <#+
  123. PushIndent(CodeRegion.GetIndent(1));
  124. }
  125. }
  126.  
  127. void EndNamespace(string namespaceName)
  128. {
  129. if (!String.IsNullOrEmpty(namespaceName))
  130. {
  131. PopIndent();
  132. #>
  133.  
  134. <#+
  135. }
  136. }
  137.  
  138. void WriteProperty(CodeGenerationTools code, EdmProperty edmProperty)
  139. {
  140. WriteProperty(PropertyVirtualModifier(Accessibility.ForProperty(edmProperty)),
  141. code.Escape(edmProperty.TypeUsage),
  142. code.Escape(edmProperty),
  143. code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
  144. code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
  145. }
  146.  
  147. void WriteNavigationProperty(CodeGenerationTools code, NavigationProperty navigationProperty)
  148. {
  149. var endType = code.Escape(navigationProperty.ToEndMember.GetEntityType());
  150. WriteProperty(PropertyVirtualModifier(Accessibility.ForProperty(navigationProperty)),
  151. navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
  152. code.Escape(navigationProperty),
  153. code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
  154. code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
  155. }
  156.  
  157. void WriteProperty(string accessibility, string type, string name, string getterAccessibility, string setterAccessibility)
  158. {
  159. #>
  160. <#=accessibility#> <#=WriteJavaProperty(type)#> <#=name#>;
  161. <#+
  162. }
  163.  
  164. string WriteJavaProperty(string name)
  165. {
  166. switch(name)
  167. {
  168. case "string":
  169. return "String";
  170. break;
  171. case "DateTime":
  172. return "Date";
  173. break;
  174. case "bool":
  175. return "boolean";
  176. break;
  177. case "decimal":
  178. return "float";
  179. break;
  180. case "Nullable<System.DateTime>":
  181. case "System.DateTime":
  182. return "Date";
  183. break;
  184. case "Nullable<int>":
  185. return "int";
  186. break;
  187. case "System.Guid":
  188. return "String";
  189. break;
  190. case "Nullable<double>":
  191. return "double";
  192. break;
  193. case "Nullable<bool>":
  194. return "Boolean";
  195. break;
  196. default:
  197. return name;
  198. break;
  199. }
  200. }
  201.  
  202. string PropertyVirtualModifier(string accessibility)
  203. {
  204. return accessibility + (accessibility != "private" ? "" : "");
  205. }
  206.  
  207. bool VerifyTypesAreCaseInsensitiveUnique(EdmItemCollection itemCollection)
  208. {
  209. var alreadySeen = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  210. foreach(var type in itemCollection.GetItems<StructuralType>())
  211. {
  212. if (!(type is EntityType || type is ComplexType))
  213. {
  214. continue;
  215. }
  216.  
  217. if (alreadySeen.ContainsKey(type.FullName))
  218. {
  219. Error(String.Format(CultureInfo.CurrentCulture, "This template does not support types that differ only by case, the types {0} are not supported", type.FullName));
  220. return false;
  221. }
  222. else
  223. {
  224. alreadySeen.Add(type.FullName, true);
  225. }
  226. }
  227.  
  228. return true;
  229. }
  230. #>
  1. <#@ template language="C#" debug="false" hostspecific="true"#>
  2. <#@ include file="EF.Utility.CS.ttinclude"#><#@
  3. output extension=".cs"#><#
  4.  
  5. CodeGenerationTools code = new CodeGenerationTools(this);
  6. MetadataLoader loader = new MetadataLoader(this);
  7. CodeRegion region = new CodeRegion(this, 1);
  8. MetadataTools ef = new MetadataTools(this);
  9.  
  10. string inputFile = @"../Model.edmx";
  11. EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
  12. string namespaceName = code.VsNamespaceSuggestion();
  13.  
  14. EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
  15. WriteHeader(fileManager);
  16.  
  17. foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
  18. {
  19. fileManager.StartNewFile(entity.Name + "Builder.java");
  20.  
  21. #>
  22. package com.iredeem.db.builder;
  23.  
  24. import org.json.JSONException;
  25. import org.json.JSONObject;
  26.  
  27. import android.content.ContentValues;
  28.  
  29. import com.iredeem.db.JSONDataBaseBuilder;
  30. import com.iredeem.db.api.<#=code.Escape(entity)#>;
  31.  
  32. <#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>class <#=code.Escape(entity)#>Builder implements JSONDataBaseBuilder<<#=code.Escape(entity)#>> <#=code.StringBefore(" : ", code.Escape(entity.BaseType))#>
  33. {
  34. <#
  35. var propertiesWithDefaultValues = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity && p.DefaultValue != null);
  36. var collectionNavigationProperties = entity.NavigationProperties.Where(np => np.DeclaringType == entity && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
  37. var complexProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == entity);
  38.  
  39. if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any())
  40. {
  41. #>
  42. public <#=code.Escape(entity)#>Builder(){ }
  43. <#
  44. }
  45. #>
  46.  
  47. @Override
  48. public ContentValues deconstruct(<#=code.Escape(entity)#> entity) {
  49. ContentValues values = new ContentValues();
  50. <#
  51. var primitiveProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity);
  52. if (primitiveProperties.Any()){
  53. foreach (var edmProperty in primitiveProperties){if (edmProperty.Name == "Id") continue;
  54. #>
  55. values.put("<#=edmProperty.Name#>", entity.<#=edmProperty.Name#>);
  56. <#}
  57. }
  58. #>
  59. return values;
  60. }
  61.  
  62. @Override
  63. public <#=code.Escape(entity)#> jsonBuild(JSONObject jsonObject) {
  64. <#=code.Escape(entity)#> entity = new <#=code.Escape(entity)#>();
  65. <#
  66. foreach (var edmProperty in primitiveProperties)
  67. {
  68. #>
  69. try {
  70. entity.<#=edmProperty.Name#> = jsonObject.<#=WriteJavaProperty(edmProperty,edmProperty.Name)#>("<#=edmProperty.Name#>");
  71. }
  72. catch (JSONException e) {
  73. }
  74.  
  75. <#} #>
  76.  
  77. return entity;
  78. }
  79. }
  80.  
  81. <#
  82. EndNamespace(namespaceName);
  83. }
  84.  
  85. foreach (var complex in ItemCollection.GetItems<ComplexType>().OrderBy(e => e.Name))
  86. {
  87. fileManager.StartNewFile(complex.Name + ".java");
  88. BeginNamespace(namespaceName, code);
  89. #>
  90.  
  91. <#=Accessibility.ForType(complex)#> class <#=code.Escape(complex)#>
  92. {
  93. <#
  94. var complexProperties = complex.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == complex);
  95. var propertiesWithDefaultValues = complex.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == complex && p.DefaultValue != null);
  96. #>
  97.  
  98. }
  99. <#
  100. EndNamespace(namespaceName);
  101. }
  102.  
  103. if (!VerifyTypesAreCaseInsensitiveUnique(ItemCollection))
  104. {
  105. return "";
  106. }
  107.  
  108. fileManager.Process();
  109.  
  110. #>
  111. <#+
  112. string GetResourceString(string resourceName)
  113. {
  114. if(_resourceManager == null)
  115. {
  116. _resourceManager = new System.Resources.ResourceManager("System.Data.Entity.Design", typeof(System.Data.Entity.Design.MetadataItemCollectionFactory).Assembly);
  117. }
  118.  
  119. return _resourceManager.GetString(resourceName, null);
  120. }
  121. System.Resources.ResourceManager _resourceManager;
  122.  
  123. void WriteHeader(EntityFrameworkTemplateFileManager fileManager)
  124. {
  125. fileManager.StartHeader();
  126. #>
  127. //------------------------------------------------------------------------------
  128. // <auto-generated>
  129. // <#=GetResourceString("Template_GeneratedCodeCommentLine1")#>
  130. //
  131. // <#=GetResourceString("Template_GeneratedCodeCommentLine2")#>
  132. // <#=GetResourceString("Template_GeneratedCodeCommentLine3")#>
  133. // </auto-generated>
  134. //------------------------------------------------------------------------------
  135.  
  136. <#+
  137. fileManager.EndBlock();
  138. }
  139.  
  140. void BeginNamespace(string namespaceName, CodeGenerationTools code)
  141. {
  142. namespaceName = namespaceName;
  143. CodeRegion region = new CodeRegion(this);
  144. if (!String.IsNullOrEmpty(namespaceName))
  145. {
  146. #>
  147. namespace <#=code.EscapeNamespace(namespaceName)#>
  148. {
  149. <#+
  150. PushIndent(CodeRegion.GetIndent(1));
  151. }
  152. }
  153.  
  154. void EndNamespace(string namespaceName)
  155. {
  156. if (!String.IsNullOrEmpty(namespaceName))
  157. {
  158. PopIndent();
  159. #>
  160.  
  161. <#+
  162. }
  163. }
  164.  
  165. string WriteJavaProperty(System.Data.Metadata.Edm.EdmProperty ent,string name)
  166. {
  167. CodeGenerationTools code = new CodeGenerationTools(this);
  168. var typeName = code.Escape(ent.TypeUsage);
  169. string rtnVal;
  170. switch(typeName)
  171. {
  172. case "string":
  173. rtnVal= "String";
  174. break;
  175. case "DateTime":
  176. rtnVal= "Date";
  177. break;
  178. case "bool":
  179. rtnVal= "boolean";
  180. break;
  181. case "decimal":
  182. rtnVal= "Long";
  183. break;
  184. case "Nullable<System.DateTime>":
  185. case "System.DateTime":
  186. rtnVal= "Date";
  187. break;
  188. case "Nullable<int>":
  189. rtnVal= "Int";
  190. break;
  191. case "System.Guid":
  192. rtnVal= "string";
  193. break;
  194. case "Nullable<bool>":
  195. rtnVal="Boolean";
  196. break;
  197. case "Nullable<double>":
  198. rtnVal="Double";
  199. break;
  200. default:
  201. rtnVal= typeName;
  202. break;
  203. }
  204. rtnVal = rtnVal.Substring(0,1).ToUpper()+rtnVal.Substring(1,rtnVal.Length-1);
  205. return "get"+rtnVal;
  206. }
  207.  
  208. string PropertyVirtualModifier(string accessibility)
  209. {
  210. return accessibility + (accessibility != "private" ? "" : "");
  211. }
  212.  
  213. bool VerifyTypesAreCaseInsensitiveUnique(EdmItemCollection itemCollection)
  214. {
  215. var alreadySeen = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  216. foreach(var type in itemCollection.GetItems<StructuralType>())
  217. {
  218. if (!(type is EntityType || type is ComplexType))
  219. {
  220. continue;
  221. }
  222.  
  223. if (alreadySeen.ContainsKey(type.FullName))
  224. {
  225. Error(String.Format(CultureInfo.CurrentCulture, "This template does not support types that differ only by case, the types {0} are not supported", type.FullName));
  226. return false;
  227. }
  228. else
  229. {
  230. alreadySeen.Add(type.FullName, true);
  231. }
  232. }
  233.  
  234. return true;
  235. }
  236.  
  237. #>

当然如果你说我不用保存到web service,而只是保存在sqllite里面,那么你只需要修改的是call.java其他的就完全不用修改了,方便吧。

到这里对数据保存是不是就不在用过多的去配置了?

Android 与 Webservice 的快速保存的更多相关文章

  1. 黎活明8天快速掌握android视频教程--12_文件的保存与读取

    1.当前是把文件保存当前手机的app的data目录下 我们来看看操作保存文件的业务类 package contract.test.savafileapplication; import android ...

  2. Android平台调用WebService详解

    上篇文章已经对Web Service及其相关知识进行了介绍(Android开发之WebService介绍 ),相信有的朋友已经忍耐不住想试试在Android应用中调用Web Service.本文将通过 ...

  3. 网摘Android调用WebService

    这边特别注意调用的.net WCF 接口的绑定方式.以前一直用的wxHttpbinding,一直连不上.改成BasicHTTPbinding就能连上了 上篇文章已经对Web Service及其相关知识 ...

  4. Android调用WebService(转)

    Android调用WebService WebService是一种基于SOAP协议的远程调用标准,通过 webservice可以将不同操作系统平台.不同语言.不同技术整合到一块.在Android SD ...

  5. android loginDemo +WebService用户登录验证

        android loginDemo +WebService用户登录验证 本文是基于android4.0下的loginActivity Demo和android下的Webservice实现的.l ...

  6. 解决android开发webservice的发布与数据库连接的问题

    由于app后续开发的需要,移植了两次webservice和数据库,遇到了不少问题,也花费了很多时间,实践告诉我要学会寻找问题的根源,这样才能在开发中节省时间,尽快解决问题!好,废话不多说,转入正题…… ...

  7. Android GIS +webservice

    Android新手经典入门教程 Android开发教程(完全免费版) Android SDK v3.1.0 Android定位功能(一) Android定位功能(二) Android 百度地图开发(一 ...

  8. 如何解析android访问webservice返回的SoapObject数据(可用)

    怎么解析android访问webservice返回的SoapObject数据 本帖最后由 kkDragon123 于 2013-03-26 15:50:07 编辑 我的数据如下:mingdanResp ...

  9. 纠正网上乱传的android调用Webservice方法。

    1.写作背景: 笔者想实现android调用webservice,可是网上全是不管对与错乱转载的文章,结果不但不能解决问题,只会让人心烦,所以笔者决定将自己整理好的能用的android调用webser ...

随机推荐

  1. 通过uiview动画来放大图片

    UIImage *image=[UIImage imageNamed:"]; UIImageView *imageView=[[UIImageView alloc]init]; imageV ...

  2. java cpu load

    $ps -Lp 179093 cu | more USER PID LWP %CPU NLWP %MEM VSZ RSS TTY STAT START TIME COMMAND admin 17909 ...

  3. iOS 设计模式之单例

    设计模式:单例 一.  单例模式是一种常用的软件设计模式.在它的核心结构中只包含一个被称为单例类的特殊类.通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并 ...

  4. mysql_DML_delete

    delete from 表名   删除表里的数据 可以配合where试用

  5. 一路踩过的坑 php

    1.数据表唯一索引  (两列字段,组合索引) 遇到的情形:项目搭建新测试环境(其实就是所谓的灰度 与线上一致的一个环境):从线上拉回来代码搭建的,数据也是来自于线上数据,但是由于线上数据有部分为机密数 ...

  6. 第四节 数据格式化和ModelAttribute注解的介绍

    从来都不坦荡,情绪都写在脸上:不开心的时候,不爱说话,笑也勉强. 课堂笔记,如果这么写,不仅仅是手速,还要有语速, 这样不太适合! --胖先生 关于数据传递: 客户端传递数据到服务端: 1.使用普通的 ...

  7. List<T>.Sort() 排序的用法

    List<T> 可以通过 .Sort()进行排序,但是当 T 对象为自定义类型时(比如自定义模型),就需要 IComparable接口重写其中的方法来实现,实现代码如下: class Pr ...

  8. 洛谷P1717 钓鱼

    P1717 钓鱼 41通过 116提交 题目提供者该用户不存在 标签贪心 难度提高+/省选- 提交该题 讨论 题解 记录 最新讨论 暂时没有讨论 题目描述 话说发源于小朋友精心设计的游戏被电脑组的童鞋 ...

  9. [Excel操作]Microsoft Office Excel 不能访问文件

    最近,客户服务器迁移,因操作系统环境变化而引起的的环境问题一堆,遇到的问题并解决方法在“[Excel]操作”类别会体现. Microsoft Office Excel 不能访问文件“C:\\LMSEx ...

  10. 【JS Note】undefined与null

    在Javascript中有这两种原始类型: Undefined与Null.而这两种原始类型都各自只有一个值,分别是undefined,null. undefined: 1.变量声明后未赋值,则变量会被 ...