Created
September 7, 2016 12:57
-
-
Save dnldsht/90db43756ab1d44b70c827999f3d4a7f to your computer and use it in GitHub Desktop.
Utils for HTTP request (also with queue when there is no connection)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AdvancedRequestHelper extends RequestsHelper { | |
private static AdvancedRequestHelper mInstance; | |
UnProcessedRequests unProcessedRequests; | |
private Context ctx; | |
public static synchronized AdvancedRequestHelper getInstance(Context context) { | |
if (mInstance == null) { | |
mInstance = new AdvancedRequestHelper(context); | |
} | |
return mInstance; | |
} | |
public AdvancedRequestHelper(Context context) { | |
super(context); | |
this.ctx = context; | |
unProcessedRequests = UnProcessedRequests.getInstance(context); | |
} | |
public boolean makeRequestWhenThereIsInternet(String url, int method, final HashMap<String, String> params, | |
Response.Listener<String> responseListener, final Response.ErrorListener errorListener) { | |
if(thereIsInternet()) { | |
makeAndSubmitRequest(url, method, params, responseListener, errorListener); | |
return true; | |
} | |
return addRequestToQueue(new MyRequest(url, method, params)); | |
} | |
public boolean addRequestToQueue(MyRequest request) { | |
return unProcessedRequests.addRequest(request); | |
} | |
public boolean removeUnprocessedRequest(MyRequest request) { | |
return unProcessedRequests.removeRequest(request); | |
} | |
public ArrayList<MyRequest> getUnprocessedRequests() { | |
return unProcessedRequests.getRequests(); | |
} | |
private boolean thereIsInternet() { | |
NetworkInfo activeNetworkInfo = ((ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); | |
return activeNetworkInfo != null && activeNetworkInfo.isAvailable(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyRequest { | |
private int id = -1; | |
private String url; | |
private HashMap<String, String> params; | |
private int method; | |
public MyRequest(String url, int method, HashMap<String,String> params) { | |
this.url = url; | |
this.params = params; | |
this.method = method; | |
} | |
public MyRequest(int id, String url, int method, String serializedParams) { | |
this.id = id; | |
this.url = url; | |
this.method = method; | |
this.params = deserializeParams(serializedParams); | |
} | |
public int getId() { | |
return id; | |
} | |
public int getMethod() { | |
return method; | |
} | |
public String getUrl() { | |
return url; | |
} | |
public HashMap<String, String> getParams() { | |
return params; | |
} | |
public String getSerializedParams() { | |
StringBuilder builder = new StringBuilder(); | |
for (String s : params.keySet()) | |
builder.append(s).append('§').append(params.get(s)).append('|'); | |
return builder.toString(); | |
} | |
private HashMap<String, String> deserializeParams(String s) { | |
HashMap<String, String> map = new HashMap<>(); | |
String[] split = s.split("\\|"); | |
for (String s1 : split) { | |
String[] split1 = s1.split("§"); | |
map.put(split1[0], split1[1]); | |
} | |
return map; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NetworkChangeReceiver extends BroadcastReceiver { | |
@Override public void onReceive(final Context context, final Intent intent) { | |
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo(); | |
if (activeNetworkInfo != null && activeNetworkInfo.isAvailable()) { | |
final AdvancedRequestHelper helper = AdvancedRequestHelper.getInstance(context); | |
ArrayList<MyRequest> unprocessedRequests = helper.getUnprocessedRequests(); | |
for (final MyRequest request : unprocessedRequests) { | |
helper.makeAndSubmitRequest(request.getUrl(), request.getMethod(), request.getParams(), new Response.Listener<String>() { | |
@Override | |
public void onResponse(String response) { | |
// NOTE: remove only if the request got a positive response | |
helper.removeUnprocessedRequest(request); | |
} | |
}, new Response.ErrorListener() { | |
@Override | |
public void onErrorResponse(VolleyError error) { | |
Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show(); | |
} | |
}); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RequestsHelper { | |
private RequestQueue mRequestQueue; | |
private ImageLoader mImageLoader; | |
private static RequestsHelper mInstance; | |
private static Context ctx; | |
public static synchronized RequestsHelper getInstance(Context context) { | |
if (mInstance == null) | |
mInstance = new RequestsHelper(context); | |
return mInstance; | |
} | |
public RequestsHelper(Context context) { | |
ctx = context; | |
mRequestQueue = getRequestQueue(); | |
mImageLoader = new ImageLoader(mRequestQueue, | |
new ImageLoader.ImageCache() { | |
private final LruCache<String, Bitmap> cache = new LruCache<>(20); | |
@Override public Bitmap getBitmap(String url) { | |
return cache.get(url); | |
} | |
@Override public void putBitmap(String url, Bitmap bitmap) { | |
cache.put(url, bitmap); | |
} | |
}); | |
} | |
public void makePostRequest(String baseUrl, String id, final Map<String, String> params, | |
Response.Listener<String> responseListener, Response.ErrorListener errorListener) { | |
String url = baseUrl + id; | |
makeAndSubmitRequest(url, Request.Method.POST, params, responseListener, errorListener); | |
} | |
public void makeGetRequest(String url, final Map<String, String> params, | |
Response.Listener<String> responseListener, Response.ErrorListener errorListener) { | |
makeAndSubmitRequest(url, Request.Method.GET, params, responseListener, errorListener); | |
} | |
public void makeAndSubmitRequest(String url, int method, final Map<String, String> params, | |
Response.Listener<String> responseListener, Response.ErrorListener errorListener) { | |
submitRequest(makeRequest(url, method, params, responseListener, errorListener)); | |
} | |
public StringRequest makeRequest(String url, int method, final Map<String, String> params, | |
Response.Listener<String> responseListener, Response.ErrorListener errorListener) { | |
StringRequest stringRequest = new StringRequest(method, url, responseListener, errorListener){ | |
@Override | |
protected Map<String, String> getParams(){ return params; } | |
}; | |
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); | |
return stringRequest; | |
} | |
public void submitRequest(StringRequest request) { | |
getRequestQueue().add(request); | |
} | |
public ImageLoader getImageLoader() { | |
return mImageLoader; | |
} | |
public RequestQueue getRequestQueue() { | |
if (mRequestQueue == null) { | |
Cache cache = new DiskBasedCache(ctx.getCacheDir(), 10 * 1024 * 1024); | |
Network network = new BasicNetwork(new HurlStack()); | |
mRequestQueue = new RequestQueue(cache, network); | |
// Don't forget to start the volley request queue | |
mRequestQueue.start(); | |
} | |
return mRequestQueue; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UnProcessedRequests extends SQLiteOpenHelper { | |
private static final int DATABASE_VERSION = 1; | |
private static final String DATABASE_NAME = "request_queue.db"; | |
private static final String TABLE_REQUESTS = "requests"; | |
private static final String REQUEST_ID = "id"; | |
private static final String REQUEST_URL = "url"; | |
private static final String REQUEST_METHOD = "method"; | |
private static final String REQUEST_PARAMS = "params"; | |
private static UnProcessedRequests instance; | |
public static UnProcessedRequests getInstance(Context context) { | |
if (instance == null) { | |
synchronized (UnProcessedRequests.class) { | |
if (instance == null) | |
instance = new UnProcessedRequests(context); | |
} | |
} | |
return instance; | |
} | |
private UnProcessedRequests(Context ctx) { | |
super(ctx, DATABASE_NAME, null, DATABASE_VERSION); | |
} | |
public void onCreate(SQLiteDatabase db) { | |
this.createAlbumsTable(db); | |
} | |
private void createAlbumsTable(SQLiteDatabase db) { | |
db.execSQL("CREATE TABLE " + | |
TABLE_REQUESTS + "(" + | |
REQUEST_ID + " INTEGER PRIMARY KEY," + | |
REQUEST_URL + " TEXT," + | |
REQUEST_METHOD + " INTEGER," + | |
REQUEST_PARAMS + " TEXT" +")"); | |
} | |
@Override | |
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { | |
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REQUESTS); | |
onCreate(db); | |
} | |
public boolean addRequest(MyRequest request) { | |
SQLiteDatabase db = getWritableDatabase(); | |
ContentValues values = new ContentValues(); | |
values.put(REQUEST_URL, request.getUrl()); | |
values.put(REQUEST_METHOD, request.getMethod()); | |
values.put(REQUEST_PARAMS, request.getSerializedParams()); | |
return db.insert(TABLE_REQUESTS, null, values) == 1; | |
} | |
public ArrayList<MyRequest> getRequests() { | |
ArrayList<MyRequest> requests = new ArrayList<>(); | |
SQLiteDatabase db = getReadableDatabase(); | |
String projection[] = new String[]{ | |
REQUEST_ID, REQUEST_URL, REQUEST_METHOD, REQUEST_PARAMS | |
}; | |
Cursor cur = db.query(TABLE_REQUESTS, projection, null, null, null, null, null); | |
if (cur.moveToFirst()) | |
do requests.add(new MyRequest(cur.getInt(0), cur.getString(1), cur.getInt(2), cur.getString(3))); | |
while (cur.moveToNext()); | |
cur.close(); | |
return requests; | |
} | |
public boolean removeRequest(MyRequest request) { | |
SQLiteDatabase db = getWritableDatabase(); | |
return db.delete(TABLE_REQUESTS, REQUEST_ID +"=?", | |
new String[]{ String.valueOf(request.getId()) }) == 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment