volley5--Request<T>类的介绍

本文深入解析了Volley框架中的Request类,介绍了其属性、构造方法、重试策略及实现细节。并通过StringRequest实例展示了如何继承Request类以实现具体的网络请求。

源码:

  1 /*
  2  * Copyright (C) 2011 The Android Open Source Project
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package com.android.volley;
 18 
 19 import android.net.TrafficStats;
 20 import android.net.Uri;
 21 import android.os.Handler;
 22 import android.os.Looper;
 23 import android.text.TextUtils;
 24 import com.android.volley.VolleyLog.MarkerLog;
 25 
 26 import java.io.UnsupportedEncodingException;
 27 import java.net.URLEncoder;
 28 import java.util.Collections;
 29 import java.util.Map;
 30 
 31 /**
 32  * Base class for all network requests.
 33  *
 34  * @param <T> The type of parsed response this request expects.
 35  */
 36 public abstract class Request<T> implements Comparable<Request<T>> {
 37 
 38     /**
 39      * Default encoding for POST or PUT parameters. See {@link #getParamsEncoding()}.
 40      */
 41     private static final String DEFAULT_PARAMS_ENCODING = "UTF-8";
 42 
 43     /**
 44      * Supported request methods.
 45      */
 46     public interface Method {
 47         int DEPRECATED_GET_OR_POST = -1;
 48         int GET = 0;
 49         int POST = 1;
 50         int PUT = 2;
 51         int DELETE = 3;
 52         int HEAD = 4;
 53         int OPTIONS = 5;
 54         int TRACE = 6;
 55         int PATCH = 7;
 56     }
 57 
 58     /** An event log tracing the lifetime of this request; for debugging. */
 59     private final MarkerLog mEventLog = MarkerLog.ENABLED ? new MarkerLog() : null;
 60 
 61     /**
 62      * Request method of this request.  Currently supports GET, POST, PUT, DELETE, HEAD, OPTIONS,
 63      * TRACE, and PATCH.
 64      */
 65     private final int mMethod;
 66 
 67     /** URL of this request. */
 68     private final String mUrl;
 69 
 70     /** The redirect url to use for 3xx http responses */
 71     private String mRedirectUrl;
 72 
 73     /** The unique identifier of the request */
 74     private String mIdentifier;
 75 
 76     /** Default tag for {@link TrafficStats}. */
 77     private final int mDefaultTrafficStatsTag;
 78 
 79     /** Listener interface for errors. */
 80     private Response.ErrorListener mErrorListener;
 81 
 82     /** Sequence number of this request, used to enforce FIFO ordering. */
 83     private Integer mSequence;
 84 
 85     /** The request queue this request is associated with. */
 86     private RequestQueue mRequestQueue;
 87 
 88     /** Whether or not responses to this request should be cached. */
 89     private boolean mShouldCache = true;
 90 
 91     /** Whether or not this request has been canceled. */
 92     private boolean mCanceled = false;
 93 
 94     /** Whether or not a response has been delivered for this request yet. */
 95     private boolean mResponseDelivered = false;
 96 
 97     /** The retry policy for this request. */
 98     private RetryPolicy mRetryPolicy;
 99 
100     /**
101      * When a request can be retrieved from cache but must be refreshed from
102      * the network, the cache entry will be stored here so that in the event of
103      * a "Not Modified" response, we can be sure it hasn't been evicted from cache.
104      */
105     private Cache.Entry mCacheEntry = null;
106 
107     /** An opaque token tagging this request; used for bulk cancellation. */
108     private Object mTag;
109 
110     /**
111      * Creates a new request with the given URL and error listener.  Note that
112      * the normal response listener is not provided here as delivery of responses
113      * is provided by subclasses, who have a better idea of how to deliver an
114      * already-parsed response.
115      *
116      * @deprecated Use {@link #Request(int, String, com.android.volley.Response.ErrorListener)}.
117      */
118     @Deprecated
119     public Request(String url, Response.ErrorListener listener) {
120         this(Method.DEPRECATED_GET_OR_POST, url, listener);
121     }
122 
123     /**
124      * Creates a new request with the given method (one of the values from {@link Method}),
125      * URL, and error listener.  Note that the normal response listener is not provided here as
126      * delivery of responses is provided by subclasses, who have a better idea of how to deliver
127      * an already-parsed response.
128      */
129     public Request(int method, String url, Response.ErrorListener listener) {
130         mMethod = method;
131         mUrl = url;
132         mIdentifier = createIdentifier(method, url);
133         mErrorListener = listener;
134         setRetryPolicy(new DefaultRetryPolicy());
135 
136         mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url);
137     }
138 
139     /**
140      * Return the method for this request.  Can be one of the values in {@link Method}.
141      */
142     public int getMethod() {
143         return mMethod;
144     }
145 
146     /**
147      * Set a tag on this request. Can be used to cancel all requests with this
148      * tag by {@link RequestQueue#cancelAll(Object)}.
149      *
150      * @return This Request object to allow for chaining.
151      */
152     public Request<?> setTag(Object tag) {
153         mTag = tag;
154         return this;
155     }
156 
157     /**
158      * Returns this request's tag.
159      * @see Request#setTag(Object)
160      */
161     public Object getTag() {
162         return mTag;
163     }
164 
165     /**
166      * @return this request's {@link com.android.volley.Response.ErrorListener}.
167      */
168     public Response.ErrorListener getErrorListener() {
169         return mErrorListener;
170     }
171 
172     /**
173      * @return A tag for use with {@link TrafficStats#setThreadStatsTag(int)}
174      */
175     public int getTrafficStatsTag() {
176         return mDefaultTrafficStatsTag;
177     }
178 
179     /**
180      * @return The hashcode of the URL's host component, or 0 if there is none.
181      */
182     private static int findDefaultTrafficStatsTag(String url) {
183         if (!TextUtils.isEmpty(url)) {
184             Uri uri = Uri.parse(url);
185             if (uri != null) {
186                 String host = uri.getHost();
187                 if (host != null) {
188                     return host.hashCode();
189                 }
190             }
191         }
192         return 0;
193     }
194 
195     /**
196      * Sets the retry policy for this request.
197      *
198      * @return This Request object to allow for chaining.
199      */
200     public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
201         mRetryPolicy = retryPolicy;
202         return this;
203     }
204 
205     /**
206      * Adds an event to this request's event log; for debugging.
207      */
208     public void addMarker(String tag) {
209         if (MarkerLog.ENABLED) {
210             mEventLog.add(tag, Thread.currentThread().getId());
211         }
212     }
213 
214     /**
215      * Notifies the request queue that this request has finished (successfully or with error).
216      *
217      * <p>Also dumps all events from this request's event log; for debugging.</p>
218      */
219     void finish(final String tag) {
220         if (mRequestQueue != null) {
221             mRequestQueue.finish(this);
222             onFinish();
223         }
224         if (MarkerLog.ENABLED) {
225             final long threadId = Thread.currentThread().getId();
226             if (Looper.myLooper() != Looper.getMainLooper()) {
227                 // If we finish marking off of the main thread, we need to
228                 // actually do it on the main thread to ensure correct ordering.
229                 Handler mainThread = new Handler(Looper.getMainLooper());
230                 mainThread.post(new Runnable() {
231                     @Override
232                     public void run() {
233                         mEventLog.add(tag, threadId);
234                         mEventLog.finish(this.toString());
235                     }
236                 });
237                 return;
238             }
239 
240             mEventLog.add(tag, threadId);
241             mEventLog.finish(this.toString());
242         }
243     }
244 
245     /**
246      * clear listeners when finished
247      */
248     protected void onFinish() {
249         mErrorListener = null;
250     }
251 
252     /**
253      * Associates this request with the given queue. The request queue will be notified when this
254      * request has finished.
255      *
256      * @return This Request object to allow for chaining.
257      */
258     public Request<?> setRequestQueue(RequestQueue requestQueue) {
259         mRequestQueue = requestQueue;
260         return this;
261     }
262 
263     /**
264      * Sets the sequence number of this request.  Used by {@link RequestQueue}.
265      *
266      * @return This Request object to allow for chaining.
267      */
268     public final Request<?> setSequence(int sequence) {
269         mSequence = sequence;
270         return this;
271     }
272 
273     /**
274      * Returns the sequence number of this request.
275      */
276     public final int getSequence() {
277         if (mSequence == null) {
278             throw new IllegalStateException("getSequence called before setSequence");
279         }
280         return mSequence;
281     }
282 
283     /**
284      * Returns the URL of this request.
285      */
286     public String getUrl() {
287         return (mRedirectUrl != null) ? mRedirectUrl : mUrl;
288     }
289 
290     /**
291      * Returns the URL of the request before any redirects have occurred.
292      */
293     public String getOriginUrl() {
294         return mUrl;
295     }
296 
297     /**
298      * Returns the identifier of the request.
299      */
300     public String getIdentifier() {
301         return mIdentifier;
302     }
303 
304     /**
305      * Sets the redirect url to handle 3xx http responses.
306      */
307     public void setRedirectUrl(String redirectUrl) {
308         mRedirectUrl = redirectUrl;
309     }
310 
311     /**
312      * Returns the cache key for this request.  By default, this is the URL.
313      */
314     public String getCacheKey() {
315         return mMethod + ":" + mUrl;
316     }
317 
318     /**
319      * Annotates this request with an entry retrieved for it from cache.
320      * Used for cache coherency support.
321      *
322      * @return This Request object to allow for chaining.
323      */
324     public Request<?> setCacheEntry(Cache.Entry entry) {
325         mCacheEntry = entry;
326         return this;
327     }
328 
329     /**
330      * Returns the annotated cache entry, or null if there isn't one.
331      */
332     public Cache.Entry getCacheEntry() {
333         return mCacheEntry;
334     }
335 
336     /**
337      * Mark this request as canceled.  No callback will be delivered.
338      */
339     public void cancel() {
340         mCanceled = true;
341     }
342 
343     /**
344      * Returns true if this request has been canceled.
345      */
346     public boolean isCanceled() {
347         return mCanceled;
348     }
349 
350     /**
351      * Returns a list of extra HTTP headers to go along with this request. Can
352      * throw {@link AuthFailureError} as authentication may be required to
353      * provide these values.
354      * @throws AuthFailureError In the event of auth failure
355      */
356     public Map<String, String> getHeaders() throws AuthFailureError {
357         return Collections.emptyMap();
358     }
359 
360     /**
361      * Returns a Map of POST parameters to be used for this request, or null if
362      * a simple GET should be used.  Can throw {@link AuthFailureError} as
363      * authentication may be required to provide these values.
364      *
365      * <p>Note that only one of getPostParams() and getPostBody() can return a non-null
366      * value.</p>
367      * @throws AuthFailureError In the event of auth failure
368      *
369      * @deprecated Use {@link #getParams()} instead.
370      */
371     @Deprecated
372     protected Map<String, String> getPostParams() throws AuthFailureError {
373         return getParams();
374     }
375 
376     /**
377      * Returns which encoding should be used when converting POST parameters returned by
378      * {@link #getPostParams()} into a raw POST body.
379      *
380      * <p>This controls both encodings:
381      * <ol>
382      *     <li>The string encoding used when converting parameter names and values into bytes prior
383      *         to URL encoding them.</li>
384      *     <li>The string encoding used when converting the URL encoded parameters into a raw
385      *         byte array.</li>
386      * </ol>
387      *
388      * @deprecated Use {@link #getParamsEncoding()} instead.
389      */
390     @Deprecated
391     protected String getPostParamsEncoding() {
392         return getParamsEncoding();
393     }
394 
395     /**
396      * @deprecated Use {@link #getBodyContentType()} instead.
397      */
398     @Deprecated
399     public String getPostBodyContentType() {
400         return getBodyContentType();
401     }
402 
403     /**
404      * Returns the raw POST body to be sent.
405      *
406      * @throws AuthFailureError In the event of auth failure
407      *
408      * @deprecated Use {@link #getBody()} instead.
409      */
410     @Deprecated
411     public byte[] getPostBody() throws AuthFailureError {
412         // Note: For compatibility with legacy clients of volley, this implementation must remain
413         // here instead of simply calling the getBody() function because this function must
414         // call getPostParams() and getPostParamsEncoding() since legacy clients would have
415         // overridden these two member functions for POST requests.
416         Map<String, String> postParams = getPostParams();
417         if (postParams != null && postParams.size() > 0) {
418             return encodeParameters(postParams, getPostParamsEncoding());
419         }
420         return null;
421     }
422 
423     /**
424      * Returns a Map of parameters to be used for a POST or PUT request.  Can throw
425      * {@link AuthFailureError} as authentication may be required to provide these values.
426      *
427      * <p>Note that you can directly override {@link #getBody()} for custom data.</p>
428      *
429      * @throws AuthFailureError in the event of auth failure
430      */
431     protected Map<String, String> getParams() throws AuthFailureError {
432         return null;
433     }
434 
435     /**
436      * Returns which encoding should be used when converting POST or PUT parameters returned by
437      * {@link #getParams()} into a raw POST or PUT body.
438      *
439      * <p>This controls both encodings:
440      * <ol>
441      *     <li>The string encoding used when converting parameter names and values into bytes prior
442      *         to URL encoding them.</li>
443      *     <li>The string encoding used when converting the URL encoded parameters into a raw
444      *         byte array.</li>
445      * </ol>
446      */
447     protected String getParamsEncoding() {
448         return DEFAULT_PARAMS_ENCODING;
449     }
450 
451     /**
452      * Returns the content type of the POST or PUT body.
453      */
454     public String getBodyContentType() {
455         return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
456     }
457 
458     /**
459      * Returns the raw POST or PUT body to be sent.
460      *
461      * <p>By default, the body consists of the request parameters in
462      * application/x-www-form-urlencoded format. When overriding this method, consider overriding
463      * {@link #getBodyContentType()} as well to match the new body format.
464      *
465      * @throws AuthFailureError in the event of auth failure
466      */
467     public byte[] getBody() throws AuthFailureError {
468         Map<String, String> params = getParams();
469         if (params != null && params.size() > 0) {
470             return encodeParameters(params, getParamsEncoding());
471         }
472         return null;
473     }
474 
475     /**
476      * Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
477      */
478     private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
479         StringBuilder encodedParams = new StringBuilder();
480         try {
481             for (Map.Entry<String, String> entry : params.entrySet()) {
482                 encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
483                 encodedParams.append('=');
484                 encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
485                 encodedParams.append('&');
486             }
487             return encodedParams.toString().getBytes(paramsEncoding);
488         } catch (UnsupportedEncodingException uee) {
489             throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
490         }
491     }
492 
493     /**
494      * Set whether or not responses to this request should be cached.
495      *
496      * @return This Request object to allow for chaining.
497      */
498     public final Request<?> setShouldCache(boolean shouldCache) {
499         mShouldCache = shouldCache;
500         return this;
501     }
502 
503     /**
504      * Returns true if responses to this request should be cached.
505      */
506     public final boolean shouldCache() {
507         return mShouldCache;
508     }
509 
510     /**
511      * Priority values.  Requests will be processed from higher priorities to
512      * lower priorities, in FIFO order.
513      */
514     public enum Priority {
515         LOW,
516         NORMAL,
517         HIGH,
518         IMMEDIATE
519     }
520 
521     /**
522      * Returns the {@link Priority} of this request; {@link Priority#NORMAL} by default.
523      */
524     public Priority getPriority() {
525         return Priority.NORMAL;
526     }
527 
528     /**
529      * Returns the socket timeout in milliseconds per retry attempt. (This value can be changed
530      * per retry attempt if a backoff is specified via backoffTimeout()). If there are no retry
531      * attempts remaining, this will cause delivery of a {@link TimeoutError} error.
532      */
533     public final int getTimeoutMs() {
534         return mRetryPolicy.getCurrentTimeout();
535     }
536 
537     /**
538      * Returns the retry policy that should be used  for this request.
539      */
540     public RetryPolicy getRetryPolicy() {
541         return mRetryPolicy;
542     }
543 
544     /**
545      * Mark this request as having a response delivered on it.  This can be used
546      * later in the request's lifetime for suppressing identical responses.
547      */
548     public void markDelivered() {
549         mResponseDelivered = true;
550     }
551 
552     /**
553      * Returns true if this request has had a response delivered for it.
554      */
555     public boolean hasHadResponseDelivered() {
556         return mResponseDelivered;
557     }
558 
559     /**
560      * Subclasses must implement this to parse the raw network response
561      * and return an appropriate response type. This method will be
562      * called from a worker thread.  The response will not be delivered
563      * if you return null.
564      * @param response Response from the network
565      * @return The parsed response, or null in the case of an error
566      */
567     abstract protected Response<T> parseNetworkResponse(NetworkResponse response);
568 
569     /**
570      * Subclasses can override this method to parse 'networkError' and return a more specific error.
571      *
572      * <p>The default implementation just returns the passed 'networkError'.</p>
573      *
574      * @param volleyError the error retrieved from the network
575      * @return an NetworkError augmented with additional information
576      */
577     protected VolleyError parseNetworkError(VolleyError volleyError) {
578         return volleyError;
579     }
580 
581     /**
582      * Subclasses must implement this to perform delivery of the parsed
583      * response to their listeners.  The given response is guaranteed to
584      * be non-null; responses that fail to parse are not delivered.
585      * @param response The parsed response returned by
586      * {@link #parseNetworkResponse(NetworkResponse)}
587      */
588     abstract protected void deliverResponse(T response);
589 
590     /**
591      * Delivers error message to the ErrorListener that the Request was
592      * initialized with.
593      *
594      * @param error Error details
595      */
596     public void deliverError(VolleyError error) {
597         if (mErrorListener != null) {
598             mErrorListener.onErrorResponse(error);
599         }
600     }
601 
602     /**
603      * Our comparator sorts from high to low priority, and secondarily by
604      * sequence number to provide FIFO ordering.
605      */
606     @Override
607     public int compareTo(Request<T> other) {
608         Priority left = this.getPriority();
609         Priority right = other.getPriority();
610 
611         // High-priority requests are "lesser" so they are sorted to the front.
612         // Equal priorities are sorted by sequence number to provide FIFO ordering.
613         return left == right ?
614                 this.mSequence - other.mSequence :
615                 right.ordinal() - left.ordinal();
616     }
617 
618     @Override
619     public String toString() {
620         String trafficStatsTag = "0x" + Integer.toHexString(getTrafficStatsTag());
621         return (mCanceled ? "[X] " : "[ ] ") + getUrl() + " " + trafficStatsTag + " "
622                 + getPriority() + " " + mSequence;
623     }
624 
625     private static long sCounter;
626     /**
627      *  sha1(Request:method:url:timestamp:counter)
628      * @param method http method
629      * @param url               http request url
630      * @return sha1 hash string
631      */
632     private static String createIdentifier(final int method, final String url) {
633         return InternalUtils.sha1Hash("Request:" + method + ":" + url +
634                 ":" + System.currentTimeMillis() + ":" + (sCounter++));
635     }
636 }
Request

 Request<T>中的泛型T,是指解析response以后的结果。在上一篇文章中我们知道,ResponseDelivery会把response分派给对应的request(中文翻译就是,把响应分派给对应的请求)。在我们定义的请求中,需要重写parseNetworkResponse(NetworkResponse response)这个方法,解析请求,解析出来的结果,就是T类型的。

首先是一些属性

  1 /** 
  2  * Base class for all network requests. 
  3  * 请求基类 
  4  * @param <T> The type of parsed response this request expects. 
  5  * T为响应类型 
  6  */  
  7 public abstract class Request<T> implements Comparable<Request<T>> {  
  8   
  9     /** 
 10      * Default encoding for POST or PUT parameters. See {@link #getParamsEncoding()}. 
 11      * 默认编码 
 12      */  
 13     private static final String DEFAULT_PARAMS_ENCODING = "UTF-8";  
 14   
 15     /** 
 16      * Supported request methods. 
 17      * 支持的请求方式 
 18      */  
 19     public interface Method {  
 20         int DEPRECATED_GET_OR_POST = -1;  
 21         int GET = 0;  
 22         int POST = 1;  
 23         int PUT = 2;  
 24         int DELETE = 3;  
 25         int HEAD = 4;  
 26         int OPTIONS = 5;  
 27         int TRACE = 6;  
 28         int PATCH = 7;  
 29     }  
 30   
 31     /**  
 32      * An event log tracing the lifetime of this request; for debugging. 
 33      * 用于跟踪请求的生存时间,用于调试  
 34      * */  
 35     private final MarkerLog mEventLog = MarkerLog.ENABLED ? new MarkerLog() : null;  
 36   
 37     /** 
 38      * Request method of this request.  Currently supports GET, POST, PUT, DELETE, HEAD, OPTIONS, 
 39      * TRACE, and PATCH. 
 40      * 当前请求方式 
 41      */  
 42     private final int mMethod;  
 43   
 44     /**  
 45      * URL of this request.  
 46      * 请求地址  
 47      */  
 48     private final String mUrl;  
 49       
 50     /**  
 51      * The redirect url to use for 3xx http responses  
 52      * 重定向地址  
 53      */  
 54     private String mRedirectUrl;  
 55   
 56     /**  
 57      * The unique identifier of the request 
 58      * 该请求的唯一凭证  
 59      */  
 60     private String mIdentifier;  
 61   
 62     /**  
 63      * Default tag for {@link TrafficStats}. 
 64      * 流量统计标签  
 65      */  
 66     private final int mDefaultTrafficStatsTag;  
 67   
 68     /**  
 69      * Listener interface for errors. 
 70      * 错误监听器  
 71      */  
 72     private final Response.ErrorListener mErrorListener;  
 73   
 74     /**  
 75      * Sequence number of this request, used to enforce FIFO ordering. 
 76      * 请求序号,用于fifo算法  
 77      */  
 78     private Integer mSequence;  
 79   
 80     /**  
 81      * The request queue this request is associated with. 
 82      * 请求所在的请求队列  
 83      */  
 84     private RequestQueue mRequestQueue;  
 85   
 86     /**  
 87      * Whether or not responses to this request should be cached. 
 88      * 是否使用缓存响应请求  
 89      */  
 90     private boolean mShouldCache = true;  
 91   
 92     /**  
 93      * Whether or not this request has been canceled. 
 94      * 该请求是否被取消  
 95      */  
 96     private boolean mCanceled = false;  
 97   
 98     /**  
 99      * Whether or not a response has been delivered for this request yet. 
100      * 该请求是否已经被响应  
101      */  
102     private boolean mResponseDelivered = false;  
103       
104     /** 
105      * A cheap variant of request tracing used to dump slow requests. 
106      * 一个简单的变量,跟踪请求,用来抛弃过慢的请求 
107      * 请求产生时间  
108      */  
109     private long mRequestBirthTime = 0;  
110   
111     /** Threshold at which we should log the request (even when debug logging is not enabled). */  
112     private static final long SLOW_REQUEST_THRESHOLD_MS = 3000;  
113   
114     /**  
115      * The retry policy for this request. 
116      * 请求重试策略  
117      */  
118     private RetryPolicy mRetryPolicy;  
119   
120     /** 
121      * When a request can be retrieved from cache but must be refreshed from 
122      * the network, the cache entry will be stored here so that in the event of 
123      * a "Not Modified" response, we can be sure it hasn't been evicted from cache. 
124      * 缓存记录。当请求可以从缓存中获得响应,但必须从网络上更新时。我们保留这个缓存记录,所以一旦从网络上获得的响应带有Not Modified 
125      * (没有更新)时,来保证这个缓存没有被回收. 
126      */  
127     private Cache.Entry mCacheEntry = null;  
128   
129     /** 
130      *  An opaque token tagging this request; used for bulk cancellation. 
131      *  用于自定义标记,可以理解为用于请求的分类  
132      */  
133     private Object mTag;  

接下来看构造方法

/** 
     * Creates a new request with the given method (one of the values from {@link Method}), 
     * URL, and error listener.  Note that the normal response listener is not provided here as 
     * delivery of responses is provided by subclasses, who have a better idea of how to deliver 
     * an already-parsed response. 
     * 根据请求方式,创建新的请求(需要地址,错误监听器等参数)  
     */  
    public Request(int method, String url, Response.ErrorListener listener) {  
        mMethod = method;  
        mUrl = url;  
        mIdentifier = createIdentifier(method, url);//为请求创建唯一凭证  
        mErrorListener = listener;//设定监听器  
        setRetryPolicy(new DefaultRetryPolicy());//设置默认重试策略  
  
        mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url);//设置流量标志  
    } 

首先是请求方式,请求地址的设定,这是作为一个请求必须有的。然后是监听器的设定,注意这里只是这是了ErrorListner,说明errorListener是必须的,但是正确响应,我们有可能不处理。这样设定是合理的,因为出错了,我们必须处理,至于请求成功,我们可以不处理。那么我们想处理成功的请求怎么办呢,这需要在子类中重写构造方法(例如StringRequest)。

 

然后是创建了一个唯一凭证

/** 
     *  sha1(Request:method:url:timestamp:counter) 
     * @param method http method 
     * @param url               http request url 
     * @return sha1 hash string 
     * 利用请求方式和地址,进行sha1加密,创建该请求的唯一凭证 
     */  
    private static String createIdentifier(final int method, final String url) {  
        return InternalUtils.sha1Hash("Request:" + method + ":" + url +  
                ":" + System.currentTimeMillis() + ":" + (sCounter++));  
    } 

由上面的方法可以看出,这个凭证和当前时间有关,因此是独一无二的

 

接着是设置重试策略,这个类等下再介绍,接下来是流量标志的设置,所谓流量标志,是用于调试日志记录的,不是重点

/** 
     * @return The hashcode of the URL's host component, or 0 if there is none. 
     * 返回url的host(主机地址)部分的hashcode,如果host不存在,返回0 
     */  
    private static int findDefaultTrafficStatsTag(String url) {  
        if (!TextUtils.isEmpty(url)) {  
            Uri uri = Uri.parse(url);  
            if (uri != null) {  
                String host = uri.getHost();  
                if (host != null) {  
                    return host.hashCode();  
                }  
            }  
        }  
        return 0;  
    }  

我们再回过头来看这个重试策略。

 

volley为重试策略专门定义了一个类,这样我们就可以根据需要实现自己的重试策略了,至于源码内部,为我们提供了一个默认的重试策略DefaultRetryPolicy()

要介绍重试策略,我们先看重试策略的基类RetryPolicy

/** 
 * Retry policy for a request. 
 * 请求重试策略类 
 */  
public interface RetryPolicy {  
  
    /** 
     * Returns the current timeout (used for logging). 
     * 获得当前时间,用于日志 
     */  
    public int getCurrentTimeout();  
  
    /** 
     * Returns the current retry count (used for logging). 
     * 返回当前重试次数,用于日志 
     */  
    public int getCurrentRetryCount();  
  
    /** 
     * Prepares for the next retry by applying a backoff to the timeout. 
     * @param error The error code of the last attempt. 
     * @throws VolleyError In the event that the retry could not be performed (for example if we 
     * ran out of attempts), the passed in error is thrown. 
     * 重试实现 
     */  
    public void retry(VolleyError error) throws VolleyError;  
}  

重要的是retry()这个方法,我们来看DefaultRetryPolicy里面这个方法的具体实现

/** 
     * Prepares for the next retry by applying a backoff to the timeout. 
     * @param error The error code of the last attempt. 
     */  
    @Override  
    public void retry(VolleyError error) throws VolleyError {  
        mCurrentRetryCount++;//当前重试次数  
        mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier);//当前超出时间  
        if (!hasAttemptRemaining()) {//是否已经到达最大重试次数  
            throw error;  
        }  
    }  
  
    /** 
     * Returns true if this policy has attempts remaining, false otherwise. 
     * 是否还重试 
     */  
    protected boolean hasAttemptRemaining() {  
        return mCurrentRetryCount <= mMaxNumRetries;//最大重试次数  
    }  

可以看到,在默认的重试策略中,只是简单地统计了重试的次数,然后,在超出最大次数以后,抛出异常。

 

就这么简单,那么究竟volley是怎么实现重试的呢?

实际上,当从队列中取出一个request去进行网络请求的时候,我们是写在一个死循环里面的(在以后的代码可以看到,这样不贴出来以免类过多造成困扰)。

一旦请求失败,就会调用上面的retry()方法,但是没有跳出循环。直到请求成功获得response,才return。如果一直请求失败,根据上面的重试策略,最后会抛出VolleyError异常,这个异常不处理,而是通过throws向外抛,从而结束死循环。

从程序设计的角度来说,通过抛出异常结束死循环,显得不是那么的优雅(通常我们用设置标记的方法结束循环),但是在volley中使用了这个方式,原因是对于这个异常,要交给程序员自己处理,虽然这样使异常传递的过程变得复杂,但是增加了程序的灵活性。

最终的异常,我们会在Request<T>的parseNetworkError()和deliverError()方法里面处理,parseNetworkError()用于解析Volleyerror,deliverError()方法回调了上面一开始就提到的ErrorListener

  /** 
     * Subclasses can override this method to parse 'networkError' and return a more specific error. 
     * 
     * <p>The default implementation just returns the passed 'networkError'.</p> 
     * 
     * @param volleyError the error retrieved from the network 
     * @return an NetworkError augmented with additional information 
     * 解析网络错误 
     */  
    public VolleyError parseNetworkError(VolleyError volleyError) {  
        return volleyError;  
    }  
  
    /** 
     * Delivers error message to the ErrorListener that the Request was 
     * initialized with. 
     * 
     * @param error Error details 
     * 分发网络错误 
     */  
    public void deliverError(VolleyError error) {  
        if (mErrorListener != null) {  
            mErrorListener.onErrorResponse(error);  
        }  
    }

其实除了上面两个处理错误的方法,还有两个方法用于处理成功响应,是必须要继承的

/** 
     * Subclasses must implement this to parse the raw network response 
     * and return an appropriate response type. This method will be 
     * called from a worker thread.  The response will not be delivered 
     * if you return null. 
     * @param response Response from the network 
     * @return The parsed response, or null in the case of an error 
     * 解析响应 
     */  
    public abstract Response<T> parseNetworkResponse(NetworkResponse response);  
<pre name="code" class="java">/** 
     * Subclasses must implement this to perform delivery of the parsed 
     * response to their listeners.  The given response is guaranteed to 
     * be non-null; responses that fail to parse are not delivered. 
     * @param response The parsed response returned by 
     * {@link #parseNetworkResponse(NetworkResponse)} 
     * 分发响应 
     */  
    public abstract void deliverResponse(T response);  

parseNetworkResponse(NetworkResponse response)用于将网络response解析为本地response,解析出来的response,会交给deliverResponse(T response)方法。

 

为什么要解析,其实上面已经说过,要将结果解析为T类型。至于这两个方法,其实是在ResponseDelivery响应分发器里面调用的。

看完初始化方法,我们来看结束请求的方法finish(),有时候我们想要主动终止请求,例如停止下载文件,又或者请求已经成功了,我们从队列中去除这个请求

 1 /** 
 2      * Notifies the request queue that this request has finished (successfully or with error). 
 3      * 提醒请求队列,当前请求已经完成(失败或成功) 
 4      * <p>Also dumps all events from this request's event log; for debugging.</p> 
 5      *  
 6      */  
 7     public void finish(final String tag) {  
 8         if (mRequestQueue != null) {  
 9             mRequestQueue.finish(this);//该请求完成  
10         }  
11         if (MarkerLog.ENABLED) {//如果开启调试  
12             final long threadId = Thread.currentThread().getId();//线程id  
13             if (Looper.myLooper() != Looper.getMainLooper()) {//请求不是在主线程  
14                 // If we finish marking off of the main thread, we need to  
15                 // actually do it on the main thread to ensure correct ordering.  
16                 //如果我们不是在主线程记录log,我们需要在主线程做这项工作来保证正确的顺序  
17                 Handler mainThread = new Handler(Looper.getMainLooper());  
18                 mainThread.post(new Runnable() {  
19                     @Override  
20                     public void run() {  
21                         mEventLog.add(tag, threadId);  
22                         mEventLog.finish(this.toString());  
23                     }  
24                 });  
25                 return;  
26             }  
27             //如果在主线程,直接记录  
28             mEventLog.add(tag, threadId);  
29             mEventLog.finish(this.toString());  
30         } else {//不开启调试  
31             long requestTime = SystemClock.elapsedRealtime() - mRequestBirthTime;  
32             if (requestTime >= SLOW_REQUEST_THRESHOLD_MS) {  
33                 VolleyLog.d("%d ms: %s", requestTime, this.toString());  
34             }  
35         }  
36     }  

上面主要是做了一些日志记录的工作,最重要的是调用了mRequestQueue的finish()方法,来从队列中去除这个请求。

 

看完上面的介绍以后,大家是否注意到,Request<T>继承了Comparable<Request<T>>接口,为什么要继承这个接口了,我们当然要来看compareTo()方法了

/** 
     * Our comparator sorts from high to low priority, and secondarily by 
     * sequence number to provide FIFO ordering. 
     */  
    @Override  
    public int compareTo(Request<T> other) {  
        Priority left = this.getPriority();  
        Priority right = other.getPriority();  
  
        // High-priority requests are "lesser" so they are sorted to the front.  
        // Equal priorities are sorted by sequence number to provide FIFO ordering.  
        return left == right ?  
                this.mSequence - other.mSequence :  
                right.ordinal() - left.ordinal();  
    }  

这个方法比较了两个请求的优先级,如果优先级相等,就按照顺序

 

实现这个接口的目的,正如上一篇文章提到的,有的请求比较重要,希望早点执行,也就是说让它排在请求队列的前头

通过比较方法,我们就可以设定请求在请求队列中排队顺序的根据,从而让优先级高的排在前面。

 

OK,Request<T>就基本介绍完了,当然有些属性,例如缓存mCacheEntry,mRedirectUrl重定向地址等我们还没有用到,我们先记住它们,在以后会使用到的。

其实Request<T>类并不复杂,主要就是一些属性的设置,这些属性有的比较难考虑到,例如优先级,重定向地址,自定义标记,重试策略等。

 

最后,我们通过StringRequest来看一下Request<T>类的具体实现

/** 
 * A canned request for retrieving the response body at a given URL as a String. 
 */  
public class StringRequest extends Request<String> {  
    private final Listener<String> mListener;  
  
    /** 
     * Creates a new request with the given method. 
     * 
     * @param method the request {@link Method} to use 
     * @param url URL to fetch the string at 
     * @param listener Listener to receive the String response 
     * @param errorListener Error listener, or null to ignore errors 
     */  
    public StringRequest(int method, String url, Listener<String> listener,  
            ErrorListener errorListener) {  
        super(method, url, errorListener);  
        mListener = listener;  
    }

上面的构造方法中,添加了一个新的接口Listener<String> listener,用于监听成功的response

 

然后是parseNetworkResponse(NetworkResponse response),这个方法

@Override  
    public Response<String> parseNetworkResponse(NetworkResponse response) {  
        String parsed;  
        try {  
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));  
        } catch (UnsupportedEncodingException e) {  
            parsed = new String(response.data);  
        }  
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));  
    }

可以看到,将NetworkResponse解析为String类型的了,然后再构造成对应的本地response

@Override  
    public void deliverResponse(String response) {  
        mListener.onResponse(response);  
    } 

至于deliverResponse(String response),则调用了构造方法里面要求的,新的监听器。

 

到此为止,对于Request<T>的介绍就结束了,由于Request<T>和其他类的耦合并不是特别重,相信是比较容易理解。

在下一篇文章中,我们会来看RequestQueue队列,看看这个队列的作用到底是什么,我们为什么要创建一个队列来保存request而不是直接每个request开启一个线程去加载网络数据。

转载于:https://www.cnblogs.com/ganchuanpu/p/7627180.html

package com.example.kucun2.entity.data; import android.content.Context; import android.util.Log; import com.example.kucun2.entity.; import com.example.kucun2.function.MyAppFnction; import com.example.kucun2.function.TLSUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import java.util.; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.X509TrustManager; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Data { // 数据集合声明(保持原有属性名不变) public static SynchronizedList<Bancai> bancais = new SynchronizedList<>(Bancai.class); public static SynchronizedList<Caizhi> caizhis = new SynchronizedList<>(Caizhi.class); public static SynchronizedList<Mupi> mupis = new SynchronizedList<>(Mupi.class); public static SynchronizedList<Chanpin> chanpins = new SynchronizedList<>(Chanpin.class); public static SynchronizedList<Chanpin_Zujian> chanpinZujians = new SynchronizedList<>(Chanpin_Zujian.class); public static SynchronizedList<Dingdan> dingdans = new SynchronizedList<>(Dingdan.class); public static SynchronizedList<Dingdan_Chanpin> dingdanChanpins = new SynchronizedList<>(Dingdan_Chanpin.class); public static SynchronizedList<Dingdan_chanpin_zujian> dingdanBancais = new SynchronizedList<>(Dingdan_chanpin_zujian.class); public static SynchronizedList<Kucun> kucuns = new SynchronizedList<>(Kucun.class); public static SynchronizedList<Zujian> zujians = new SynchronizedList<>(Zujian.class); public static SynchronizedList<User> users = new SynchronizedList<>(Bancai.class); public static SynchronizedList<Jinhuo> jinhuoList = new SynchronizedList<>(Bancai.class); private static final Gson gson = new Gson(); private static OkHttpClient client ; private static final String TAG = "DataLoader"; public static void loadAllData(Context context, LoadDataCallback callback) { // 确保使用安全的客户端 if (client == null) { client= MyAppFnction.getClient(); } String url = MyAppFnction.getStringResource("string", "url") + MyAppFnction.getStringResource("string", "url_all"); Log.d("url", "loadAllData: " + url); Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "Failed to load data", e); if (callback != null) callback.onFailure(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { Log.e(TAG, "Unexpected response code: " + response.code()); if (callback != null) callback.onFailure(); return; } String responseData = response.body().string(); parseAndAssignData(responseData, context, callback); } }); } // 解析并赋值数据 private static void parseAndAssignData(String jsonData, Context context, LoadDataCallback callback) { // 创建包含所有数据型的TypeToken Type informationType = new TypeToken<Information<AllDataResponse>>(){}.getType(); Information<AllDataResponse> information = gson.fromJson(jsonData, informationType); Log.e(TAG, "Invalid response data"+jsonData); if (information == null || information.getData() == null || information.getStatus() != 200) { Log.e(TAG, "Invalid response data"); if (callback != null) callback.onFailure(); return; } AllDataResponse allData = information.getData(); // 赋值到对应的列表(使用安全方法保持已有引用) updateList(bancais, allData.bancais); updateList(caizhis, allData.caizhis); updateList(mupis, allData.mupis); updateList(chanpins, allData.chanpins); updateList(chanpinZujians, allData.chanpin_zujians); updateList(dingdans, allData.dingdans); updateList(dingdanChanpins, allData.dingdan_chanpins); updateList(dingdanBancais, allData.dingdan_bancais); updateList(kucuns, allData.kucuns); updateList(zujians, allData.zujians); updateList(users, allData.users); updateList(jinhuoList, allData.jinhuos); resolveReferences(); if (callback != null) callback.onSuccess(); } // 更新列表内容但保持对象引用不变 private static <T> void updateList(List<T> existingList, List<T> newList) { if (newList == null) return; existingList.clear(); existingList.addAll(newList); } // 解析对象间的引用关系(使用ID关联) private static void resolveReferences() { // 创建ID到对象的映射 Map<Integer, Bancai> bancaiMap = createIdMap(bancais); Map<Integer, Caizhi> caizhiMap = createIdMap(caizhis); Map<Integer, Mupi> mupiMap = createIdMap(mupis); Map<Integer, Chanpin> chanpinMap = createIdMap(chanpins); Map<Integer, Zujian> zujianMap = createIdMap(zujians); Map<Integer, Dingdan> dingdanMap = createIdMap(dingdans); Map<Integer, Kucun> kucunMap = createIdMap(kucuns); // 解析Bancai引用 for (Bancai bancai : bancais) { if (bancai.getCaizhi() != null) { bancai.setCaizhi(caizhiMap.get(bancai.getCaizhi().getId())); } if (bancai.getMupi1() != null) { bancai.setMupi1(mupiMap.get(bancai.getMupi1().getId())); } if (bancai.getMupi2() != null) { bancai.setMupi2(mupiMap.get(bancai.getMupi2().getId())); } } // 解析Kucun引用 for (Kucun kucun : kucuns) { if (kucun.getBancai() != null) { kucun.setBancai(bancaiMap.get(kucun.getBancai().getId())); } } // 解析订单相关的嵌套对象 for (Dingdan_Chanpin dc : dingdanChanpins) { if (dc.getDingdan() != null) { dc.setDingdan(dingdanMap.get(dc.getDingdan().getId())); } if (dc.getChanpin() != null) { dc.setChanpin(chanpinMap.get(dc.getChanpin().getId())); } } // 解析产品相关的嵌套对象 for (Chanpin_Zujian cz : chanpinZujians) { if (cz.getChanpin() != null) { cz.setChanpin(chanpinMap.get(cz.getChanpin().getId())); } if (cz.getZujian() != null) { cz.setZujian(zujianMap.get(cz.getZujian().getId())); } if (cz.getBancai() != null) { cz.setBancai(bancaiMap.get(cz.getBancai().getId())); } } // 解析库存关联 for (Kucun k : kucuns) { if (k.getBancai() != null) { k.setBancai(bancaiMap.get(k.getBancai().getId())); } } } // 创建ID到对象的映射 private static <T extends EntityClassGrassrootsid> Map<Integer, T> createIdMap(List<T> list) { Map<Integer, T> map = new HashMap<>(); for (T item : list) { map.put(item.getId(), item); } return map; } // 回调接口 public interface LoadDataCallback { void onSuccess(); void onFailure(); } // 内部用于解析JSON响应 public static class AllDataResponse { public List<Bancai> bancais; public List<Caizhi> caizhis; public List<Mupi> mupis; public List<Chanpin> chanpins; public List<Chanpin_Zujian> chanpin_zujians; public List<Dingdan> dingdans; public List<Dingdan_Chanpin> dingdan_chanpins; public List<Dingdan_chanpin_zujian> dingdan_bancais; public List<Kucun> kucuns; public List<Zujian> zujians; public List<User> users; public List<Jinhuo> jinhuos; } }package com.example.kucun2.entity.data; import android.util.Log; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** 支持数据变更自动同步的泛型集合 基于SynchronizableEntity的事件机制实现数据变更自动同步 @param <T> 必须是SynchronizableEntity或其子 */ public class SynchronizedList<T extends SynchronizableEntity> implements List<T> { // 使用ArrayList作为底层存储 private final List<T> list = new ArrayList<>(); public SynchronizedList(Class T ) { } // 实体变更监听器 private final EntityChangeListener<T> entityChangeListener = new EntityChangeListener<>(); @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(Object o) { return list.contains(o); } @Override public Iterator<T> iterator() { return new SyncedIterator<>(list.iterator(), entityChangeListener); } @Override public Object[] toArray() { return list.toArray(); } @Override public <E> E[] toArray(E[] a) { return list.toArray(a); } // 添加元素时注册监听器 @Override public boolean add(T element) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } Log.d(“z”,“element”); return list.add(element); } // 移除元素时注销监听器 @Override public boolean remove(Object o) { if (o instanceof SynchronizableEntity) { ((SynchronizableEntity) o).removePropertyChangeListener(entityChangeListener); } return list.remove(o); } @Override public boolean containsAll(Collection<?> c) { return list.containsAll©; } // 批量添加时逐个注册监听器 @Override public boolean addAll(Collection<? extends T> c) { for (T element : c) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } } return list.addAll©; } @Override public boolean addAll(int index, Collection<? extends T> c) { for (T element : c) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } } return list.addAll(index, c); } // 批量移除时逐个注销监听器 @Override public boolean removeAll(Collection<?> c) { for (Object o : c) { if (o instanceof SynchronizableEntity) { ((SynchronizableEntity) o).removePropertyChangeListener(entityChangeListener); } } return list.removeAll©; } @Override public boolean retainAll(Collection<?> c) { // 先移除未保留元素的监听器 for (T element : list) { if (!c.contains(element)) { element.removePropertyChangeListener(entityChangeListener); } } return list.retainAll©; } // 清空集合时移除所有监听器 @Override public void clear() { for (T element : list) { element.removePropertyChangeListener(entityChangeListener); } list.clear(); } @Override public T get(int index) { return list.get(index); } // 替换元素时更新监听器 @Override public T set(int index, T element) { T oldElement = list.get(index); if (oldElement != null) { oldElement.removePropertyChangeListener(entityChangeListener); } if (element != null) { element.addPropertyChangeListener(entityChangeListener); } return list.set(index, element); } // 在指定位置添加元素时注册监听器 @Override public void add(int index, T element) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } list.add(index, element); } // 移除元素时注销监听器 @Override public T remove(int index) { T removed = list.remove(index); if (removed != null) { removed.removePropertyChangeListener(entityChangeListener); } return removed; } @Override public int indexOf(Object o) { return list.indexOf(o); } @Override public int lastIndexOf(Object o) { return list.lastIndexOf(o); } @Override public ListIterator<T> listIterator() { return new SyncedListIterator<>(list.listIterator(), entityChangeListener); } @Override public ListIterator<T> listIterator(int index) { return new SyncedListIterator<>(list.listIterator(index), entityChangeListener); } @Override public List<T> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } /** 内部实体变更监听器 监听属性变化并触发同步操作 */ private static class EntityChangeListener<T extends SynchronizableEntity> implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { @SuppressWarnings(“unchecked”) T entity = (T) evt.getSource(); entity.sync(); // 触发同步操作 } } /** 增强的Iterator实现 移除元素时自动注销监听器 */ private static class SyncedIterator<T extends SynchronizableEntity> implements Iterator<T> { private final Iterator<T> iterator; private final EntityChangeListener<T> listener; private T current; public SyncedIterator(Iterator<T> iterator, EntityChangeListener<T> listener) { this.iterator = iterator; this.listener = listener; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { current = iterator.next(); return current; } @Override public void remove() { if (current != null) { current.removePropertyChangeListener(listener); } iterator.remove(); } } /** 增强的ListIterator实现 支持添加/设置元素时的监听器管理 */ private static class SyncedListIterator<T extends SynchronizableEntity> implements ListIterator<T> { private final ListIterator<T> iterator; private final EntityChangeListener<T> listener; private T lastReturned; public SyncedListIterator(ListIterator<T> iterator, EntityChangeListener<T> listener) { this.iterator = iterator; this.listener = listener; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { lastReturned = iterator.next(); return lastReturned; } @Override public boolean hasPrevious() { return iterator.hasPrevious(); } @Override public T previous() { lastReturned = iterator.previous(); return lastReturned; } @Override public int nextIndex() { return iterator.nextIndex(); } @Override public int previousIndex() { return iterator.previousIndex(); } @Override public void remove() { if (lastReturned != null) { lastReturned.removePropertyChangeListener(listener); } iterator.remove(); } @Override public void set(T e) { if (lastReturned != null) { lastReturned.removePropertyChangeListener(listener); } if (e != null) { e.addPropertyChangeListener(listener); } iterator.set(e); lastReturned = e; } @Override public void add(T e) { if (e != null) { e.addPropertyChangeListener(listener); } iterator.add(e); } } }package com.example.kucun2.entity.data; import android.util.Log; import com.example.kucun2.entity.Information; import com.example.kucun2.function.MyAppFnction; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.HashMap; import java.util.Map; public abstract class SynchronizableEntity implements EntityClassGrassrootsid { public enum SyncState { NEW, MODIFIED, DELETED } SyncState state = SyncState.NEW; // 设置状态的方法 public void setState(SyncState state) { this.state = state; } // 使用标准属性变更支持 private transient PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); // 属性缓存(可选,用于优化) private final Map<String, Object> propertyCache = new HashMap<>(); // 添加属性变更监听器 public void addPropertyChangeListener(PropertyChangeListener listener) { if (changeSupport == null) { changeSupport = new PropertyChangeSupport(this); } changeSupport.addPropertyChangeListener(listener); } // 移除属性变更监听器 public void removePropertyChangeListener(PropertyChangeListener listener) { if (changeSupport != null) { changeSupport.removePropertyChangeListener(listener); } } // 触发属性变更通知(子在setter中调用) protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { if (changeSupport != null && changeSupport.hasListeners(propertyName)) { // 更新属性缓存(可选) propertyCache.put(propertyName, newValue); // 触发变更事件 changeSupport.firePropertyChange(propertyName, oldValue, newValue); } } // 获取属性当前值(可选,用于setter中获取旧值) protected <T> T getCachedProperty(String propertyName) { return (T) propertyCache.get(propertyName); } // 初始化属性缓存(可选,在构造函数中调用) protected void initPropertyCache() { // 初始化所有字段到缓存 for (java.lang.reflect.Field field : getClass().getDeclaredFields()) { try { field.setAccessible(true); propertyCache.put(field.getName(), field.get(this)); } catch (Exception e) { // 忽略初始化异常 } } } /** * 添加url * @param type 操作增删改查 * @return 返回相对url */ public String getEndpoint(String type){ //从String.xml获取url Log.d("getEndpoint", "getEndpoint: "+"url_"+type+"_"+this.getClass().getSimpleName().toLowerCase()); return MyAppFnction.getStringResource("string","url_"+type+"_"+this.getClass().getSimpleName().toLowerCase()); } public void sync() { if (this.state == null) return; try { switch (this.state) { case NEW: createToServer(); break; case MODIFIED: updateToServer(); break; case DELETED: deleteFromServer(); break; } } catch (Exception e) { Log.e("SyncError", "Sync failed for " + getClass().getSimpleName(), e); } } /** * 创建实体到后端 */ private void createToServer() { String endpoint = MyAppFnction.getStringResource("string", "url") + getEndpoint("add"); Information<SynchronizableEntity> requestData = new Information<SynchronizableEntity>(); // 使用Volley、Retrofit或OkHttp执行POST请求 // 伪代码示例: ApiClient.post(endpoint, requestData, new ApiClient.ApiCallback<SynchronizableEntity>() { @Override public void onSuccess(Information<SynchronizableEntity> e) { // 解析服务器返回的ID Log.d("onSuccess",e.toJson()); // String serverId = parseServerId(response); // if (serverId != null) { // // 更新本地ID // setId(serverId); // 需要实体实现setId方法 // } state = SyncState.MODIFIED; } }); } /** * 更新实体到后端 */ private void updateToServer() { String endpoint = MyAppFnction.getStringResource("string", "url") + getEndpoint("update") + "/" + getId(); // 获取实体ID Information<SynchronizableEntity> requestData = new Information<SynchronizableEntity>(); ApiClient.post(endpoint, requestData, new ApiClient.ApiCallback<SynchronizableEntity>() { @Override public void onSuccess(Information<SynchronizableEntity> e) { // 解析服务器返回的ID Log.d("onSuccess",e.toJson()); // String serverId = parseServerId(response); // if (serverId != null) { // // 更新本地ID // setId(serverId); // 需要实体实现setId方法 // } // state = SyncState.MODIFIED; } }); } /** * 从后端删除实体 */ private void deleteFromServer() { String endpoint = MyAppFnction.getStringResource("string", "url") + getEndpoint("delete") + "/" + getId(); ApiClient.delete(endpoint, new ApiClient.ApiCallback<SynchronizableEntity>() { @Override public void onSuccess(Information<SynchronizableEntity> e) { Log.d("SyncDelete", "Successfully deleted " + getId()); } }); } /** * 将实体转换为请求映射 */ protected Information<SynchronizableEntity> toRequestMap(){ return Information.newSuccess(this); } } 初始加载数据时自动同步一直在出发
06-12
/* ========== Dingdan_Chanpin.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; /** 订单产品关联 */ public class Dingdan_Chanpin extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private Dingdan dingdan; private Chanpin chanpin; private Integer shuliang; public Dingdan_Chanpin(Integer id, Dingdan dingdan, Chanpin chanpin, Integer shuliang) { this.id = id; this.dingdan = dingdan; this.chanpin = chanpin; this.shuliang = shuliang; } @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public Dingdan getDingdan() { return dingdan; } public void setDingdan(Dingdan dingdan) { Dingdan oldValue = this.dingdan; this.dingdan = dingdan; firePropertyChange(“dingdan”, oldValue, dingdan); } public Chanpin getChanpin() { return chanpin; } public void setChanpin(Chanpin chanpin) { Chanpin oldValue = this.chanpin; this.chanpin = chanpin; firePropertyChange(“chanpin”, oldValue, chanpin); } public Integer getShuliang() { return shuliang; } public void setShuliang(Integer shuliang) { Integer oldValue = this.shuliang; this.shuliang = shuliang; firePropertyChange(“shuliang”, oldValue, shuliang); } public Dingdan_Chanpin() { } } /* ========== Dingdan_chanpin_zujian.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; /** 、 订单板材关联 */ public class Dingdan_chanpin_zujian extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private Dingdan dingdian; private Chanpin_Zujian zujian; private Bancai bancai; private Integer shuliang; @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public Dingdan getDingdian() { return dingdian; } public void setDingdian(Dingdan dingdian) { Dingdan oldValue = this.dingdian; this.dingdian = dingdian; firePropertyChange(“dingdian”, oldValue, dingdian); } public Chanpin_Zujian getZujian() { return zujian; } public void setZujian(Chanpin_Zujian zujian) { Chanpin_Zujian oldValue = this.zujian; this.zujian = zujian; firePropertyChange(“zujian”, oldValue, zujian); } public Bancai getBancai() { return bancai; } public void setBancai(Bancai bancai) { Bancai oldValue = this.bancai; this.bancai = bancai; firePropertyChange(“bancai”, oldValue, bancai); } public Integer getShuliang() { return shuliang; } public void setShuliang(Integer shuliang) { Integer oldValue = this.shuliang; this.shuliang = shuliang; firePropertyChange(“shuliang”, oldValue, shuliang); } public Dingdan_chanpin_zujian() { } } /* ========== Information.java ========== */ package com.example.kucun2.entity; import android.annotation.SuppressLint; import androidx.annotation.Keep; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; @Keep // 防止Proguard混淆 public class Information<T> { private Integer status; private String text; private T data; // 使用泛型保证型安全 private static final Gson gson = new Gson(); // Gson实例复用 // 构造方法 public Information(Integer status, String text, T data) { this.status = status; this.text = text; this.data = data; } // JSON反序列化构造方法 @SuppressLint(“NewApi”) public Information(Integer status, String text, String jsonData, Type dataType) { this.status = status; this.text = text; try { this.data = gson.fromJson(jsonData, dataType); } catch (JsonSyntaxException e) { this.data = null; // 处理解析失败 } } // 空构造方法 public Information() { } // 序列化为JSON public String toJson() { return gson.toJson(this); } // 静态创建方法 public static <T> Information<T> newSuccess(T data) { return new Information<>(200, “success”, data); } public static Information<String> newSuccess(String text) { return new Information<>(200, “success”, text); } public static <T> Information<T> newFail(int status, String text, T data) { return new Information<>(status, text, data); } // Getter/Setter public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getText() { return text; } public void setText(String text) { this.text = text; } public T getData() { return data; } public void setData(T data) { this.data = data; } } /* ========== Jinhuo.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; import java.util.Date; /** 进货消耗 */ public class Jinhuo extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; //属于哪个订单 private Dingdan dingdan; //属于哪个产品 private Chanpin chanpin; //属于哪个组件 private Zujian zujian; //进的什么板材 private Bancai bancai; //进货数量 private Integer shuliang; private Date date; private User user; public Jinhuo(Integer id, Dingdan dingdan, Chanpin chanpin, Zujian zujian, Bancai bancai, Integer shuliang, Date date, User user) { super(); this.id = id; this.dingdan = dingdan; this.chanpin = chanpin; this.zujian = zujian; this.bancai = bancai; this.shuliang = shuliang; this.date = date; this.user = user; } public Jinhuo() { super(); // TODO Auto-generated constructor stub } @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public Dingdan getDingdan() { return dingdan; } public void setDingdan(Dingdan dingdan) { Dingdan oldValue = this.dingdan; this.dingdan = dingdan; firePropertyChange(“dingdan”, oldValue, dingdan); } public Chanpin getChanpin() { return chanpin; } public void setChanpin(Chanpin chanpin) { Chanpin oldValue = this.chanpin; this.chanpin = chanpin; firePropertyChange(“chanpin”, oldValue, chanpin); } public Zujian getZujian() { return zujian; } public void setZujian(Zujian zujian) { Zujian oldValue = this.zujian; this.zujian = zujian; firePropertyChange(“zujian”, oldValue, zujian); } public Bancai getBancai() { return bancai; } public void setBancai(Bancai bancai) { Bancai oldValue = this.bancai; this.bancai = bancai; firePropertyChange(“bancai”, oldValue, bancai); } public Integer getShuliang() { return shuliang; } public void setShuliang(Integer shuliang) { Integer oldValue = this.shuliang; this.shuliang = shuliang; firePropertyChange(“shuliang”, oldValue, shuliang); } public Date getDate() { return date; } public void setDate(Date date) { Date oldValue = this.date; this.date = date; firePropertyChange(“date”, oldValue, date); } public User getUser() { return user; } public void setUser(User user) { User oldValue = this.user; this.user = user; firePropertyChange(“user”, oldValue, user); } } /* ========== Kucun.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; /** 库存 */ public class Kucun extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private Integer shuliang; private Bancai bancai; @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public Integer getShuliang() { return shuliang; } public void setShuliang(Integer shuliang) { Integer oldValue = this.shuliang; this.shuliang = shuliang; firePropertyChange(“shuliang”, oldValue, shuliang); } public Bancai getBancai() { return bancai; } public void setBancai(Bancai bancai) { Bancai oldValue = this.bancai; this.bancai = bancai; firePropertyChange(“bancai”, oldValue, bancai); } public Kucun() { } public Kucun(Integer id, Integer shuliang, Bancai bancai) { this.id = id; this.shuliang = shuliang; this.bancai = bancai; } } /* ========== Mupi.java ========== */ package com.example.kucun2.entity; import android.annotation.SuppressLint; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; import java.util.ArrayList; import java.util.List; public class Mupi extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private String name; /** 是否有油漆 */ private Boolean you = false; private List<Bancai> bancais = new ArrayList<>(); @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public String getName() { return name; } public void setName(String name) { String oldValue = this.name; this.name = name; firePropertyChange(“name”, oldValue, name); } public Boolean getYou() { if (you == null) { you = false; return false; } return you; } public void setYou(Boolean you) { if (you == null) return; Boolean oldValue = this.you; this.you = you; firePropertyChange("you", oldValue, you); } public List<Bancai> getBancais() { return bancais; } public void setBancais(List<Bancai> bancais) { List<Bancai> oldValue = this.bancais; this.bancais = bancais; firePropertyChange(“bancais”, oldValue, bancais); } public Mupi() { } public Mupi(Integer id, String name, List<Bancai> bancais) { this.id = id; this.name = name; this.bancais = bancais; } public Mupi(List<Bancai> bancais, Boolean you, String name, Integer id) { this.bancais = bancais; this.you = you; this.name = name; this.id = id; } // 3. 木皮显示格式化方法 public String formatMupiDisplay() { return getName() + (getYou() ? "油" : ""); } } /* ========== User.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; /** 用户 */ public class User extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private String name; private String andy; private String pass; private Integer role; @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public String getName() { return name; } public void setName(String name) { String oldValue = this.name; this.name = name; firePropertyChange(“name”, oldValue, name); } public String getAndy() { return andy; } public void setAndy(String andy) { String oldValue = this.andy; this.andy = andy; firePropertyChange(“andy”, oldValue, andy); } public String getPass() { return pass; } public void setPass(String pass) { String oldValue = this.pass; this.pass = pass; firePropertyChange(“pass”, oldValue, pass); } public Integer getRole() { return role; } public void setRole(Integer role) { Integer oldValue = this.role; this.role = role; firePropertyChange(“role”, oldValue, role); } public User(int id, String name, String andy, String pass, int role) { this.id = id; this.name = name; this.andy = andy; this.pass = pass; this.role = role; } public User() { } @Override public String toString() { StringBuilder sb = new StringBuilder(“{”); // 处理属性名 sb.append("“id”: "); // 处理不同数据型 // 其他对象型 sb.append((id != null) ? id : “null”); sb.append(“,”); // 处理属性名 sb.append(""name": "); // 处理不同数据型 // 字符串型处理(含转义) sb.append(“"”) .append(name .replace(“\”, “\\”) .replace(“"”, “\"”) .replace(“\b”, “\b”) .replace(“\f”, “\f”) .replace(“\n”, “\n”) .replace(“\r”, “\r”) .replace(“\t”, “\t”)) .append(“"”); sb.append(“,”); // 处理属性名 sb.append(""andy": "); // 处理不同数据型 // 字符串型处理(含转义) sb.append(“"”) .append(andy .replace(“\”, “\\”) .replace(“"”, “\"”) .replace(“\b”, “\b”) .replace(“\f”, “\f”) .replace(“\n”, “\n”) .replace(“\r”, “\r”) .replace(“\t”, “\t”)) .append(“"”); sb.append(“,”); // 处理属性名 sb.append(""pass": "); // 处理不同数据型 // 字符串型处理(含转义) sb.append(“"”) .append(pass .replace(“\”, “\\”) .replace(“"”, “\"”) .replace(“\b”, “\b”) .replace(“\f”, “\f”) .replace(“\n”, “\n”) .replace(“\r”, “\r”) .replace(“\t”, “\t”)) .append(“"”); sb.append(“,”); // 处理属性名 sb.append(""role": "); // 处理不同数据型 // 其他对象型 sb.append((role != null) ? role : “null”); sb.append(“}”); return sb.toString(); } } /* ========== Zujian.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; /** 组件 */ public class Zujian extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private String name; public Zujian() { } public Zujian(Integer id, String name) { this.id = id; this.name = name; } @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public String getName() { return name; } public void setName(String name) { String oldValue = this.name; this.name = name; firePropertyChange(“name”, oldValue, name); } } /* ========== Bancai.java ========== */ package com.example.kucun2.entity; import android.annotation.SuppressLint; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; import java.util.Collections; import java.util.Map; import java.util.Objects; //板材 public class Bancai extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private Caizhi caizhi; private Mupi mupi1; private Mupi mupi2; private Double houdu; private Dingdan_chanpin_zujian Dingdan_chanpin_zujian; public Bancai() { } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Bancai bancai = (Bancai) o; return Objects.equals(id, bancai.id) && Objects.equals(caizhi, bancai.caizhi) && Objects.equals(mupi1, bancai.mupi1) && Objects.equals(mupi2, bancai.mupi2) && Objects.equals(houdu, bancai.houdu); } @Override public int hashCode() { return Objects.hash(id, caizhi, mupi1, mupi2, houdu); } public Bancai(Integer id, Caizhi caizhi, Mupi mupi1, Mupi mupi2, Double houdu) { this.id = id; this.caizhi = caizhi; this.mupi1 = mupi1; this.mupi2 = mupi2; this.houdu = houdu; } @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public Caizhi getCaizhi() { return caizhi; } public void setCaizhi(Caizhi caizhi) { Caizhi oldValue = this.caizhi; this.caizhi = caizhi; firePropertyChange(“caizhi”, oldValue, caizhi); } public Mupi getMupi1() { return mupi1; } public void setMupi1(Mupi mupi1) { Mupi oldValue = this.mupi1; this.mupi1 = mupi1; firePropertyChange(“mupi1”, oldValue, mupi1); } public Mupi getMupi2() { return mupi2; } public void setMupi2(Mupi mupi2) { Mupi oldValue = this.mupi2; this.mupi2 = mupi2; firePropertyChange(“mupi2”, oldValue, mupi2); } public Double getHoudu() { return houdu; } public void setHoudu(Double houdu) { Double oldValue = this.houdu; this.houdu = houdu; firePropertyChange(“houdu”, oldValue, houdu); } /** 表格中显示的文字 @return */ @SuppressLint(“DefaultLocale”) public String TableText() { String boardInfo = “”; boardInfo += String.format(“%.1f”, this.getHoudu()) + this.getCaizhi().getName() + “(”; if (mupi1 != null) { boardInfo += (this.getMupi1().getYou() ? this.getMupi1().getName() + “油” : this.getMupi1().getName()); } if (mupi2 != null && mupi1 != null) { boardInfo += “,”; } if (mupi2 != null) { boardInfo += (this.getMupi2().getYou() ? this.getMupi2().getName() + “油” : this.getMupi2().getName()); } boardInfo += “)”; return boardInfo; } public com.example.kucun2.entity.Dingdan_chanpin_zujian getDingdan_chanpin_zujian() { return Dingdan_chanpin_zujian; } public void setDingdan_chanpin_zujian(com.example.kucun2.entity.Dingdan_chanpin_zujian dingdan_chanpin_zujian) { com.example.kucun2.entity.Dingdan_chanpin_zujian oldValue = this.Dingdan_chanpin_zujian; Dingdan_chanpin_zujian = dingdan_chanpin_zujian; firePropertyChange(“dingdan_chanpin_zujian”, oldValue, dingdan_chanpin_zujian); } } /* ========== Caizhi.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; import java.util.ArrayList; import java.util.List; import java.util.Objects; //材质 public class Caizhi extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private String name; private List<Bancai> bancai = new ArrayList<>(); @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public String getName() { return name; } public void setName(String name) { String oldValue = this.name; this.name = name; firePropertyChange(“name”, oldValue, name); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Caizhi caizhi = (Caizhi) o; return Objects.equals(name, caizhi.name); } @Override public int hashCode() { return Objects.hashCode(name); } public List<Bancai> getBancai() { return bancai; } public void setBancai(List<Bancai> bancai) { List<Bancai> oldValue = this.bancai; this.bancai = bancai; firePropertyChange(“bancai”, oldValue, bancai); } } /* ========== Chanpin.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; import java.util.ArrayList; import java.util.List; //产品 public class Chanpin extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private String bianhao; private List<Chanpin_Zujian> chanpinZujian = new ArrayList<>(); private List<Dingdan_Chanpin> dingdanChanpin = new ArrayList<>(); ; @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public List<Chanpin_Zujian> getChanpinZujian() { return chanpinZujian; } public void setChanpinZujian(List<Chanpin_Zujian> chanpinZujian) { List<Chanpin_Zujian> oldValue = this.chanpinZujian; this.chanpinZujian = chanpinZujian; firePropertyChange(“chanpinZujian”, oldValue, chanpinZujian); } public List<Dingdan_Chanpin> getDingdanChanpin() { return dingdanChanpin; } public void setDingdanChanpin(List<Dingdan_Chanpin> dingdanChanpin) { List<Dingdan_Chanpin> oldValue = this.dingdanChanpin; this.dingdanChanpin = dingdanChanpin; firePropertyChange(“dingdanChanpin”, oldValue, dingdanChanpin); } public Chanpin() { } public String getBianhao() { return bianhao; } public void setBianhao(String bianhao) { String oldValue = this.bianhao; this.bianhao = bianhao; firePropertyChange(“bianhao”, oldValue, bianhao); } } /* ========== Chanpin_Zujian.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; //产品组件关联 public class Chanpin_Zujian extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private Chanpin chanpin; private Zujian zujian; private Double one_howmany; private Bancai bancai; public Chanpin_Zujian() { super(); } @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public Chanpin getChanpin() { return chanpin; } public void setChanpin(Chanpin chanpin) { Chanpin oldValue = this.chanpin; this.chanpin = chanpin; firePropertyChange(“chanpin”, oldValue, chanpin); } public Zujian getZujian() { return zujian; } public void setZujian(Zujian zujian) { Zujian oldValue = this.zujian; this.zujian = zujian; firePropertyChange(“zujian”, oldValue, zujian); } public Double getOne_howmany() { return one_howmany; } public void setOne_howmany(Double one_howmany) { Double oldValue = this.one_howmany; this.one_howmany = one_howmany; firePropertyChange(“one_howmany”, oldValue, one_howmany); } public Bancai getBancai() { return bancai; } public void setBancai(Bancai bancai) { Bancai oldValue = this.bancai; this.bancai = bancai; firePropertyChange(“bancai”, oldValue, bancai); } } /* ========== Dingdan.java ========== */ package com.example.kucun2.entity; import com.example.kucun2.entity.data.EntityClassGrassrootsid; import com.example.kucun2.entity.data.SynchronizableEntity; import java.util.ArrayList; import java.util.Date; import java.util.List; /** 订单 */ public class Dingdan extends SynchronizableEntity implements EntityClassGrassrootsid { private Integer id; private String number; private List<Dingdan_Chanpin> dingdanChanpin = new ArrayList<>(); ; private List<Dingdan_chanpin_zujian> dingdanChanpinZujian = new ArrayList<>(); ; private Date xiadan; private Date jiaohuo; public List<Dingdan_Chanpin> getDingdanChanpin() { return dingdanChanpin; } public void setDingdanChanpin(List<Dingdan_Chanpin> dingdanChanpin) { List<Dingdan_Chanpin> oldValue = this.dingdanChanpin; this.dingdanChanpin = dingdanChanpin; firePropertyChange(“dingdanChanpin”, oldValue, dingdanChanpin); } @Override public Integer getId() { return id; } public void setId(Integer id) { Integer oldValue = this.id; this.id = id; firePropertyChange(“id”, oldValue, id); } public String getNumber() { return number; } public void setNumber(String number) { String oldValue = this.number; this.number = number; firePropertyChange(“number”, oldValue, number); } public Date getXiadan() { return xiadan; } public void setXiadan(Date xiadan) { Date oldValue = this.xiadan; this.xiadan = xiadan; firePropertyChange(“xiadan”, oldValue, xiadan); } public Date getJiaohuo() { return jiaohuo; } public void setJiaohuo(Date jiaohuo) { Date oldValue = this.jiaohuo; this.jiaohuo = jiaohuo; firePropertyChange(“jiaohuo”, oldValue, jiaohuo); } public Dingdan() { } public List<Dingdan_chanpin_zujian> getDingdanChanpinZujian() { return dingdanChanpinZujian; } public void setDingdanChanpinZujian(List<Dingdan_chanpin_zujian> dingdanChanpinZujian) { List<Dingdan_chanpin_zujian> oldValue = this.dingdanChanpinZujian; this.dingdanChanpinZujian = dingdanChanpinZujian; firePropertyChange(“dingdanChanpinZujian”, oldValue, dingdanChanpinZujian); } } /* ========== EntityClassGrassrootsid.java ========== */ package com.example.kucun2.entity.data; public interface EntityClassGrassrootsid { Integer getId(); void setId(Integer id); String getEndpoint(String type); void sync(); } /* ========== ReflectionJsonUtils.java ========== */ package com.example.kucun2.entity.data; import android.util.Log; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public class ReflectionJsonUtils { /** 将任意Java对象转换为JSON字符串 @param obj 需要转换的对象 @return JSON格式字符串 */ public static String toJson(Object obj) { if (obj == null) { return “null”; } Class<?> clazz = obj.getClass(); // 处理基础型 if (isPrimitiveOrWrapper(clazz) || clazz == String.class) { return handlePrimitive(obj); } // 处理数组 if (clazz.isArray()) { return handleArray(obj); } // 处理集合 if (Collection.class.isAssignableFrom(clazz)) { return handleCollection((Collection<?>) obj); } // 处理Map if (Map.class.isAssignableFrom(clazz)) { return handleMap((Map<?, ?>) obj); } // 处理自定义对象 return handleObject(obj); } /** 处理基本数据型和字符串 */ private static String handlePrimitive(Object obj) { if (obj == null) return “null”; Class<?> clazz = obj.getClass(); if (clazz == String.class) { return “"” + escapeString((String) obj) + “"”; } if (clazz == Character.class || clazz == char.class) { return “"” + escapeChar((Character) obj) + “"”; } return obj.toString(); } /** 处理数组 */ private static String handleArray(Object array) { Class<?> componentType = array.getClass().getComponentType(); int length = java.lang.reflect.Array.getLength(array); StringBuilder sb = new StringBuilder(“[”); for (int i = 0; i < length; i++) { Object element = java.lang.reflect.Array.get(array, i); sb.append(toJson(element)); if (i < length - 1) { sb.append(","); } } sb.append(“]”); return sb.toString(); } /** 处理集合 */ private static String handleCollection(Collection<?> collection) { StringBuilder sb = new StringBuilder(“[”); int index = 0; int size = collection.size(); for (Object element : collection) { sb.append(toJson(element)); if (index < size - 1) { sb.append(“,”); } index++; } sb.append(“]”); return sb.toString(); } /** 处理Map */ private static String handleMap(Map<?, ?> map) { StringBuilder sb = new StringBuilder(“{”); int index = 0; int size = map.size(); for (Map.Entry<?, ?> entry : map.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); if (!(key instanceof String) && !isPrimitiveOrWrapper(key.getClass())) { throw new IllegalArgumentException("Map keys must be strings or primitives for JSON conversion"); } String keyStr = key instanceof String ? (String) key : key.toString(); sb.append("\"").append(escapeString(keyStr)).append("\":"); sb.append(toJson(value)); if (index < size - 1) { sb.append(","); } index++; } sb.append(“}”); return sb.toString(); } /** 处理自定义对象 */ private static String handleObject(Object obj) { Class<?> clazz = obj.getClass(); Field[] fields = getAllFields(clazz); StringBuilder sb = new StringBuilder(“{”); int index = 0; for (Field field : fields) { // 跳过静态字段 if (Modifier.isStatic(field.getModifiers())) { continue; } field.setAccessible(true); String fieldName = field.getName(); Object fieldValue = null; try { fieldValue = field.get(obj); } catch (IllegalAccessException e) { // 忽略访问异常,字段值保持null Log.e("ReflectionJsonUtils", "handleObject: " + e.getLocalizedMessage()); } sb.append("\"").append(escapeString(fieldName)).append("\":"); if (SynchronizableEntity.class.isAssignableFrom(field.getType()) && fieldValue != null && ((SynchronizableEntity) fieldValue).getId() != null) { try { Log.d("ReflectionJsonUtils", "isAssignableFrom: " + sb); sb.append("{\"id\":") .append(((SynchronizableEntity) fieldValue).getId()) .append("}"); } catch (Exception e) { sb.append(toJson(fieldValue)); } } else { sb.append(toJson(fieldValue)); } if (index < fields.length - 1) { sb.append(","); } index++; } sb.append(“}”); Log.d(“ReflectionJsonUtils”, "handleObject: " + sb); return sb.toString(); } // 获取及其父的所有字段 private static Field[] getAllFields(Class<?> type) { List<Field> fields = new ArrayList<>(); while (type != null && type != Object.class) { Field[] declaredFields = type.getDeclaredFields(); for (Field field : declaredFields) { // 跳过静态字段 if (!Modifier.isStatic(field.getModifiers())) { fields.add(field); } } type = type.getSuperclass(); } return fields.toArray(new Field[0]); } // 检查是否基本型或其包装 private static boolean isPrimitiveOrWrapper(Class<?> clazz) { return clazz.isPrimitive() || clazz == Boolean.class || clazz == Character.class || clazz == Byte.class || clazz == Short.class || clazz == Integer.class || clazz == Long.class || clazz == Float.class || clazz == Double.class || clazz == Void.class; } // 转义JSON字符串中的特殊字符 private static String escapeString(String str) { if (str == null) return “”; return str.replace(“\”, “\\”) .replace(“"”, “\"”) .replace(“/”, “\/”) .replace(“\b”, “\b”) .replace(“\f”, “\f”) .replace(“\n”, “\n”) .replace(“\r”, “\r”) .replace(“\t”, “\t”); } // 转义特殊字符 private static String escapeChar(Character ch) { if (ch == null) return “”; return escapeString(String.valueOf(ch)); } } /* ========== SynchronizableEntity.java ========== */ package com.example.kucun2.entity.data; import android.util.Log; import com.example.kucun2.entity.Information; import com.example.kucun2.function.MyAppFnction; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.HashMap; import java.util.Map; public abstract class SynchronizableEntity implements EntityClassGrassrootsid { public boolean isPreservedObject() { return this.getId() != null && this.getId() == -1; } public enum SyncState {NEW, MODIFIED, DELETED, PRESERVED} SyncState state = SyncState.NEW; private static boolean syncEnabled = true; public static void setSyncEnabled(boolean enabled) { syncEnabled = enabled; } // 设置状态的方法 public void setState(SyncState state) { this.state = state; } // 使用标准属性变更支持 private transient PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); // 属性缓存(可选,用于优化) private final Map<String, Object> propertyCache = new HashMap<>(); // 添加属性变更监听器 public void addPropertyChangeListener(PropertyChangeListener listener) { if (changeSupport == null) { changeSupport = new PropertyChangeSupport(this); } changeSupport.addPropertyChangeListener(listener); } // 移除属性变更监听器 public void removePropertyChangeListener(PropertyChangeListener listener) { if (changeSupport != null) { changeSupport.removePropertyChangeListener(listener); } } // 触发属性变更通知(子在setter中调用) protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { if (changeSupport != null && changeSupport.hasListeners(propertyName)) { // 更新属性缓存(可选) propertyCache.put(propertyName, newValue); // 触发变更事件 changeSupport.firePropertyChange(propertyName, oldValue, newValue); } } // 获取属性当前值(可选,用于setter中获取旧值) protected <T> T getCachedProperty(String propertyName) { return (T) propertyCache.get(propertyName); } // 初始化属性缓存(可选,在构造函数中调用) protected void initPropertyCache() { // 初始化所有字段到缓存 for (java.lang.reflect.Field field : getClass().getDeclaredFields()) { try { field.setAccessible(true); propertyCache.put(field.getName(), field.get(this)); } catch (Exception e) { // 忽略初始化异常 } } } /** 添加url @param type 操作增删改查 @return 返回相对url */ public String getEndpoint(String type) { //从String.xml获取url Log.d(“getEndpoint”, "getEndpoint: " + “url_” + type + “" + this.getClass().getSimpleName().toLowerCase()); return MyAppFnction.getStringResource(“string”, "url” + type + “_” + this.getClass().getSimpleName().toLowerCase()); } public void sync() { if (!syncEnabled) return; // 全局控制开关 if (this.state == null) return; try { switch (this.state) { case NEW: createToServer(); break; case MODIFIED: updateToServer(); break; case DELETED: deleteFromServer(); break; } } catch (Exception e) { Log.e("SyncError", "Sync failed for " + getClass().getSimpleName(), e); } } /** 创建实体到后端 */ private void createToServer() { String endpoint = MyAppFnction.getStringResource(“string”, “url”) + getEndpoint(“add”); Information<SynchronizableEntity> requestData = new Information<SynchronizableEntity>(); // 使用Volley、Retrofit或OkHttp执行POST请求 // 伪代码示例: ApiClient.post(endpoint, requestData, new ApiClient.ApiCallback<SynchronizableEntity>() { @Override public void onSuccess(Information<SynchronizableEntity> e) { // 解析服务器返回的ID Log.d(“onSuccess”, e.toJson()); if (e.getData() != null) { setId(e.getData().getId()); // 设置服务器返回的ID } state = SyncState.MODIFIED; state = SyncState.MODIFIED; } }); } /** 更新实体到后端 */ private void updateToServer() { String endpoint = MyAppFnction.getStringResource(“string”, “url”) + getEndpoint(“update”) + “/” + getId(); // 获取实体ID Information<SynchronizableEntity> requestData = new Information<SynchronizableEntity>(); ApiClient.post(endpoint, requestData, new ApiClient.ApiCallback<SynchronizableEntity>() { @Override public void onSuccess(Information<SynchronizableEntity> e) { // 解析服务器返回的ID Log.d(“onSuccess”, e.toJson()); // String serverId = parseServerId(response); // if (serverId != null) { // // 更新本地ID // setId(serverId); // 需要实体实现setId方法 // } // state = SyncState.MODIFIED; } }); } /** 从后端删除实体 */ private void deleteFromServer() { String endpoint = MyAppFnction.getStringResource(“string”, “url”) + getEndpoint(“delete”) + “/” + getId(); ApiClient.delete(endpoint, new ApiClient.ApiCallback<SynchronizableEntity>() { @Override public void onSuccess(Information<SynchronizableEntity> e) { Log.d(“SyncDelete”, "Successfully deleted " + getId()); } }); } /** 将实体转换为请求映射 */ protected Information<SynchronizableEntity> toRequestMap() { return Information.newSuccess(this); } } /* ========== SynchronizedList.java ========== */ package com.example.kucun2.entity.data; import android.annotation.SuppressLint; import android.util.Log; import com.google.gson.Gson; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** 支持数据变更自动同步的泛型集合 基于SynchronizableEntity的事件机制实现数据变更自动同步 @param <T> 必须是SynchronizableEntity或其子 */ public class SynchronizedList<T extends SynchronizableEntity> implements List<T> { // 使用ArrayList作为底层存储 private final List<T> list = new ArrayList<>(); public Class<T> getEntityType() { return entityType; } private Class<T> entityType; public SynchronizedList(Class<T> T) { this.entityType = T; } // 实体变更监听器 private final EntityChangeListener<T> entityChangeListener = new EntityChangeListener<>(); @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(Object o) { return list.contains(o); } @Override public Iterator<T> iterator() { return new SyncedIterator<>(list.iterator(), entityChangeListener); } @Override public Object[] toArray() { return list.toArray(); } @Override public <E> E[] toArray(E[] a) { return list.toArray(a); } // 添加元素时注册监听器 @SuppressLint(“SuspiciousIndentation”) @Override public boolean add(T element) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } return list.add(element); } // 移除元素时注销监听器 @Override public boolean remove(Object o) { if (o instanceof SynchronizableEntity) { ((SynchronizableEntity) o).removePropertyChangeListener(entityChangeListener); } return list.remove(o); } @Override public boolean containsAll(Collection<?> c) { return list.containsAll©; } // 批量添加时逐个注册监听器 @Override public boolean addAll(Collection<? extends T> c) { for (T element : c) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } } return list.addAll©; } @Override public boolean addAll(int index, Collection<? extends T> c) { for (T element : c) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } } return list.addAll(index, c); } // 批量移除时逐个注销监听器 @Override public boolean removeAll(Collection<?> c) { for (Object o : c) { if (o instanceof SynchronizableEntity) { ((SynchronizableEntity) o).removePropertyChangeListener(entityChangeListener); } } return list.removeAll©; } @Override public boolean retainAll(Collection<?> c) { // 先移除未保留元素的监听器 for (T element : list) { if (!c.contains(element)) { element.removePropertyChangeListener(entityChangeListener); } } return list.retainAll©; } // 清空集合时移除所有监听器 @Override public void clear() { for (T element : list) { element.removePropertyChangeListener(entityChangeListener); } list.clear(); } @Override public T get(int index) { return list.get(index); } // 替换元素时更新监听器 @Override public T set(int index, T element) { T oldElement = list.get(index); if (oldElement != null) { oldElement.removePropertyChangeListener(entityChangeListener); } if (element != null) { element.addPropertyChangeListener(entityChangeListener); } return list.set(index, element); } // 在指定位置添加元素时注册监听器 @Override public void add(int index, T element) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } list.add(index, element); } // 移除元素时注销监听器 @Override public T remove(int index) { T removed = list.remove(index); if (removed != null) { removed.removePropertyChangeListener(entityChangeListener); } return removed; } @Override public int indexOf(Object o) { return list.indexOf(o); } @Override public int lastIndexOf(Object o) { return list.lastIndexOf(o); } @Override public ListIterator<T> listIterator() { return new SyncedListIterator<>(list.listIterator(), entityChangeListener); } @Override public ListIterator<T> listIterator(int index) { return new SyncedListIterator<>(list.listIterator(index), entityChangeListener); } @Override public List<T> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } /** 内部实体变更监听器 监听属性变化并触发同步操作 / private static class EntityChangeListener<T extends SynchronizableEntity> implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { @SuppressWarnings(“unchecked”) T entity = (T) evt.getSource(); entity.sync(); // 触发同步操作 } } /* 增强的Iterator实现 移除元素时自动注销监听器 */ private static class SyncedIterator<T extends SynchronizableEntity> implements Iterator<T> { private final Iterator<T> iterator; private final EntityChangeListener<T> listener; private T current; public SyncedIterator(Iterator<T> iterator, EntityChangeListener<T> listener) { this.iterator = iterator; this.listener = listener; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { current = iterator.next(); return current; } @Override public void remove() { if (current != null) { current.removePropertyChangeListener(listener); } iterator.remove(); } } /** 增强的ListIterator实现 支持添加/设置元素时的监听器管理 */ private static class SyncedListIterator<T extends SynchronizableEntity> implements ListIterator<T> { private final ListIterator<T> iterator; private final EntityChangeListener<T> listener; private T lastReturned; public SyncedListIterator(ListIterator<T> iterator, EntityChangeListener<T> listener) { this.iterator = iterator; this.listener = listener; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { lastReturned = iterator.next(); return lastReturned; } @Override public boolean hasPrevious() { return iterator.hasPrevious(); } @Override public T previous() { lastReturned = iterator.previous(); return lastReturned; } @Override public int nextIndex() { return iterator.nextIndex(); } @Override public int previousIndex() { return iterator.previousIndex(); } @Override public void remove() { if (lastReturned != null) { lastReturned.removePropertyChangeListener(listener); } iterator.remove(); } @Override public void set(T e) { if (lastReturned != null) { lastReturned.removePropertyChangeListener(listener); } if (e != null) { e.addPropertyChangeListener(listener); } iterator.set(e); lastReturned = e; } @Override public void add(T e) { if (e != null) { e.addPropertyChangeListener(listener); } iterator.add(e); } } } /* ========== Data.java ========== */ package com.example.kucun2.entity.data; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.Log; import com.example.kucun2.entity.; import com.example.kucun2.function.MyAppFnction; import com.example.kucun2.function.SafeLogger; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.; import java.util.; import java.util.stream.Collectors; import okhttp3.; /** 核心数据管理 负责: 声明所有实体的静态存储列表 从服务器加载全量数据 管理实体间的关联关系 处理数据同步状态 */ public class Data { // ====================== 静态数据列表声明 ====================== public static SynchronizedList<Bancai> bancais = new SynchronizedList<>(Bancai.class); public static SynchronizedList<Caizhi> caizhis = new SynchronizedList<>(Caizhi.class); public static SynchronizedList<Mupi> mupis = new SynchronizedList<>(Mupi.class); public static SynchronizedList<Chanpin> chanpins = new SynchronizedList<>(Chanpin.class); public static SynchronizedList<Chanpin_Zujian> chanpin_zujians = new SynchronizedList<>(Chanpin_Zujian.class); public static SynchronizedList<Dingdan> dingdans = new SynchronizedList<>(Dingdan.class); public static SynchronizedList<Dingdan_Chanpin> dingdan_chanpins = new SynchronizedList<>(Dingdan_Chanpin.class); public static SynchronizedList<Dingdan_chanpin_zujian> Dingdan_chanpin_zujians = new SynchronizedList<>(Dingdan_chanpin_zujian.class); public static SynchronizedList<Kucun> kucuns = new SynchronizedList<>(Kucun.class); public static SynchronizedList<Zujian> zujians = new SynchronizedList<>(Zujian.class); public static SynchronizedList<User> users = new SynchronizedList<>(User.class); public static SynchronizedList<Jinhuo> jinhuos = new SynchronizedList<>(Jinhuo.class); private static User user; // 实体型与列表的映射表 <实体, 对应的同步列表> public static final Map<Class, SynchronizedList<SynchronizableEntity>> dataCollectionMap = new HashMap<>(); private static final Gson gson = GsonFactory.createWithIdSerialization(); private static OkHttpClient client; private static final String TAG = “DataLoader”; // 静态初始化:建立实体型与列表的映射关系 static { try { // 通过反射获取所有SynchronizedList字段 for (Field field : Data.class.getDeclaredFields()) { if (SynchronizedList.class.equals(field.getType())) { SynchronizedList<?> list = (SynchronizedList<?>) field.get(null); if (list != null) { // 将实体型与列表关联 dataCollectionMap.put(list.getEntityType(), (SynchronizedList<SynchronizableEntity>) list); } } } } catch (IllegalAccessException e) { throw new RuntimeException(“初始化dataCollectionMap失败”, e); } } // ====================== 核心数据加载方法 ====================== /** 从服务器加载全量数据 @param context Android上下文 @param callback 加载结果回调 */ public static void loadAllData(Context context, LoadDataCallback callback) { // 主线程检查 if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException(“必须在主线程调用Data.loadAllData”); } ensurePreservedObjects(); // 确保存在预置对象 // 使用传入的 Context 获取主线程 Handler Handler mainHandler = new Handler(context.getMainLooper()); // 确保使用安全的客户端 if (client == null) { client = MyAppFnction.getClient(); } SynchronizableEntity.setSyncEnabled(false); String url = MyAppFnction.getStringResource(“string”, “url”) + MyAppFnction.getStringResource(“string”, “url_all”); Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, “Failed to load data”, e); SynchronizableEntity.setSyncEnabled(true); mainHandler.post(() -> { if (callback != null) callback.onFailure(); }); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { Log.e(TAG, "Unexpected response code: " + response.code()); SynchronizableEntity.setSyncEnabled(true); mainHandler.post(() -> { if (callback != null) callback.onFailure(); }); return; } String responseData = response.body().string(); SynchronizableEntity.setSyncEnabled(true); ensurePreservedObjects(); // 在主线程处理解析 mainHandler.post(() -> { parseAndAssignData(responseData, context, callback); }); } }); } // ====================== 数据处理私有方法 ====================== /** 解析JSON数据并更新到实体列表 */ private static void parseAndAssignData(String jsonData, Context context, LoadDataCallback callback) { try { // 解析顶层响应结构 Type responseType = new TypeToken<Information<AllDataResponse>>() {}.getType(); Information<AllDataResponse> info = gson.fromJson(jsonData, responseType); // 验证响应有效性 if (info == null || info.getData() == null || info.getStatus() != 200) { throw new IllegalStateException(“无效服务器响应”); } AllDataResponse allData = info.getData(); SafeLogger.d(data”, "原始数据: " + gson.toJson(allData)); // 更新所有数据列表 updateAllLists(allData); automaticAssociation(); // 建立实体关联 setAllEntitiesState(SynchronizableEntity.SyncState.MODIFIED); // 设置状态 safeCallback(callback, true); // 成功回调 } catch (Exception e) { Log.e(TAG, "数据处理异常: " + e.getMessage()); safeCallback(callback, false); } finally { SynchronizableEntity.setSyncEnabled(true); // 重新启用同步 } } /** 批量更新所有实体列表 / private static void updateAllLists(AllDataResponse allData) { updateList(bancais, allData.bancais); updateList(caizhis, allData.caizhis); updateList(mupis, allData.mupis); updateList(chanpins, allData.chanpins); updateList(chanpin_zujians, allData.chanpin_zujians); updateList(dingdans, allData.dingdans); updateList(dingdan_chanpins, allData.dingdan_chanpins); updateList(Dingdan_chanpin_zujians, allData.Dingdan_chanpin_zujians); updateList(kucuns, allData.kucuns); updateList(zujians, allData.zujians); updateList(users, allData.users); updateList(jinhuos, allData.jinhuos); } /* 安全更新单个列表(保留预置对象) */ private static <T extends SynchronizableEntity> void updateList( List<T> existingList, List<T> newList ) { if (newList == null) return; // 保留现有列表中的预置对象 List<T> preservedItems = existingList.stream() .filter(item -> item != null && item.isPreservedObject()) .collect(Collectors.toList()); // 清空后重新添加(预置对象 + 有效新数据) existingList.clear(); existingList.addAll(preservedItems); existingList.addAll(newList.stream() .filter(item -> item != null && item.getId() != null && item.getId() != -1) .collect(Collectors.toList()) ); } /** 确保每个列表都有预置对象(用于表示空值/默认值) / private static void ensurePreservedObjects() { // 为每个实体型检查并添加预置对象 addIfMissing(bancais, Bancai.class); addIfMissing(caizhis, Caizhi.class); addIfMissing(mupis, Mupi.class); addIfMissing(chanpins, Chanpin.class); addIfMissing(chanpin_zujians, Chanpin_Zujian.class); addIfMissing(dingdans, Dingdan.class); addIfMissing(kucuns, Kucun.class); addIfMissing(zujians, Zujian.class); addIfMissing(Dingdan_chanpin_zujians, Dingdan_chanpin_zujian.class); addIfMissing(dingdan_chanpins, Dingdan_Chanpin.class); addIfMissing(jinhuos, Jinhuo.class); addIfMissing(users, User.class); } private static <T extends SynchronizableEntity> void addIfMissing( List<T> list, Class<T> clazz ) { if (!containsPreservedObject(list)) { list.add(createInstance(clazz)); } } /* 检查列表是否包含预置对象 @param list 目标实体列表 @return 是否包含预置对象 / private static <T extends SynchronizableEntity> boolean containsPreservedObject(List<T> list) { return list.stream().anyMatch(item -> item != null && item.isPreservedObject() ); } /* 自动建立实体间关联关系(通过反射实现) */ private static void automaticAssociation() { for (Class<?> entityClass : dataCollectionMap.keySet()) { try { associateEntities(dataCollectionMap.get(entityClass)); } catch (Exception e) { Log.e(TAG, entityClass.getSimpleName() + " 关联失败", e); } } } private static <T extends SynchronizableEntity> void associateEntities( SynchronizedList<T> list ) throws IllegalAccessException, ClassNotFoundException { for (T entity : list) { if (entity == null) continue; for (Field field : entity.getClass().getDeclaredFields()) { field.setAccessible(true); Class<?> fieldType = field.getType(); // 处理实体引用字段 if (SynchronizableEntity.class.isAssignableFrom(fieldType)) { associateSingleReference(entity, field); } // 处理实体列表字段 else if (List.class.isAssignableFrom(fieldType)) { associateReferenceList(entity, field); } // 处理基础型字段 else { setDefaultPrimitiveValue(entity, field); } } } } // ====================== 关联辅助方法 ====================== private static void associateSingleReference( SynchronizableEntity entity, Field field ) throws IllegalAccessException { SynchronizableEntity ref = (SynchronizableEntity) field.get(entity); Class<?> targetType = field.getType(); // 查找目标实体 SynchronizableEntity target = findTargetEntity(ref, targetType); field.set(entity, target); } private static void associateReferenceList( SynchronizableEntity entity, Field field ) throws IllegalAccessException, ClassNotFoundException { // 获取列表泛型型 Type genericType = field.getGenericType(); if (!(genericType instanceof ParameterizedType)) return; Class<?> itemType = Class.forName( ((ParameterizedType) genericType).getActualTypeArguments()[0].getTypeName() ); // 只处理实体列表 if (!SynchronizableEntity.class.isAssignableFrom(itemType)) return; List<SynchronizableEntity> refList = (List<SynchronizableEntity>) field.get(entity); if (refList == null) { refList = new ArrayList<>(); field.set(entity, refList); } // 清理空值并重建引用 refList.removeAll(Collections.singleton(null)); for (int i = 0; i < refList.size(); i++) { refList.set(i, findTargetEntity(refList.get(i), itemType)); } } /** 查找关联实体(优先匹配ID,找不到则使用预置对象) */ private static SynchronizableEntity findTargetEntity( SynchronizableEntity ref, Class<?> targetType ) { SynchronizedList<SynchronizableEntity> targetList = dataCollectionMap.get(targetType); if (targetList == null) return null; // 无效引用时返回预置对象 if (ref == null || ref.getId() == null || ref.getId() < 0) { return targetList.stream() .filter(SynchronizableEntity::isPreservedObject) .findFirst().orElse(null); } // 按ID查找目标实体 return targetList.stream() .filter(e -> ref.getId().equals(e.getId())) .findFirst() .orElseGet(() -> targetList.stream() // 找不到时回退到预置对象 .filter(SynchronizableEntity::isPreservedObject) .findFirst().orElse(null) ); } // ====================== 工具方法 ====================== /** 创建带默认值的实体实例(用作预置对象) */ public static <T> T createInstance(Class<T> clazz) { try { T instance = clazz.getDeclaredConstructor().newInstance(); // 设置基础字段默认值 for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); setDefaultFieldValue(instance, field); } // 设置特殊字段 clazz.getMethod(“setId”, Integer.class).invoke(instance, -1); clazz.getMethod(“setState”, SynchronizableEntity.SyncState.class) .invoke(instance, SynchronizableEntity.SyncState.PRESERVED); return instance; } catch (Exception e) { Log.e(Data”, "创建实例失败: " + clazz.getName(), e); try { return clazz.newInstance(); // 回退创建 } catch (Exception ex) { throw new RuntimeException(“无法创建实例”, ex); } } } private static <T> void setDefaultFieldValue(T instance, Field field) throws IllegalAccessException { Class<?> type = field.getType(); if (type == String.class) field.set(instance, “无”); else if (type == Integer.class || type == int.class) field.set(instance, -1); else if (type == Double.class || type == double.class) field.set(instance, -1.0); else if (type == Boolean.class || type == boolean.class) field.set(instance, false); else if (type == Date.class) field.set(instance, new Date()); else if (SynchronizableEntity.class.isAssignableFrom(type)) { field.set(instance, getPreservedEntity((Class<?>) type)); } else if (List.class.isAssignableFrom(type)) { field.set(instance, new ArrayList<>()); } } private static SynchronizableEntity getPreservedEntity(Class<?> type) { return dataCollectionMap.get(type).stream() .filter(SynchronizableEntity::isPreservedObject) .findFirst().orElse(null); } private static void setDefaultPrimitiveValue( SynchronizableEntity entity, Field field ) throws IllegalAccessException { if (field.get(entity) != null) return; Class<?> type = field.getType(); if (type == String.class) field.set(entity, “无”); else if (type == Integer.class || type == int.class) field.set(entity, -1); else if (type == Double.class || type == double.class) field.set(entity, -1.0); else if (type == Boolean.class || type == boolean.class) field.set(entity, false); else if (type == Date.class) field.set(entity, new Date()); } /** 主线程安全回调 / private static void safeCallback(LoadDataCallback callback, boolean success) { new Handler(Looper.getMainLooper()).post(() -> { if (callback == null) return; if (success) callback.onSuccess(); else callback.onFailure(); }); } /* 设置所有实体同步状态 */ private static void setAllEntitiesState(SynchronizableEntity.SyncState state) { dataCollectionMap.values().forEach(list -> list.forEach(entity -> { if (entity != null) entity.setState(state); }) ); } // ====================== 内部/接口 ====================== public interface LoadDataCallback { void onSuccess(); void onFailure(); } /** JSON响应数据结构 */ public static class AllDataResponse { public List<Bancai> bancais; public List<Caizhi> caizhis; public List<Mupi> mupis; public List<Chanpin> chanpins; public List<Chanpin_Zujian> chanpin_zujians; public List<Dingdan> dingdans; public List<Dingdan_Chanpin> dingdan_chanpins; public List<Dingdan_chanpin_zujian> Dingdan_chanpin_zujians; public List<Kucun> kucuns; public List<Zujian> zujians; public List<User> users; public List<Jinhuo> jinhuos; } } package com.example.kucun2.entity.data; import static android.content.ContentValues.TAG; import android.content.Context; import android.util.Log; import com.example.kucun2.R; import com.example.kucun2.entity.Information; import com.example.kucun2.function.MyAppFnction; import com.example.kucun2.function.TLSUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import java.util.Map; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.X509TrustManager; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; public class ApiClient { // 使用Volley、Retrofit或OkHttp实现以下方法 private static final Gson gson = new Gson(); private static OkHttpClient client; private static final String TAG = "DataLoader"; static { } public static <T, R> void post(String url, Information<T> requestData, ApiCallback<R> callback) { // 1. 构建请求体(JSON格式) String jsonRequest = gson.toJson(requestData); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonRequest); // 2. 创建POST请求 Request request = new Request.Builder() .url(url) .post(body) .build(); Log.d(TAG, "POST请求URL: " + url); Log.d(TAG, "请求数据: " + jsonRequest); // 3. 发送异步请求 client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "请求失败: " + e.getMessage()); if (callback != null) { //callback.onError(-1, e.getMessage()); } } @Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) { Log.e(TAG, "服务器响应错误: " + response.code() + " - " + response.message()); if (callback != null) { // callback.onError(response.code(), response.message()); } return; } // 4. 处理成功响应 String jsonResponse = responseBody.string(); Log.d(TAG, "服务器响应: " + jsonResponse); // 5. 解析为Information对象 // 注意:这里需要提前确定响应中data型(TypeToken) Type responseType = new TypeToken<Information<R>>() { }.getType(); Information<R> responseInfo = gson.fromJson(jsonResponse, responseType); if (callback != null) { callback.onSuccess(responseInfo); } } } }); } public static <T, R> void put(String url, Information<T> data, ApiCallback<T> callback) { // 实现PUT请求逻辑 } public static <R> void delete(String url, ApiCallback<R> callback) { // 实现DELETE请求逻辑 } public static interface ApiCallback<T> { void onSuccess(Information<T> data); // void onError(int statusCode, String error); } }<string name=“url”>https://192.168.31.177:3000</string> <string name=“url_all”>/app/all</string> <string name=“url_bancis”>/app/bancai/all</string> <string name=“url_caizhis”>/app/caizhi/all</string> <string name=“url_mupis”>/app/mupi/all</string> <string name=“url_dingdans”>/app/dingdan/all</string> <string name=“url_chanpins”>/app/chanpin/all</string> <string name=“url_zujians”>/app/zujian/all</string> <string name="url_chanpin_zujians">/app/chanpin_zujian/all</string> <string name="url_dingdan_zujians">/app/dingdan_zujian/all</string> <string name="url_dingdan_chanpins">/app/dingdan_chanpin/all</string> <string name="url_jinhuos">/app/jinhuo/all</string> <string name="url_add_bancai">/app/bancai/add</string> <string name="url_add_dingdan">/app/dingdan/add</string> <string name="url_add_chanpin">/app/chanpin/add</string> <string name="url_add_zujian">/app/zujian/add</string> <string name="url_add_caizhi">/app/caizhi/add</string> <string name="url_add_mupi">/app/mupi/add</string> <string name="url_add_dingdan_chanpin">/app/dingdan_chanpi/add</string> <string name="url_add_dingdan_zujian">/app/dingdan_zujian/add</string> <string name="url_add_chanpin_zujian">/app/chanpin_zujian/add</string> <string name="url_add_jinhuo">/app/jinhuo/add</string> <string name="url_login">/user/login</string>补全自动同步
06-15
package com.example.kucun2.entity.data; import static android.content.ContentValues.TAG; import android.content.Context; import android.util.Log; import com.example.kucun2.R; import com.example.kucun2.entity.Information; import com.example.kucun2.function.MyAppFnction; import com.example.kucun2.function.TLSUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import java.util.Map; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.X509TrustManager; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; public class ApiClient { // 使用Volley、Retrofit或OkHttp实现以下方法 private static final Gson gson = new Gson(); private static OkHttpClient client; private static final String TAG = "ApiClient"; static { } public static <T, R> void post(String url, Information<T> requestData, ApiCallback<R> callback) { // 1. 构建请求体(JSON格式) String jsonRequest = ReflectionJsonUtils.toJson(requestData); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonRequest); // 2. 创建POST请求 Request request = new Request.Builder() .url(url) .post(body) .build(); Log.d(TAG, "POST请求URL: " + url); Log.d(TAG, "请求数据: " + jsonRequest); // 3. 发送异步请求 client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "请求失败: " + e.getMessage()); if (callback != null) { callback.onError(-1, e.getMessage()); } } @Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) { Log.e(TAG, "服务器响应错误: " + response.code() + " - " + response.message()); if (callback != null) { callback.onError(response.code(), response.message()); } return; } // 4. 处理成功响应 String jsonResponse = responseBody.string(); Log.d(TAG, "服务器响应: " + jsonResponse); // 5. 解析为Information对象 // 注意:这里需要提前确定响应中data型(TypeToken) Type responseType = new TypeToken<Information<R>>() { }.getType(); Information<R> responseInfo = gson.fromJson(jsonResponse, responseType); if (callback != null) { callback.onSuccess(responseInfo); } } } }); } public static <T, R> void put(String url, Information<T> data, ApiCallback<T> callback) { String jsonRequest = ReflectionJsonUtils.toJson(data); RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonRequest); Request request = new Request.Builder() .url(url) .put(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "PUT request failed", e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful() && callback != null) { String json = response.body().string(); Type responseType = new TypeToken<Information<T>>(){}.getType(); Information<T> info = gson.fromJson(json, responseType); callback.onSuccess(info); } } }); } public static <R> void delete(String url, ApiCallback<R> callback) { Request request = new Request.Builder() .url(url) .delete() .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "DELETE request failed", e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful() && callback != null) { // 对于删除操作,通常返回空数据 callback.onSuccess(new Information<>(200, "Deleted", null)); } } }); } public static interface ApiCallback<T> { void onSuccess(Information<T> data); void onError(int statusCode, String error); } } E Sync failed for Chanpin_Zujian java.lang.NullPointerException: Attempt to invoke virtual method 'okhttp3.Call okhttp3.OkHttpClient.newCall(okhttp3.Request)' on a null object reference at com.example.kucun2.entity.data.ApiClient.post(ApiClient.java:58) at com.example.kucun2.entity.data.SynchronizableEntity.createToServer(SynchronizableEntity.java:133) at com.example.kucun2.entity.data.SynchronizableEntity.sync(SynchronizableEntity.java:110) at com.example.kucun2.entity.data.SynchronizableEntity.syncWithDependencies(SynchronizableEntity.java:302) at com.example.kucun2.entity.data.SynchronizedList.add(SynchronizedList.java:81)
最新发布
06-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值