Here are the examples of the java api com.android.volley.RequestQueue taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
297 Examples
19
Source : VolleyHttpEngine.java
with Apache License 2.0
from youth5201314
with Apache License 2.0
from youth5201314
/**
* Volley简单实现,你可修改,这只是案例
*/
public clreplaced VolleyHttpEngine implements IHttpEngine {
private static RequestQueue mQueue = null;
public VolleyHttpEngine(Context context) {
mQueue = Volley.newRequestQueue(context);
}
@Override
public void get(String url, final Map<String, Object> params, final HttpCallBack callBack) {
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// 我这里使用的是fastjson,你也可以用gson,jackjson等
callBack.onSuccess(JSON.parseObject(response, XHttp.replacedysisClreplacedInfo(callBack)));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callBack.onFailed(error.toString());
}
}) {
// 传参
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> requestParams = new HashMap<>();
if (null != params) {
for (String key : params.keySet()) {
requestParams.put(key, (String) params.get(key));
}
}
return requestParams;
}
// 解决乱码
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String str = null;
try {
str = new String(response.data, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
}
};
mQueue.add(request);
}
@Override
public void post(String url, final Map<String, Object> params, final HttpCallBack callBack) {
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// 我这里使用的是fastjson,你也可以用gson,jackjson等
callBack.onSuccess(JSON.parseObject(response, XHttp.replacedysisClreplacedInfo(callBack)));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callBack.onFailed(error.toString());
}
}) {
// 传参
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> requestParams = new HashMap<>();
if (null != params) {
for (String key : params.keySet()) {
requestParams.put(key, (String) params.get(key));
}
}
return requestParams;
}
// 解决乱码
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String str = null;
try {
str = new String(response.data, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
}
};
mQueue.add(request);
}
}
19
Source : VolleyX.java
with Apache License 2.0
from yangweigbh
with Apache License 2.0
from yangweigbh
/**
* Set the volley request queue. If not set, the default request queue of volley is used.
* restore the default volley request queue by calling setRequestQueue(VolleyX.DEFAULT_REQUESTQUEUE)}
*
* @param queue
*/
public static void setRequestQueue(RequestQueue queue) {
if (!sInited)
throw new IllegalStateException("call init first");
if (queue != null)
sRequestQueue = queue;
}
19
Source : ApiBll.java
with Apache License 2.0
from wuxiaogu
with Apache License 2.0
from wuxiaogu
public clreplaced ApiBll {
private static ApiBll mApiBll;
private RequestQueue mQueue;
public static ApiBll getInstance() {
if (mApiBll == null) {
mApiBll = new ApiBll();
mApiBll.mQueue = Volley.newRequestQueue(AppContext.getInstance());
}
return mApiBll;
}
public RequestQueue getmQueue() {
return mApiBll.mQueue;
}
/**
* 检查是否需要发送新二维码
*/
public void checkQR() {
// if (!Configer.getInstance().getUrl().toLowerCase().startsWith("http")) {
// return;//防止首次启动还没有配置,就一直去轮循
// }
//
// mQueue.add(new FastJsonRequest(Configer.getInstance().getUrl()
// + Configer.getInstance().getPage() + "?command=ask", succ, null));
// mQueue.start();
}
/**
* 发送服务器所需要的二维码字符串给服务器
* 服务器如果有新订单,就会立马返回新的订单,手机端就不用再等下次轮循了
*
* @param qrBean 要发送的二维码参数
*/
public void sendQR(QrBean qrBean) throws UnsupportedEncodingException {
// StringBuilder stringBuilder = new StringBuilder(Configer.getInstance().getUrl())
// .append(Configer.getInstance().getPage())
// .append("?command=addqr")
// .append("&url=")
// .append(URLEncoder.encode(qrBean.getUrl(), "utf-8"))
// .append("&mark_sell=")
// .append(URLEncoder.encode(qrBean.getMark_sell(), "utf-8"));
// mQueue.add(new FastJsonRequest(stringBuilder.toString(), succ, null));
// mQueue.start();
// dealTaskList();
// LogUtils.show("发送二维码:" + stringBuilder.toString());
}
/**
* 向服务器发送支付成功的消息
* 如果因为一些原因,暂时没有通知成功,会保存任务,下次再尝试
*
* @param qrBean 订单详情信息
*/
public void payQR(final QrBean qrBean) {
// StringBuilder url = null;
// try {
// url = new StringBuilder(Configer.getInstance().getUrl())
// .append(Configer.getInstance().getPage())
// .append("?command=do")
// .append("&mark_sell=")
// .append(URLEncoder.encode(qrBean.getMark_sell(), "utf-8"))
// .append("&money=")
// .append(qrBean.getMoney())
// .append("&order_id=")
// .append(URLEncoder.encode(qrBean.getOrder_id(), "utf-8"))
// .append("&mark_buy=")
// .append(URLEncoder.encode(qrBean.getMark_buy(), "utf-8"));
// mQueue.add(new FastJsonRequest(url.toString(), null, new Response.ErrorListener() {
// @Override
// public void onErrorResponse(VolleyError error) {
// if (error == null || error.networkResponse == null || error.networkResponse.statusCode < 500) {
// //如果是服务器错误,自己检查代码,不然会一直发送成功订单造成多次支付!
// addTaskList(qrBean);
// }
// }
// }));
// mQueue.start();
// LogUtils.show("发送订单" + url.toString());
// } catch (Exception e) {
// addTaskList(qrBean);
// }
}
/**
* 处理以前没有完成的任务
*/
private void dealTaskList() {
SaveUtils saveUtils = new SaveUtils();
List<QrBean> list = saveUtils.getJsonArray(SaveUtils.TASK_LIST, QrBean.clreplaced);
if (list != null) {
// 先清空任务,如果呆会儿在payQR里又失败的话,会自动又添加的。
saveUtils.putJson(SaveUtils.TASK_LIST, null).commit();
for (QrBean qrBean : list) {
payQR(qrBean);
}
}
}
/**
* 添加未完成的任务列表
* 一定要用static的synchronized方式,上面的dealTaskList在某情况下可能会有问题
* 但个人方案就暂不考虑这么极端的情况了
*
* @param qrBean
*/
private synchronized static void addTaskList(QrBean qrBean) {
SaveUtils saveUtils = new SaveUtils();
List<QrBean> list = saveUtils.getJsonArray(SaveUtils.TASK_LIST, QrBean.clreplaced);
if (list == null) {
list = new ArrayList<>();
}
list.add(qrBean);
saveUtils.putJson(SaveUtils.TASK_LIST, list).commit();
}
/**
* 当询问是否需要生成二维码返回成功后的操作
*/
private final Response.Listener<BaseMsg> succ = new Response.Listener<BaseMsg>() {
@Override
public void onResponse(BaseMsg response) {
if (response == null) {
return;
}
QrBean qrBean = response.getData(QrBean.clreplaced);
if (qrBean != null && qrBean.getMoney() > 0 && !TextUtils.isEmpty(qrBean.getMark_sell())) {
LogUtils.show("服务器需要新二维码:" + qrBean.getMoney() + "|" + qrBean.getMark_sell() + "|" + qrBean.getChannel());
if (qrBean.getChannel().contentEquals(QrBean.WECHAT)) {
WechatHook.getInstance().creatQrTask(qrBean.getMoney(), qrBean.getMark_sell());
} else if (qrBean.getChannel().contentEquals(QrBean.ALIPAY)) {
AlipayHook.getInstance().creatQrTask(qrBean.getMoney(), qrBean.getMark_sell());
}
}
}
};
}
19
Source : VolleyQueueSingleton.java
with Apache License 2.0
from woshidasusu
with Apache License 2.0
from woshidasusu
clreplaced VolleyQueueSingleton {
/**
* Number of network request dispatcher threads to start.
*/
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 6;
private RequestQueue mRequestQueue;
private volatile static VolleyQueueSingleton sInstance;
private ExecutorService executorService = Executors.newCachedThreadPool();
public static VolleyQueueSingleton getInstance() {
if (sInstance == null) {
synchronized (VolleyQueueSingleton.clreplaced) {
if (sInstance == null) {
sInstance = new VolleyQueueSingleton();
}
}
}
return sInstance;
}
private VolleyQueueSingleton() {
// HttpsTrustManager.allowAllSSL();
HurlStack stack = new SelfSignSslHurlStack();
mRequestQueue = newAsyncRequestQueue(stack);
}
private RequestQueue newAsyncRequestQueue(HurlStack stack) {
BasicNetwork network = new BasicNetwork(stack);
// 修改Volley的请求队列,构键新的线程池
RequestQueue queue1 = new RequestQueue(new NoCache(), network, DEFAULT_NETWORK_THREAD_POOL_SIZE, new ExecutorDelivery(executorService));
queue1.start();
return queue1;
}
public void add(Request<?> request) {
mRequestQueue.add(request);
}
public void cancelAll(Object tag) {
mRequestQueue.cancelAll(tag);
}
}
19
Source : VolleySingleton.java
with Apache License 2.0
from webianks
with Apache License 2.0
from webianks
public clreplaced VolleySingleton {
public static VolleySingleton instance = null;
private RequestQueue requestQueue;
private VolleySingleton() {
requestQueue = Volley.newRequestQueue(CrimsonApplication.getContext(), new MyHurlStack());
}
public static VolleySingleton getInstance() {
if (instance == null) {
instance = new VolleySingleton();
}
return instance;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
}
19
Source : S.java
with Apache License 2.0
from UriahShaulMandel
with Apache License 2.0
from UriahShaulMandel
public static void sendVersionInfo(final Context context) {
if (!S.isEmulator() && !BuildConfig.DEBUG) {
final SharedPreferences sharedPreferences = BPrefs.get(context);
if (!sharedPreferences.contains(BPrefs.UUID_KEY)) {
sharedPreferences.edit().putString(BPrefs.UUID_KEY, UUID.randomUUID().toString()).apply();
}
final RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(new StringRequest(Request.Method.GET, "https://raw.githubusercontent.com/UriahShaulMandel/BaldPhone/master/logging%20mechanism/loga.txt", response -> {
requestQueue.add(new StringRequest(Request.Method.GET, String.format(Locale.US, "%s?uuid=%s&vcode=%d&locale=%s&flavor=%s", response, sharedPreferences.getString(BPrefs.UUID_KEY, null), BuildConfig.VERSION_CODE, String.valueOf(Locale.getDefault()), BuildConfig.FLAVOR), response2 -> {
}, error2 -> {
}).setTag("baldphone_server"));
}, error -> {
}).setTag("baldphone_get_server_info"));
}
}
19
Source : MyApp.java
with Apache License 2.0
from Temoa
with Apache License 2.0
from Temoa
/**
* Created by Temoa
* on 2016/10/12 14:24
*/
public clreplaced MyApp extends Application {
private static RequestQueue sRequestQueue;
private static TaskDBController.TasksManagerDBOpenHelper sTasksManagerDBOpenHelper;
@Override
public void onCreate() {
super.onCreate();
sRequestQueue = Volley.newRequestQueue(getApplicationContext());
WXHelper.initApi(this, Config.WX_APP_ID);
FileDownloader.init(getApplicationContext());
sTasksManagerDBOpenHelper = new TaskDBController.TasksManagerDBOpenHelper(getApplicationContext());
}
public static RequestQueue getRequestQueue() {
return sRequestQueue;
}
public static TaskDBController.TasksManagerDBOpenHelper getTasksManagerDBOpenHelper() {
return sTasksManagerDBOpenHelper;
}
}
19
Source : ModelImpl.java
with Apache License 2.0
from Temoa
with Apache License 2.0
from Temoa
/**
* Created by Temoa
* on 2016/10/17 16:53
*/
clreplaced ModelImpl implements IModel {
private RequestQueue mRequestQueue;
ModelImpl() {
mRequestQueue = MyApp.getRequestQueue();
}
@Override
public void getVideoInfo(int aid, final VideoCommonListener<VideoInfo> listener) {
mRequestQueue.add(RequestsHelper.getVideoInfo(aid, new Response.Listener<VideoInfo>() {
@Override
public void onResponse(VideoInfo response) {
if (response != null && response.getCid() != 0)
listener.onSucceed(response, 2);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
listener.onError(VolleyErrorHelper.getMessage(error));
}
}));
}
@Override
public void getVideoSrc(int cid, String type, final int flag, final VideoCommonListener<VideoSrc> listener) {
mRequestQueue.add(RequestsHelper.getVideoSrc(cid, type, new Response.Listener<VideoSrc>() {
@Override
public void onResponse(VideoSrc response) {
if (response != null && response.getDurl().size() != 0)
listener.onSucceed(response, flag);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
listener.onError(VolleyErrorHelper.getMessage(error));
}
}));
}
@Override
public void getVideoRecommend(int aid, final VideoCommonListener<VideoRecommend> listener) {
mRequestQueue.add(RequestsHelper.getVideoRecommend(aid, new Response.Listener<VideoRecommend>() {
@Override
public void onResponse(VideoRecommend response) {
if (response != null && response.getList().size() != 0)
listener.onSucceed(response, 2);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
listener.onError(VolleyErrorHelper.getMessage(error));
}
}));
}
}
19
Source : ModelImpl.java
with Apache License 2.0
from Temoa
with Apache License 2.0
from Temoa
/**
* Created by Temoa
* on 2016/10/12 14:56
*/
clreplaced ModelImpl implements IModel {
private RequestQueue mRequestQueue;
private ACache mCache;
ModelImpl(Context context) {
mRequestQueue = MyApp.getRequestQueue();
mCache = ACache.get(context);
}
/**
* 按照Flag 从缓存获取数据,网络获取数据
*
* @param flag FLAG_CACHE 从缓存获取
* FLAG_NEW_DATA 从网络获取
* @param listener 回调
*/
@Override
public void getAllData(int flag, final UpVideosListener listener) {
// 从缓存获取数据
if (flag == Presenter.FLAG_CACHE) {
List<UpVideos> cacheData = getDataFromCache();
if (cacheData != null) {
DataHelper.setBaseList(cacheData);
getPageData(listener, cacheData);
getSectionData(listener, cacheData);
return;
}
}
// 从网络获取数据
final List<UpVideos> baseList = new ArrayList<>();
Observable.just(Constants.MID_BOSS, Constants.MID_GIRL, Constants.MID_BOY).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Integer>() {
@Override
public void call(Integer mid) {
mRequestQueue.add(RequestsHelper.getUpVideos(mid, 1, new Response.Listener<UpVideos>() {
@Override
public void onResponse(UpVideos response) {
if (response == null || !response.isStatus()) {
listener.onError("出错了");
return;
}
baseList.add(response);
// 放进缓存
if (mCache != null) {
int key = response.getData().getVlist().get(0).getMid();
mCache.put(String.valueOf(key), response);
}
if (baseList.size() >= 3) {
DataHelper.setBaseList(baseList);
getPageData(listener, baseList);
getSectionData(listener, baseList);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
listener.onError(VolleyErrorHelper.getMessage(error));
}
}));
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
listener.onError("出错了");
}
});
}
private List<UpVideos> getDataFromCache() {
List<UpVideos> cacheData = new ArrayList<>();
if (mCache != null) {
UpVideos boss = (UpVideos) mCache.getAsObject(String.valueOf(Constants.MID_BOSS));
UpVideos boy = (UpVideos) mCache.getAsObject(String.valueOf(Constants.MID_BOY));
UpVideos girl = (UpVideos) mCache.getAsObject(String.valueOf(Constants.MID_GIRL));
if (boss != null && boy != null && girl != null) {
cacheData.add(boss);
cacheData.add(boy);
cacheData.add(girl);
}
return cacheData;
}
return null;
}
/**
* 获取滚动页面的数据
*/
@Override
public void getPageData(final UpVideosListener listener, List<UpVideos> origin) {
Observable.just(origin).map(new Func1<List<UpVideos>, List<VideoList>>() {
@Override
public List<VideoList> call(List<UpVideos> videos) {
return DataHelper.getRollPagerData(videos);
}
}).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<VideoList>>() {
@Override
public void call(List<VideoList> video) {
listener.onSucceed(video, Presenter.ROLL_PAGER_DATA);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
listener.onError("出错了");
}
});
}
/**
* 获取分栏的数据
*/
@Override
public void getSectionData(final UpVideosListener listener, List<UpVideos> origin) {
Observable.just(origin).map(new Func1<List<UpVideos>, List<VideoList>>() {
@Override
public List<VideoList> call(List<UpVideos> videos) {
return DataHelper.getSectionData(videos);
}
}).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<VideoList>>() {
@Override
public void call(List<VideoList> video) {
listener.onSucceed(video, Presenter.SECTION_DATA);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
listener.onError("出错了");
}
});
}
@Override
public void close() {
if (mCache != null)
mCache = null;
}
}
19
Source : ModelImpl.java
with Apache License 2.0
from Temoa
with Apache License 2.0
from Temoa
/**
* Created by Temoa
* on 2016/10/12 20:11
*/
clreplaced ModelImpl implements IModel {
static final int NEW_DATA = 0;
static final int ADD_DATA = 1;
private RequestQueue mRequestQueue;
ModelImpl() {
mRequestQueue = MyApp.getRequestQueue();
}
@Override
public void getData(final String videoCategory, final UpVideosWithPagesListener listener) {
Observable.create(new Observable.OnSubscribe<List<UpVideos>>() {
@Override
public void call(Subscriber<? super List<UpVideos>> subscriber) {
List<UpVideos> baseList = DataHelper.getBaseList();
subscriber.onNext(baseList);
subscriber.onCompleted();
}
}).map(new Func1<List<UpVideos>, List<VideoList>>() {
@Override
public List<VideoList> call(List<UpVideos> videos) {
return DataHelper.getDataByCategory(videos, videoCategory);
}
}).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<VideoList>>() {
@Override
public void call(List<VideoList> video) {
listener.onSucceed(video, NEW_DATA);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
listener.onError("出错了");
}
});
}
@Override
public void getMoreData(final String videoCategory, final int page, final UpVideosWithPagesListener listener) {
int mid;
switch(videoCategory) {
case Constants.REAL_PLAY:
mid = Constants.MID_BOSS;
break;
case Constants.LOL_TOP_10:
case Constants.PUPIL_PLAY:
case Constants.LYING_WIN:
mid = Constants.MID_GIRL;
break;
case Constants.OW_TOP_10:
mid = Constants.MID_BOY;
break;
default:
mid = 0;
}
if (mid == 0)
return;
mRequestQueue.add(RequestsHelper.getUpVideos(mid, page, new Response.Listener<UpVideos>() {
@Override
public void onResponse(UpVideos response) {
if (response == null || !response.isStatus()) {
listener.onError(null);
return;
}
Observable.just(response).map(new Func1<UpVideos, List<VideoList>>() {
@Override
public List<VideoList> call(UpVideos videos) {
listener.getPages(videos.getData().getPages());
List<UpVideos> videosList = new ArrayList<>();
videosList.add(videos);
return DataHelper.getDataByCategory(videosList, videoCategory);
}
}).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<VideoList>>() {
@Override
public void call(List<VideoList> video) {
listener.onSucceed(video, ADD_DATA);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
listener.onError("出错了");
}
});
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
listener.onError(VolleyErrorHelper.getMessage(error));
}
}));
}
}
19
Source : NetworkService.java
with GNU General Public License v3.0
from socoolby
with GNU General Public License v3.0
from socoolby
public final clreplaced NetworkService {
private static NetworkService mInstance;
private RequestQueue mRequestQueue;
private DefaultRetryPolicy mRetryPolicy;
private NetworkService() {
mRequestQueue = getRequestQueue();
}
private final static String TAG = "NetworkService";
public static synchronized NetworkService getInstance() {
if (mInstance == null) {
mInstance = new NetworkService();
}
return mInstance;
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(ClockApplication.getContext());
}
return mRequestQueue;
}
private void setRequestTimeout(int ms) {
int timeout = (ms == 0) ? DefaultRetryPolicy.DEFAULT_TIMEOUT_MS : ms;
mRetryPolicy = new DefaultRetryPolicy(timeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
}
public boolean sendRequest(RequestBase request, final RequestListener listener) {
String url = request.getUrl();
JSONObject requestObject = request.createRequest();
if (url == null || url.length() == 0 || requestObject == null) {
return false;
}
Log.d(TAG, String.format("request URL:%s \nrequest Params:%s", request.getUrl(), requestObject.toString()));
JsonObjectRequest jsonRequest = new JsonObjectRequest(url, requestObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "http response JsonString:" + response.toString());
listener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "http request fail");
listener.onRequestFailed(Constants.FAIL_CODE, error.toString());
}
}) {
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
};
setRequestTimeout(30000);
jsonRequest.setRetryPolicy(mRetryPolicy);
mRequestQueue.add(jsonRequest);
return true;
}
public interface RequestListener {
void onResponse(JSONObject response);
void onRequestFailed(int error, String errorMessage);
}
}
19
Source : Register.java
with MIT License
from singhkshitij
with MIT License
from singhkshitij
public clreplaced Register extends AppCompatActivity {
private EditText edtname, edtemail, edtpreplaced, edtcnfpreplaced, edtnumber;
private String check, name, email, preplacedword, mobile, profile;
CircleImageView image;
ImageView upload;
RequestQueue requestQueue;
boolean IMAGE_STATUS = false;
Bitmap profilePicture;
public static final String TAG = "MyTag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// check Internet Connection
new CheckInternetConnection(this).checkConnection();
Typeface typeface = ResourcesCompat.getFont(this, R.font.blacklist);
TextView appname = findViewById(R.id.appname);
appname.setTypeface(typeface);
upload = findViewById(R.id.uploadpic);
image = findViewById(R.id.profilepic);
edtname = findViewById(R.id.name);
edtemail = findViewById(R.id.email);
edtpreplaced = findViewById(R.id.preplacedword);
edtcnfpreplaced = findViewById(R.id.confirmpreplacedword);
edtnumber = findViewById(R.id.number);
edtname.addTextChangedListener(nameWatcher);
edtemail.addTextChangedListener(emailWatcher);
edtpreplaced.addTextChangedListener(preplacedWatcher);
edtcnfpreplaced.addTextChangedListener(cnfpreplacedWatcher);
edtnumber.addTextChangedListener(numberWatcher);
requestQueue = Volley.newRequestQueue(Register.this);
// validate user details and register user
Button button = findViewById(R.id.register);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO AFTER VALDATION
if (validateProfile() && validateName() && validateEmail() && validatePreplaced() && validateCnfPreplaced() && validateNumber()) {
name = edtname.getText().toString();
email = edtemail.getText().toString();
preplacedword = edtcnfpreplaced.getText().toString();
mobile = edtnumber.getText().toString();
final KProgressHUD progressDialog = KProgressHUD.create(Register.this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE).setLabel("Please wait").setCancellable(false).setAnimationSpeed(2).setDimAmount(0.5f).show();
// Validation Success
convertBitmapToString(profilePicture);
RegisterRequest registerRequest = new RegisterRequest(name, preplacedword, mobile, email, profile, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.e("Rsponse from server", response);
try {
if (new JSONObject(response).getBoolean("success")) {
Toasty.success(Register.this, "Registered Succesfully", Toast.LENGTH_SHORT, true).show();
sendRegistrationEmail(name, email);
} else
Toasty.error(Register.this, "User Already Exist", Toast.LENGTH_SHORT, true).show();
} catch (JSONException e) {
e.printStackTrace();
Toasty.error(Register.this, "Failed to Register", Toast.LENGTH_LONG, true).show();
}
}
});
requestQueue.add(registerRequest);
}
}
});
// Take already registered user to login page
final TextView loginuser = findViewById(R.id.login_now);
loginuser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(Register.this, LoginActivity.clreplaced));
finish();
}
});
// take user to reset preplacedword
final TextView forgotpreplaced = findViewById(R.id.forgot_preplaced);
forgotpreplaced.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(Register.this, ForgotPreplacedword.clreplaced));
finish();
}
});
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
Dexter.withActivity(Register.this).withPermissions(android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE).withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
// do you work now
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1000);
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// permission is denied permenantly, navigate user to app settings
Snackbar.make(view, "Kindly grant Required Permission", Snackbar.LENGTH_LONG).setAction("Allow", null).show();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).onSameThread().check();
// result will be available in onActivityResult which is overridden
}
});
}
private void sendRegistrationEmail(final String name, final String emails) {
BackgroundMail.newBuilder(Register.this).withSendingMessage("Sending Welcome Greetings to Your Email !").withSendingMessageSuccess("Kindly Check Your Email now !").withSendingMessageError("Failed to send preplacedword ! Try Again !").withUsername("[email protected]").withPreplacedword("Singh@30").withMailto(emails).withType(BackgroundMail.TYPE_PLAIN).withSubject("Greetings from Magic Print").withBody("Hello Mr/Miss, " + name + "\n " + getString(R.string.registermail1)).send();
}
private void convertBitmapToString(Bitmap profilePicture) {
/*
Base64 encoding requires a byte array, the bitmap image cannot be converted directly into a byte array.
so first convert the bitmap image into a ByteArrayOutputStream and then convert this stream into a byte array.
*/
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
profilePicture.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
byte[] array = byteArrayOutputStream.toByteArray();
profile = Base64.encodeToString(array, Base64.DEFAULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000 && resultCode == Activity.RESULT_OK && data != null) {
// Image Successfully Selected
try {
// parsing the Intent data and displaying it in the imageview
// Geting uri of the data
Uri imageUri = data.getData();
// creating an imputstrea
InputStream imageStream = getContentResolver().openInputStream(imageUri);
// decoding the input stream to bitmap
profilePicture = BitmapFactory.decodeStream(imageStream);
image.setImageBitmap(profilePicture);
// setting the flag
IMAGE_STATUS = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private boolean validateProfile() {
if (!IMAGE_STATUS)
Toasty.info(Register.this, "Select A Profile Picture", Toast.LENGTH_LONG).show();
return IMAGE_STATUS;
}
private boolean validateNumber() {
check = edtnumber.getText().toString();
Log.e("inside number", check.length() + " ");
if (check.length() > 10) {
return false;
} else if (check.length() < 10) {
return false;
}
return true;
}
private boolean validateCnfPreplaced() {
check = edtcnfpreplaced.getText().toString();
return check.equals(edtpreplaced.getText().toString());
}
private boolean validatePreplaced() {
check = edtpreplaced.getText().toString();
if (check.length() < 4 || check.length() > 20) {
return false;
} else if (!check.matches("^[A-za-z0-9@]+")) {
return false;
}
return true;
}
private boolean validateEmail() {
check = edtemail.getText().toString();
if (check.length() < 4 || check.length() > 40) {
return false;
} else if (!check.matches("^[A-za-z0-9.@]+")) {
return false;
} else if (!check.contains("@") || !check.contains(".")) {
return false;
}
return true;
}
private boolean validateName() {
check = edtname.getText().toString();
return !(check.length() < 4 || check.length() > 20);
}
// Texreplacedcher for Name -----------------------------------------------------
Texreplacedcher nameWatcher = new Texreplacedcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// none
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// none
}
@Override
public void afterTextChanged(Editable s) {
check = s.toString();
if (check.length() < 4 || check.length() > 20) {
edtname.setError("Name Must consist of 4 to 20 characters");
}
}
};
// Texreplacedcher for Email -----------------------------------------------------
Texreplacedcher emailWatcher = new Texreplacedcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// none
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// none
}
@Override
public void afterTextChanged(Editable s) {
check = s.toString();
if (check.length() < 4 || check.length() > 40) {
edtemail.setError("Email Must consist of 4 to 20 characters");
} else if (!check.matches("^[A-za-z0-9.@]+")) {
edtemail.setError("Only . and @ characters allowed");
} else if (!check.contains("@") || !check.contains(".")) {
edtemail.setError("Enter Valid Email");
}
}
};
// Texreplacedcher for preplaced -----------------------------------------------------
Texreplacedcher preplacedWatcher = new Texreplacedcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// none
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// none
}
@Override
public void afterTextChanged(Editable s) {
check = s.toString();
if (check.length() < 4 || check.length() > 20) {
edtpreplaced.setError("Preplacedword Must consist of 4 to 20 characters");
} else if (!check.matches("^[A-za-z0-9@]+")) {
edtemail.setError("Only @ special character allowed");
}
}
};
// Texreplacedcher for repeat Preplacedword -----------------------------------------------------
Texreplacedcher cnfpreplacedWatcher = new Texreplacedcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// none
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// none
}
@Override
public void afterTextChanged(Editable s) {
check = s.toString();
if (!check.equals(edtpreplaced.getText().toString())) {
edtcnfpreplaced.setError("Both the preplacedwords do not match");
}
}
};
// Texreplacedcher for Mobile -----------------------------------------------------
Texreplacedcher numberWatcher = new Texreplacedcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// none
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// none
}
@Override
public void afterTextChanged(Editable s) {
check = s.toString();
if (check.length() > 10) {
edtnumber.setError("Number cannot be grated than 10 digits");
} else if (check.length() < 10) {
edtnumber.setError("Number should be 10 digits");
}
}
};
@Override
protected void onResume() {
super.onResume();
// check Internet Connection
new CheckInternetConnection(this).checkConnection();
}
@Override
protected void onStop() {
super.onStop();
}
}
19
Source : PoolActivity.java
with GNU General Public License v3.0
from scala-network
with GNU General Public License v3.0
from scala-network
public clreplaced PoolActivity extends BaseActivity implements PoolInfoAdapter.OnSelectPoolListener, PoolInfoAdapter.OnMenuPoolListener, View.OnClickListener {
private static final String LOG_TAG = "PoolActivity";
private SwipeRefreshLayout pullToRefresh;
private RecyclerView rvPools;
private final Set<PoolItem> allPools = new HashSet<>();
private PoolInfoAdapter poolsAdapter;
private PoolItem selectedPool = null;
private RequestQueue mPoolQueue = null;
public final static String RequesterType = "Requester";
public final static int REQUESTER_NONE = 1;
public final static int REQUESTER_WIZARD = 0;
public final static int REQUESTER_SETTINGS = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
// Activity was brought to front and not created,
// Thus finishing this will get us to the last viewed activity
finish();
return;
}
setContentView(R.layout.fragment_pool);
// If activity is created from Home Wizard
Intent intent = getIntent();
int requesterType = intent.getIntExtra(PoolActivity.RequesterType, PoolActivity.REQUESTER_NONE);
LinearLayout llPoolsParent = findViewById(R.id.llPoolsParent);
int marginBottom = requesterType == PoolActivity.REQUESTER_WIZARD ? Utils.getDimPixels(llPoolsParent, 90) : Utils.getDimPixels(llPoolsParent, 15);
int marginDefault = Utils.getDimPixels(llPoolsParent, 15);
// Must use parent layout for some reason
((RelativeLayout.LayoutParams) llPoolsParent.getLayoutParams()).setMargins(marginDefault, marginDefault, marginDefault, marginBottom);
RelativeLayout rlSaveSettings = findViewById(R.id.rlSaveSettings);
rlSaveSettings.setVisibility(requesterType == PoolActivity.REQUESTER_WIZARD ? View.VISIBLE : View.GONE);
// Toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowreplacedleEnabled(false);
toolbar.setOnButtonListener(new Toolbar.OnButtonListener() {
@Override
public void onButtonMain(int type) {
if (type == Toolbar.BUTTON_MAIN_CLOSE) {
onBackPressed();
}
}
@Override
public void onButtonOptions(int type) {
// Does nothing in pool view
}
});
toolbar.setreplacedle("Mining Pool");
toolbar.setButtonMain(Toolbar.BUTTON_MAIN_CLOSE);
toolbar.setButtonOptions(Toolbar.BUTTON_OPTIONS_NONE);
mPoolQueue = Volley.newRequestQueue(this);
View view = findViewById(android.R.id.content).getRootView();
View fabAddPool = view.findViewById(R.id.fabAddPool);
fabAddPool.setOnClickListener(this);
fabAddPool.setVisibility(requesterType == PoolActivity.REQUESTER_WIZARD ? View.GONE : View.VISIBLE);
rvPools = view.findViewById(R.id.rvPools);
poolsAdapter = new PoolInfoAdapter(this, this, this);
rvPools.setAdapter(poolsAdapter);
pullToRefresh = view.findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refresh();
}
});
Utils.hideKeyboard(this);
refresh();
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.fabAddPool) {
newPool = true;
EditDialog diag = createEditDialog(null);
if (diag != null) {
diag.show();
}
}
}
@Override
public void onBackPressed() {
SettingsFragment.selectedPoolTmp = selectedPool;
ProviderManager.saveUserDefinedPools(getApplicationContext());
super.onBackPressed();
}
private void updateSelectedPoolLayout() {
// If recycler view has not been rendered yet
if (Objects.requireNonNull(rvPools.getLayoutManager()).gereplacedemCount() <= 0)
return;
String selectedPoolName = SettingsFragment.selectedPoolTmp == null ? Config.read(Config.CONFIG_SELECTED_POOL) : SettingsFragment.selectedPoolTmp.getKey();
PoolItem[] allPools = ProviderManager.getAllPools();
if (selectedPoolName.isEmpty()) {
selectedPoolName = allPools[0].getKey();
}
if (!selectedPoolName.isEmpty()) {
for (PoolItem poolItem : allPools) {
if (selectedPoolName.equals(poolItem.getKey())) {
// selectedPoolView = rvPools.getChildAt(i);
selectedPool = poolItem;
}
}
}
}
private AsyncLoadPools asyncLoadPools = null;
private void refresh() {
// ignore refresh request as one is ongoing
if (asyncLoadPools != null)
return;
asyncLoadPools = new AsyncLoadPools();
asyncLoadPools.execute();
}
@Override
public void onSelectPool(final PoolItem poolItem) {
selectedPool.setIsSelected(false);
poolItem.setIsSelected(true);
selectedPool = poolItem;
SettingsFragment.selectedPoolTmp = null;
newPool = false;
poolsAdapter.dataSetChanged();
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onContextInteraction(MenuItem item, PoolItem poolItem) {
switch(item.gereplacedemId()) {
case R.id.action_edit_pool:
EditDialog diag = createEditDialog(poolItem);
if (diag != null) {
diag.show();
}
break;
case R.id.action_delete_pool:
onDeletePool(poolItem);
break;
default:
return super.onContexreplacedemSelected(item);
}
return true;
}
public void onDeletePool(final PoolItem poolItem) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int action) {
switch(action) {
case DialogInterface.BUTTON_POSITIVE:
if (poolItem.isUserDefined()) {
poolsAdapter.deletePool(poolItem);
ProviderManager.delete(poolItem);
ProviderManager.saveUserDefinedPools(getApplicationContext());
refresh();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
// do nothing
break;
}
}
};
if (!poolItem.isUserDefined()) {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogCustom);
builder.setMessage("Default pools cannot be deleted.").setreplacedle(poolItem.getKey()).setPositiveButton(getString(R.string.ok), dialogClickListener).show();
} else {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogCustom);
builder.setMessage("Do you really want to delete this pool?").setreplacedle(poolItem.getKey()).setPositiveButton(getString(R.string.yes), dialogClickListener).setNegativeButton(getString(R.string.no), dialogClickListener).show();
}
}
private PoolItem poolEdit = null;
private PoolItem poolEditBackup = null;
private boolean newPool = false;
// for preventing opening of multiple dialogs
private EditDialog editDialog = null;
private EditDialog createEditDialog(final PoolItem poolItem) {
if (editDialog != null) {
editDialog.closeDialog();
editDialog = null;
}
editDialog = new EditDialog(this, poolItem);
return editDialog;
}
clreplaced EditDialog {
private boolean applyChanges() {
final String poolName = Objects.requireNonNull(etPoolName.getEditText()).getText().toString().trim();
if (poolName.isEmpty()) {
etPoolName.setError(getString(R.string.value_empty));
return false;
} else {
poolEdit.setKey(poolName);
}
final String poolUrl = Objects.requireNonNull(etPoolURL.getEditText()).getText().toString().trim();
if (poolUrl.isEmpty()) {
etPoolURL.setError(getString(R.string.value_empty));
return false;
} else {
poolEdit.setPoolUrl(poolUrl);
poolEdit.setPool(poolUrl);
}
if (poolEdit.isUserDefined()) {
String port = Objects.requireNonNull(etPoolPort.getEditText()).getText().toString().trim();
if (port.isEmpty()) {
etPoolPort.setError(getString(R.string.value_empty));
return false;
} else {
poolEdit.setSelectedPort(port);
}
} else {
poolEdit.setSelectedPort(spPoolPort.getSelectedItem().toString().trim());
}
return true;
}
private void applyChangesTmp() {
final String poolName = Objects.requireNonNull(etPoolName.getEditText()).getText().toString().trim();
poolEdit.setKey(poolName);
final String poolURL = Objects.requireNonNull(etPoolURL.getEditText()).getText().toString().trim();
poolEdit.setPoolUrl(poolURL);
if (poolEdit.isUserDefined()) {
final String poolPort = Objects.requireNonNull(etPoolPort.getEditText()).getText().toString().trim();
poolEdit.setSelectedPort(poolPort);
} else {
poolEdit.setSelectedPort(spPoolPort.getSelectedItem().toString().trim());
}
}
private void apply() {
poolEditBackup = null;
if (applyChanges()) {
closeDialog();
if (newPool) {
poolsAdapter.addPool(poolEdit);
ProviderManager.add(poolEdit);
ProviderManager.saveUserDefinedPools(getApplicationContext());
}
poolsAdapter.dataSetChanged();
}
}
private void closeDialog() {
if (editDialog == null)
return;
Utils.hideKeyboard(getParent());
editDialog.dismiss();
editDialog = null;
}
private void undoChanges() {
if (poolEditBackup != null) {
poolEdit.overwriteWith(poolEditBackup);
poolEditBackup = null;
}
}
private void show() {
editDialog.show();
}
androidx.appcompat.app.AlertDialog editDialog;
final TextInputLayout etPoolName;
final TextInputLayout etPoolURL;
final Spinner spPoolPort;
final TextInputLayout etPoolPort;
final ImageView ivPoolIcon;
public static final int GET_FROM_GALLERY = 1;
EditDialog(Activity activity, final PoolItem poolItem) {
MaterialAlertDialogBuilder alertDialogBuilder = new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogCustom);
LayoutInflater li = LayoutInflater.from(alertDialogBuilder.getContext());
View promptsView = li.inflate(R.layout.prompt_editpool, null);
alertDialogBuilder.setView(promptsView);
etPoolName = promptsView.findViewById(R.id.etPoolName);
etPoolURL = promptsView.findViewById(R.id.etPoolURL);
spPoolPort = promptsView.findViewById(R.id.spinnerPort);
ImageView imgSpinnerDown = promptsView.findViewById(R.id.imgSpinnerDown);
imgSpinnerDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
spPoolPort.performClick();
}
});
etPoolPort = promptsView.findViewById(R.id.etPoolPort);
ivPoolIcon = promptsView.findViewById(R.id.ivPoolIcon);
Button btnSelectImage = promptsView.findViewById(R.id.btnSelectImage);
btnSelectImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
applyChangesTmp();
pickImage();
}
});
if (poolItem != null) {
poolEdit = poolItem;
if (poolEditBackup == null)
poolEditBackup = new PoolItem(poolItem);
Objects.requireNonNull(etPoolName.getEditText()).setText(poolItem.getKey());
Objects.requireNonNull(etPoolURL.getEditText()).setText(poolItem.getPoolUrl());
Bitmap icon = poolItem.getIcon();
if (icon != null)
ivPoolIcon.setImageBitmap(poolItem.getIcon());
else {
ivPoolIcon.setImageBitmap(ProviderManager.getDefaultPoolIcon(getApplicationContext(), poolItem));
}
} else {
poolEdit = new PoolItem();
poolEdit.setUserDefined(true);
poolEditBackup = null;
ivPoolIcon.setImageBitmap(ProviderManager.getDefaultPoolIcon(getApplicationContext(), null));
}
boolean isUserDefined = poolEdit.isUserDefined();
etPoolName.setEnabled(isUserDefined);
etPoolURL.setEnabled(isUserDefined);
TextView tvPort = promptsView.findViewById(R.id.tvPort);
tvPort.setVisibility(isUserDefined ? View.GONE : View.VISIBLE);
LinearLayout llspinnerPort = promptsView.findViewById(R.id.llSpinnerPort);
llspinnerPort.setVisibility(isUserDefined ? View.GONE : View.VISIBLE);
etPoolPort.setVisibility(isUserDefined ? View.VISIBLE : View.GONE);
ivPoolIcon.setEnabled(isUserDefined);
btnSelectImage.setEnabled(isUserDefined);
if (isUserDefined) {
String port = poolItem != null ? poolItem.getPort() : "";
Objects.requireNonNull(etPoolPort.getEditText()).setText(port);
} else {
replacedert poolItem != null;
ArrayList<String> ports = poolItem.getPorts();
if (ports.isEmpty())
ports.add(poolItem.getDefaultPort());
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.spinner_text, ports);
spPoolPort.setAdapter(adapter);
String selectedPort = poolItem.getPort();
int selectedPortIndex = 0;
for (int i = 0; i < ports.size(); i++) {
if (ports.get(i).equals(selectedPort)) {
selectedPortIndex = i;
break;
}
}
spPoolPort.setSelection(selectedPortIndex);
}
// set dialog message
alertDialogBuilder.setCancelable(false).setPositiveButton(getString(R.string.ok), null).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
undoChanges();
closeDialog();
// to refresh test results
poolsAdapter.dataSetChanged();
}
});
editDialog = alertDialogBuilder.create();
// these need to be here, since we don't always close the dialog
editDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(final DialogInterface dialog) {
Button button = editDialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
apply();
}
});
}
});
// refresh();
}
@SuppressLint("IntentReset")
public void pickImage() {
@SuppressLint("IntentReset")
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EditDialog.GET_FROM_GALLERY & resultCode == Activity.RESULT_OK) {
// Already save the cropped image
Bitmap bitmap = Utils.getCroppedBitmap((Bitmap) data.getExtras().get("data"));
poolEdit.setIcon(bitmap);
EditDialog diag = createEditDialog(poolEdit);
if (diag != null) {
diag.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void onNext(View view) {
Config.write(Config.CONFIG_SELECTED_POOL, selectedPool.getKey().trim());
Config.write(Config.CONFIG_CUSTOM_PORT, selectedPool.getSelectedPort().trim());
startActivity(new Intent(PoolActivity.this, WizardSettingsActivity.clreplaced));
}
static public void parseVolleyError(VolleyError error) {
String message = "";
try {
if (error.networkResponse != null) {
String responseBody = new String(error.networkResponse.data, StandardCharsets.UTF_8);
JSONObject data = new JSONObject(responseBody);
JSONArray errors = data.getJSONArray("errors");
JSONObject jsonMessage = errors.getJSONObject(0);
message = "VolleyError: " + jsonMessage.getString("message");
} else {
message = error.getMessage();
}
} catch (JSONException e) {
message = "JSONException: " + e.getMessage();
} catch (NullPointerException e) {
message = "NullPointerException: " + e.getMessage();
} catch (Exception e) {
message = "Exception: " + e.getMessage();
} finally {
replacedert message != null;
Log.i("parseVolleyError:", message);
}
}
@SuppressLint("StaticFieldLeak")
private clreplaced AsyncLoadPools extends AsyncTask<Void, PoolItem, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
poolsAdapter.setPools(null);
poolsAdapter.allowClick(false);
showProgressDialog(R.string.loading_pools);
selectedPool = ProviderManager.getSelectedPool();
}
@Override
protected Boolean doInBackground(Void... params) {
allPools.clear();
PoolItem[] pools = ProviderManager.getPools(getApplicationContext());
for (PoolItem poolItem : pools) {
StringRequest stringRequest = poolItem.getInterface().getStringRequest(poolsAdapter);
mPoolQueue.add(stringRequest);
allPools.add(poolItem);
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
complete();
}
@Override
protected void onCancelled(Boolean result) {
complete();
}
private void complete() {
if (ProviderManager.useDefaultPool) {
Context context = getApplicationContext();
Utils.showToast(context, context.getResources().getString(R.string.unreachable_pools_repo), Toast.LENGTH_LONG);
}
asyncLoadPools = null;
pullToRefresh.setRefreshing(false);
poolsAdapter.setPools(allPools);
poolsAdapter.allowClick(true);
rvPools.post(PoolActivity.this::updateSelectedPoolLayout);
dismissProgressDialog();
}
}
}
19
Source : MiningService.java
with GNU General Public License v3.0
from scala-network
with GNU General Public License v3.0
from scala-network
public clreplaced MiningService extends Service {
private static final String LOG_TAG = "MiningSvc";
private Process process;
private String configTemplate;
private String privatePath;
private OutputReaderThread outputHandler;
private InputReaderThread inputHandler;
private ProcessMonitor procMon;
private PowerManager.WakeLock wl;
private int accepted = 0;
private int difficulty = 0;
private int connection = 0;
private float speed = 0.0f;
private float max = 0.0f;
private String lastreplacedetPath;
private String lastOutput = "";
private static RequestQueue reqQueue;
private final static String API_IP = "https://json.geoiplookup.io/";
@Override
public void onCreate() {
super.onCreate();
privatePath = getFilesDir().getAbsolutePath();
Tools.deleteDirectoryContents(new File(privatePath));
reqQueue = Volley.newRequestQueue(this);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
super.onTaskRemoved(rootIntent);
}
@Override
public void onDestroy() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
super.onDestroy();
}
private MiningServiceStateListener listener = null;
public interface MiningServiceStateListener {
void onStateChange(Boolean state, String message);
void onStatusChange(String status, float speed, float max, int accepted, int difficulty, int connection);
}
public void setMiningServiceStateListener(MiningServiceStateListener listener) {
if (this.listener != null)
this.listener = null;
this.listener = listener;
}
Boolean mMiningServiceState = false;
private void raiseMiningServiceStateChange(boolean state, String message) {
mMiningServiceState = state;
if (listener != null)
listener.onStateChange(state, message);
}
private void raiseMiningServiceStatusChange(String status, float speed, float max, int accepted, int difficulty, int connection) {
if (listener != null)
listener.onStatusChange(status, speed, max, accepted, difficulty, connection);
}
public Boolean getMiningServiceState() {
return mMiningServiceState;
}
private void copyMinerFiles() {
String abi = Tools.getABI();
String replacedetPath = "";
String libraryPath = "";
String configPath = "";
Log.i(LOG_TAG, "MINING SERVICE ABI: " + abi);
String replacedetExtension = Config.miner_xlarig;
if (Arrays.asList(Config.SUPPORTED_ARCHITECTURES).contains(abi)) {
replacedetPath = replacedetExtension + "/" + abi;
libraryPath = "lib" + "/" + abi;
configPath = replacedetExtension + "/config.json";
} else {
Log.i(LOG_TAG, "NO replacedET PATH");
}
Log.i(LOG_TAG, "replacedET PATH: " + replacedetPath);
Log.i(LOG_TAG, "LAST replacedET PATH: " + lastreplacedetPath);
Log.i(LOG_TAG, "ABI: " + abi);
if (!replacedetPath.equals(lastreplacedetPath)) {
Tools.deleteDirectoryContents(new File(privatePath));
Tools.copyDirectoryContents(this, libraryPath, privatePath);
Tools.copyDirectoryContents(this, replacedetPath, privatePath);
configTemplate = Tools.loadConfigTemplate(this, configPath);
Tools.logDirectoryFiles(new File(privatePath));
lastreplacedetPath = replacedetPath;
}
}
clreplaced MiningServiceBinder extends Binder {
MiningService getService() {
return MiningService.this;
}
}
private static String createCpuConfig(int cores, int threads, int intensity) {
StringBuilder cpuConfig = new StringBuilder();
for (int i = 0; i < cores; i++) {
for (int j = 0; j < threads; j++) {
if (!cpuConfig.toString().equals("")) {
cpuConfig.append(",");
}
cpuConfig.append("[").append(intensity).append(",").append(i).append("]");
}
}
return "[" + cpuConfig + "]";
}
static clreplaced MiningConfig {
String username, pool, preplacedword, algo, replacedetExtension, cpuConfig, poolHost, poolPort;
int cores, threads, intensity, legacyThreads, legacyIntensity;
}
public MiningConfig newConfig(String address, String preplacedword, int cores, int threads, int intensity) {
MiningConfig config = new MiningConfig();
PoolItem pi = ProviderManager.getSelectedPool();
config.username = address;
config.cores = cores;
config.threads = threads;
config.intensity = intensity;
config.preplacedword = preplacedword;
config.algo = Config.algo;
config.replacedetExtension = Config.miner_xlarig;
config.legacyThreads = threads * cores;
config.legacyIntensity = intensity;
replacedert pi != null;
config.poolHost = pi.getPool();
config.poolPort = pi.getPort();
config.cpuConfig = createCpuConfig(cores, threads, intensity);
return config;
}
@Override
public IBinder onBind(Intent intent) {
return new MiningServiceBinder();
}
public void stopMining() {
if (outputHandler != null) {
outputHandler.interrupt();
outputHandler = null;
}
if (inputHandler != null) {
inputHandler.interrupt();
inputHandler = null;
}
if (process != null) {
process.destroy();
process = null;
}
}
public static String getIpByHost(PoolItem pi) {
String hostIP = "";
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(API_IP + pi.getPool(), new JSONObject(), future, future);
reqQueue.add(request);
try {
// Sync call
JSONObject response = future.get(5, TimeUnit.SECONDS);
hostIP = response.optString("ip");
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
if (hostIP.isEmpty())
hostIP = pi.getPoolIP();
return hostIP + ":" + pi.getPort();
}
public void startMining(MiningConfig config) {
stopMining();
new startMiningAsync().execute(config);
}
clreplaced startMiningAsync extends AsyncTask<MiningConfig, Void, String> {
String getPoolHost() {
PoolItem pi = ProviderManager.getSelectedPool();
replacedert pi != null;
return getIpByHost(pi);
}
private MiningConfig config;
protected String doInBackground(MiningConfig... config) {
try {
this.config = config[0];
this.config.pool = getPoolHost();
return "success";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
copyMinerFiles();
startMiningProcess(this.config);
}
}
public void startMiningProcess(MiningConfig config) {
Log.i(LOG_TAG, "starting...");
if (process != null) {
process.destroy();
process = null;
}
if (wl != null) {
if (wl.isHeld()) {
// Wakelock
wl.release();
}
wl = null;
}
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PARTIAL_WAKE_LOCK, "app:sleeplock");
wl.acquire(10 * 60 * 1000L);
try {
Tools.writeConfig(configTemplate, config, privatePath);
String[] args = { "./" + Config.miner_xlarig };
ProcessBuilder pb = new ProcessBuilder(args);
pb.directory(new File(privatePath));
pb.environment().put("LD_LIBRARY_PATH", privatePath);
pb.redirectErrorStream();
accepted = 0;
difficulty = 0;
connection = 0;
speed = -1.0f;
max = -1.0f;
lastOutput = "";
process = pb.start();
outputHandler = new MiningService.OutputReaderThread(process.getInputStream());
outputHandler.start();
inputHandler = new MiningService.InputReaderThread(process.getOutputStream());
inputHandler.start();
if (procMon != null) {
procMon.interrupt();
procMon = null;
}
procMon = new ProcessMonitor(process);
procMon.start();
} catch (Exception e) {
Log.e(LOG_TAG, "exception:", e);
Utils.showToast(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT);
process = null;
}
}
public String getOutput() {
if (outputHandler != null && outputHandler.getOutput() != null) {
lastOutput = outputHandler.getOutput().toString();
}
return lastOutput;
}
public void sendInput(String s) {
if (inputHandler != null) {
inputHandler.sendInput(s);
}
}
private clreplaced ProcessMonitor extends Thread {
Process proc;
ProcessMonitor(Process proc) {
this.proc = proc;
}
public void run() {
try {
raiseMiningServiceStateChange(true, "");
if (proc != null) {
proc.waitFor();
Log.i(LOG_TAG, "process exit: " + proc.exitValue());
}
raiseMiningServiceStateChange(false, "");
} catch (Exception e) {
// replacedume problem with process and not running
raiseMiningServiceStateChange(false, e.getMessage());
Log.e(LOG_TAG, "exception:", e);
}
}
}
private clreplaced OutputReaderThread extends Thread {
private InputStream inputStream;
private StringBuilder output = new StringBuilder();
OutputReaderThread(InputStream inputStream) {
this.inputStream = inputStream;
}
private void processLogLine(String line) {
output.append(line).append(System.getProperty("line.separator"));
String lineCompare = line.toLowerCase();
if (lineCompare.contains("accepted")) {
accepted++;
if (lineCompare.contains("diff")) {
int i = lineCompare.indexOf("diff ") + "diff ".length();
int imax = lineCompare.indexOf(" ", i);
difficulty = Integer.parseInt(lineCompare.substring(i, imax).trim());
}
if (lineCompare.contains("ms)")) {
int i = lineCompare.indexOf("(", lineCompare.length() - 10) + 1;
int imax = lineCompare.indexOf("ms)");
connection = Integer.parseInt(lineCompare.substring(i, imax).trim());
}
} else // For some reason some devices display "miner" instead of "speed"
if (lineCompare.contains("speed")) {
String[] split = TextUtils.split(line, " ");
String tmpSpeed = lineCompare.contains("miner") ? split[9] : split[4];
if (tmpSpeed.equals("n/a")) {
tmpSpeed = split[5];
if (tmpSpeed.equals("n/a")) {
tmpSpeed = split[6];
}
}
try {
speed = Float.parseFloat(tmpSpeed.trim());
} catch (NumberFormatException e) {
// Ignore
}
if (lineCompare.contains("max")) {
int i = lineCompare.indexOf("max ") + "max ".length();
int imax = lineCompare.indexOf(" ", i);
String tmpMax = lineCompare.substring(i, imax).trim();
try {
max = Float.parseFloat(tmpMax);
} catch (NumberFormatException e) {
// Ignore
}
}
}
if (output.length() > Config.logMaxLength) {
output.delete(0, output.indexOf(Objects.requireNonNull(System.getProperty("line.separator")), Config.logPruneLength) + 1);
}
raiseMiningServiceStatusChange(line, speed, max, accepted, difficulty, connection);
}
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
Log.i(LOG_TAG, "miner: " + line);
processLogLine(line);
if (currentThread().isInterrupted())
return;
}
} catch (IOException e) {
Log.w(LOG_TAG, "exception", e);
}
}
public StringBuilder getOutput() {
return output;
}
}
private clreplaced InputReaderThread extends Thread {
private OutputStream outputStream;
private BufferedWriter writer;
InputReaderThread(OutputStream outputStream) {
this.outputStream = outputStream;
}
public void run() {
try {
writer = new BufferedWriter(new OutputStreamWriter(outputStream));
while (true) {
try {
Thread.sleep(250);
} catch (InterruptedException ignored) {
}
if (currentThread().isInterrupted()) {
return;
}
}
} catch (Exception e) {
Log.w(LOG_TAG, "exception", e);
}
}
public void sendInput(String s) {
try {
writer.write(s);
writer.flush();
} catch (Exception e) {
Log.w(LOG_TAG, "exception", e);
}
}
}
/*public boolean isMiningProcessAlive() {
try {
if(process != null) {
process.exitValue();
}
} catch(IllegalThreadStateException ignored) {
// Mining process is alive
return true;
}
return false;
}*/
}
19
Source : AppController.java
with Apache License 2.0
from sarveshchavan7
with Apache License 2.0
from sarveshchavan7
public clreplaced AppController extends Application {
public static final String TAG = AppController.clreplaced.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
addToRequestQueue(req, TAG);
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
19
Source : FilmySyncAdapter.java
with Apache License 2.0
from salRoid
with Apache License 2.0
from salRoid
/*
* Filmy Application for Android
* Copyright (c) 2016 Ramankit Singh (http://github.com/webianks).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public clreplaced FilmySyncAdapter extends AbstractThreadedSyncAdapter {
public static final int SYNC_INTERVAL = 60 * 180;
// Interval at which to sync with the weather, in seconds.
// 60 seconds (1 minute) * 180 = 3 hours
public static final int SYNC_FLEXTIME = SYNC_INTERVAL / 3;
private static final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
private static final int NOTIFICATION_ID = 3004;
private static String LOG_TAG = FilmySyncAdapter.clreplaced.getSimpleName();
Resources resource = FilmyApplication.getContext().getResources();
TmdbVolleySingleton tmdbVolleySingleton = TmdbVolleySingleton.getInstance();
RequestQueue tmdbrequestQueue = tmdbVolleySingleton.getRequestQueue();
private String api_key = BuildConfig.TMDB_API_KEY;
public FilmySyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
/**
* Helper method to have the sync adapter sync immediately
*
* @param context The context used to access the account service
*/
public static void syncImmediately(Context context) {
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle);
}
/**
* Helper method to schedule the sync adapter periodic execution
*/
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
Account account = getSyncAccount(context);
String authority = context.getString(R.string.content_authority);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// we can enable inexact timers in our periodic sync
SyncRequest request = new SyncRequest.Builder().syncPeriodic(syncInterval, flexTime).setSyncAdapter(account, authority).setExtras(new Bundle()).build();
ContentResolver.requestSync(request);
} else {
ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval);
}
}
/**
* Helper method to get the fake account to be used with SyncAdapter, or make a new one
* if the fake account doesn't exist yet. If we make a new account, we call the
* onAccountCreated method so we can initialize things.
*
* @param context The context used to access the account service
* @return a fake account.
*/
public static Account getSyncAccount(Context context) {
// Get an instance of the Android account manager
AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
// Create the account type and default account
Account newAccount = new Account(context.getString(R.string.app_name), context.getString(R.string.sync_account_type));
// If the preplacedword doesn't exist, the account doesn't exist
if (null == accountManager.getPreplacedword(newAccount)) {
/*
* Add the account and account type, no preplacedword or user data
* If successful, return the Account object, otherwise report an error.
*/
if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
return null;
}
/*
* If you don't set android:syncable="true" in
* in your <provider> element in the manifest,
* then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
* here.
*/
onAccountCreated(newAccount, context);
}
return newAccount;
}
private static void onAccountCreated(Account newAccount, Context context) {
/*
* Since we've created an account
*/
FilmySyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME);
/*
* Without calling setSyncAutomatically, our periodic sync will not be enabled.
*/
ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true);
/*
* Finally, let's do a sync to get things started
*/
syncImmediately(context);
}
public static void initializeSyncAdapter(Context context) {
getSyncAccount(context);
}
@Override
public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
syncNowTrending();
syncNowInTheaters();
syncNowUpComing();
}
private void syncNowInTheaters() {
final String Intheatres_Base_URL = resource.getString(R.string.tmdb_movie_base_url) + "now_playing?" + api_key;
JsonObjectRequest IntheatresJsonObjectRequest = new JsonObjectRequest(Intheatres_Base_URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
intheatresparseOutput(response.toString(), 2);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("webi", "Volley Error: " + error.getCause());
}
});
tmdbrequestQueue.add(IntheatresJsonObjectRequest);
}
private void syncNowUpComing() {
final String Upcoming_Base_URL = resource.getString(R.string.tmdb_movie_base_url) + "upcoming?" + api_key;
JsonObjectRequest UpcomingJsonObjectRequest = new JsonObjectRequest(Upcoming_Base_URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
upcomingparseOutput(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("webi", "Volley Error: " + error.getCause());
}
});
tmdbrequestQueue.add(UpcomingJsonObjectRequest);
}
private void syncNowTrending() {
final String BASE_URL = "https://api.themoviedb.org/3/movie/popular?api_key=b640f55eb6ecc47b3433cfe98d0675b1";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(BASE_URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
parseOutput(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("webi", "Volley Error: " + error.getCause());
}
});
tmdbrequestQueue.add(jsonObjectRequest);
}
private void intheatresparseOutput(String s, int type) {
MainActivityParseWork pa = new MainActivityParseWork(getContext(), s);
pa.inTheatres();
}
private void upcomingparseOutput(String result_upcoming) {
MainActivityParseWork pa = new MainActivityParseWork(getContext(), result_upcoming);
pa.parseUpcoming();
}
private void parseOutput(String result) {
MainActivityParseWork pa = new MainActivityParseWork(getContext(), result);
pa.parse();
}
}
19
Source : VolleySingleton.java
with Apache License 2.0
from salRoid
with Apache License 2.0
from salRoid
/*
* Filmy Application for Android
* Copyright (c) 2016 Sajal Gupta (http://github.com/salroid).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public clreplaced VolleySingleton {
public static VolleySingleton instance = null;
private RequestQueue requestQueue;
private VolleySingleton() {
requestQueue = Volley.newRequestQueue(FilmyApplication.getContext(), new MyHurlStack());
}
public static VolleySingleton getInstance() {
if (instance == null) {
instance = new VolleySingleton();
}
return instance;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
}
19
Source : TmdbVolleySingleton.java
with Apache License 2.0
from salRoid
with Apache License 2.0
from salRoid
/*
* Filmy Application for Android
* Copyright (c) 2016 Sajal Gupta (http://github.com/salroid).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public clreplaced TmdbVolleySingleton {
public static TmdbVolleySingleton instance = null;
private RequestQueue requestQueue;
private TmdbVolleySingleton() {
requestQueue = Volley.newRequestQueue(FilmyApplication.getContext());
}
public static TmdbVolleySingleton getInstance() {
if (instance == null) {
instance = new TmdbVolleySingleton();
}
return instance;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
}
19
Source : QuestionLoaderActivity.java
with MIT License
from rituraj22
with MIT License
from rituraj22
public clreplaced QuestionLoaderActivity extends AppCompatActivity {
String apiurl, code, qcode;
RequestQueue queue;
SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contest);
swipeRefreshLayout = findViewById(R.id.contest_swipe_refresh_layout);
findViewById(R.id.contest_toolbar).setVisibility(View.GONE);
findViewById(R.id.full_contest_download).setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(true);
code = getIntent().getExtras().getString("code");
qcode = getIntent().getExtras().getString("qcode");
apiurl = "https://www.codechef.com/api/contests/" + code + "/problems/" + qcode;
queue = Volley.newRequestQueue(this);
File f = new File(getFilesDir(), qcode + ".extra2");
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, apiurl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String qname = response.getString("problem_name");
String cname = "Practice Question";
if (!code.equals("PRACTICE")) {
cname = response.getString("contest_name");
}
Intent i = new Intent(getApplicationContext(), QuestionActivity.clreplaced);
i.putExtra("code", qcode);
i.putExtra("name", qname);
i.putExtra("contest", code);
i.putExtra("cname", cname);
startActivity(i);
finish();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Not a question, trying to open in browser", Toast.LENGTH_SHORT).show();
StaticHelper.openBrowser("https://www.codechef.com/" + code + "/problems/" + qcode, getApplicationContext());
finish();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(), "Error loading", Toast.LENGTH_SHORT).show();
}
});
if (f.exists()) {
Intent i = new Intent(getApplicationContext(), QuestionActivity.clreplaced);
swipeRefreshLayout.setRefreshing(false);
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(f);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream, Charset.forName("UTF-8")));
i.putExtra("code", qcode);
i.putExtra("name", bufferedReader.readLine());
i.putExtra("contest", code);
i.putExtra("cname", bufferedReader.readLine());
fileInputStream.close();
bufferedReader.close();
startActivity(i);
finish();
} catch (FileNotFoundException e) {
queue.add(jsonObjectRequest);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
queue.add(jsonObjectRequest);
}
} else {
queue.add(jsonObjectRequest);
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
queue.add(jsonObjectRequest);
}
});
}
}
19
Source : ContestLoaderActivity.java
with MIT License
from rituraj22
with MIT License
from rituraj22
public clreplaced ContestLoaderActivity extends AppCompatActivity {
String apiurl, code;
RequestQueue queue;
SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contest);
swipeRefreshLayout = findViewById(R.id.contest_swipe_refresh_layout);
findViewById(R.id.contest_toolbar).setVisibility(View.GONE);
findViewById(R.id.full_contest_download).setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(true);
queue = Volley.newRequestQueue(this);
code = getIntent().getExtras().getString("code");
apiurl = "https://www.codechef.com/api/contests/" + code;
File file = new File(getFilesDir(), code + ".contest");
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, apiurl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject time = response.getJSONObject("time");
String contestName = response.getString("name");
long start = time.getLong("start");
long end = time.getLong("end");
Date startDate = new Date(start * 1000);
Date endDate = new Date(end * 1000);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
String sDate = simpleDateFormat.format(startDate);
String eDate = simpleDateFormat.format(endDate);
Intent i = new Intent(getApplicationContext(), ContestActivity.clreplaced);
swipeRefreshLayout.setRefreshing(false);
i.putExtra("code", code);
i.putExtra("name", contestName);
i.putExtra("start", sDate);
i.putExtra("end", eDate);
startActivity(i);
finish();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Not a contest, trying to open in browser", Toast.LENGTH_SHORT).show();
StaticHelper.openBrowser("https://www.codechef.com/" + code, getApplicationContext());
finish();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error loading", Toast.LENGTH_SHORT).show();
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
queue.add(jsonObjectRequest);
}
});
if (file.exists()) {
Intent i = new Intent(getApplicationContext(), ContestActivity.clreplaced);
swipeRefreshLayout.setRefreshing(false);
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream, Charset.forName("UTF-8")));
i.putExtra("code", code);
i.putExtra("name", bufferedReader.readLine());
i.putExtra("start", bufferedReader.readLine());
i.putExtra("end", bufferedReader.readLine());
fileInputStream.close();
bufferedReader.close();
startActivity(i);
finish();
} catch (FileNotFoundException e) {
e.printStackTrace();
queue.add(jsonObjectRequest);
} catch (IOException e) {
e.printStackTrace();
queue.add(jsonObjectRequest);
}
} else {
queue.add(jsonObjectRequest);
}
}
}
19
Source : WeatherRepositoryImplVolley.java
with Apache License 2.0
from Reyurnible
with Apache License 2.0
from Reyurnible
/**
* Volleyでの実装
* https://github.com/mcxiaoke/android-volley
*/
public clreplaced WeatherRepositoryImplVolley implements WeatherRepository {
public static final String TAG = WeatherRepositoryImplVolley.clreplaced.getSimpleName();
RequestQueue queue;
public WeatherRepositoryImplVolley(Context context) {
queue = Volley.newRequestQueue(context);
}
@Override
public void getWeather(final RequestCallback callback) {
final JsonObjectRequest request = new JsonObjectRequest(uri.toString(), null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "result: " + response.toString());
final Weather weather = new Gson().fromJson(response.toString(), Weather.clreplaced);
callback.success(weather);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callback.error(error);
}
});
queue.add(request);
}
}
19
Source : MyApp.java
with Apache License 2.0
from RealMoMo
with Apache License 2.0
from RealMoMo
/**
* Created by Administrator on 2016/12/6 0006.
*/
public clreplaced MyApp extends Application {
private RequestQueue queue;
@Override
public void onCreate() {
super.onCreate();
// 初始化RequestQueue
queue = Volley.newRequestQueue(this);
}
public RequestQueue getRequestQueue() {
return queue;
}
}
19
Source : NetworkClient.java
with MIT License
from OpenST
with MIT License
from OpenST
public clreplaced NetworkClient {
private static RequestQueue mRequestQueue;
/**
* Nothing to see here.
*/
private NetworkClient() {
// no instances
}
/**
* @param context
* application context
*/
public static void init(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
}
public static RequestQueue getRequestQueue() {
return mRequestQueue;
}
}
19
Source : MappyNetworkClient.java
with MIT License
from OpenST
with MIT License
from OpenST
public clreplaced MappyNetworkClient {
private static final String USERNAME = "username";
private static final String PreplacedWORD = "preplacedword";
private static final String DEVICE_ADDRESS = "address";
private static final String API_SIGNER_ADDRESS = "api_signer_address";
private static final String UNAUTHORIZED = "401 Unauthorized";
private final String mUrl;
private final RequestQueue mRequestQueue;
public MappyNetworkClient(String url, RequestQueue requestQueue) {
this.mUrl = url;
this.mRequestQueue = requestQueue;
}
public void createAccount(String userName, String preplacedword, ResponseCallback callback) {
try {
JSONObject params = new JSONObject();
params.put(USERNAME, userName);
params.put(PreplacedWORD, preplacedword);
sendRequest(Request.Method.POST, "signup", params, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void logIn(String userName, String preplacedword, ResponseCallback callback) {
try {
JSONObject params = new JSONObject();
params.put(USERNAME, userName);
params.put(PreplacedWORD, preplacedword);
sendRequest(Request.Method.POST, "login", params, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void registerDevice(String deviceAddress, String apiSignerAddress, ResponseCallback callback) {
try {
JSONObject params = new JSONObject();
params.put(DEVICE_ADDRESS, deviceAddress);
params.put(API_SIGNER_ADDRESS, apiSignerAddress);
sendRequest(Request.Method.POST, "devices", params, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void getLoggedInUserPinSalt(ResponseCallback callback) {
try {
JSONObject params = new JSONObject();
sendRequest(Request.Method.GET, "users/current-user-salt", params, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void getLoggedInUser(ResponseCallback callback) {
try {
JSONObject params = new JSONObject();
sendRequest(Request.Method.GET, "users/current-user", params, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void notifyUserActivate(final ResponseCallback callback) {
try {
JSONObject params = new JSONObject();
sendRequest(Request.Method.POST, "notify/user-activate", params, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void getCurrentUserBalance(final ResponseCallback callback) {
try {
JSONObject params = new JSONObject();
sendRequest(Request.Method.GET, String.format("users/%s/balance", AppProvider.get().getCurrentUser().getId()), params, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void postCrashlyticsPreference(final boolean postCrash, ResponseCallback callback) {
try {
String userId = AppProvider.get().getCurrentUser().getId();
String ostUserId = AppProvider.get().getCurrentUser().getOstUserId();
String deviceAddress = OstSdk.getUser(ostUserId).getCurrentDevice().getAddress();
JSONObject params = new JSONObject();
params.put("preference", postCrash ? 1 : 0);
params.put("device_address", deviceAddress);
sendRequest(Request.Method.POST, String.format("users/%s/set-preference", userId), params, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void getCrashlyticsPreference(ResponseCallback callback) {
try {
String userId = AppProvider.get().getCurrentUser().getId();
String ostUserId = AppProvider.get().getCurrentUser().getOstUserId();
String deviceAddress = OstSdk.getUser(ostUserId).getCurrentDevice().getAddress();
JSONObject params = new JSONObject();
sendRequest(Request.Method.GET, String.format("users/%s/get-preference?device_address=%s", userId, deviceAddress), params, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void getCurrentUserTransactions(final JSONObject nextPayload, final ResponseCallback callback) {
try {
String urlResource = String.format("users/ledger", AppProvider.get().getCurrentUser().getId());
String nextPageParams = addNextPagePayload(nextPayload);
urlResource += nextPageParams.equals("") ? "" : String.format("?%s", nextPageParams);
sendRequest(Request.Method.GET, urlResource, null, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void getUserList(JSONObject nextPayload, ResponseCallback callback) {
try {
String urlResource = "users";
String nextPageParams = addNextPagePayload(nextPayload);
urlResource += nextPageParams.equals("") ? "" : String.format("?%s", nextPageParams);
sendRequest(Request.Method.GET, urlResource, null, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
public void getCurrentUserDevices(JSONObject nextPayload, ResponseCallback callback) {
try {
String urlResource = "devices";
String nextPageParams = addNextPagePayload(nextPayload);
urlResource += nextPageParams.equals("") ? "" : String.format("?%s", nextPageParams);
sendRequest(Request.Method.GET, urlResource, null, callback);
} catch (Exception ex) {
callback.onFailure(ex);
}
}
private String addNextPagePayload(JSONObject payload) {
String payloadParams = "";
try {
if (payload != null && !payload.toString().equals("{}")) {
JSONObject nextPagePayload = payload.getJSONObject("next_page_payload");
Iterator<?> keys = nextPagePayload.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
Object value = nextPagePayload.get(key);
payloadParams += String.format("%s=%s&", key, value);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return payloadParams;
}
private void sendRequest(int method, final String resource, JSONObject params, final ResponseCallback callback) {
String logInUrl = String.format("%s%s", mUrl, resource);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(method, logInUrl, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (null != error.networkResponse && !(resource.equalsIgnoreCase("users/current-user")) && null != error.networkResponse.headers && UNAUTHORIZED.equalsIgnoreCase(error.networkResponse.headers.get("Status"))) {
DialogFactory.createSimpleOkErrorDialog(AppProvider.get().getCurrentActivity(), "Cookie expired", "Login required", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AppProvider.get().relaunchApp();
}
}).show();
} else {
callback.onFailure(error.getCause());
}
}
});
mRequestQueue.add(jsonObjectRequest);
}
public interface ResponseCallback {
void onSuccess(JSONObject jsonObject);
void onFailure(Throwable throwable);
}
}
19
Source : ApiInvoker.java
with Apache License 2.0
from OpenAPITools
with Apache License 2.0
from OpenAPITools
public clreplaced ApiInvoker {
private static ApiInvoker INSTANCE;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private RequestQueue mRequestQueue;
private Map<String, Authentication> authentications;
private int connectionTimeout;
/**
* Content type "text/plain" with UTF-8 encoding.
*/
public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8);
/**
* ISO 8601 date time format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
/**
* ISO 8601 date format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
static {
// Use UTC as the default time zone.
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public static void setUserAgent(String userAgent) {
INSTANCE.addDefaultHeader("User-Agent", userAgent);
}
public static Date parseDateTime(String str) {
try {
return DATE_TIME_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static Date parseDate(String str) {
try {
return DATE_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static String formatDateTime(Date datetime) {
return DATE_TIME_FORMAT.format(datetime);
}
public static String formatDate(Date date) {
return DATE_FORMAT.format(date);
}
public static String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDateTime((Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for (Object o : (Collection) param) {
if (b.length() > 0) {
b.append(",");
}
b.append(String.valueOf(o));
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/*
Format to {@code Pair} objects.
*/
public static List<Pair> parameterToPairs(String collectionFormat, String name, Object value) {
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null)
return params;
Collection valueCollection = null;
if (value instanceof Collection) {
valueCollection = (Collection) value;
} else {
params.add(new Pair(name, parameterToString(value)));
return params;
}
if (valueCollection.isEmpty()) {
return params;
}
// get the collection format
// default: csv
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat);
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
for (Object item : valueCollection) {
params.add(new Pair(name, parameterToString(item)));
}
return params;
}
String delimiter = ",";
if (collectionFormat.equals("csv")) {
delimiter = ",";
} else if (collectionFormat.equals("ssv")) {
delimiter = " ";
} else if (collectionFormat.equals("tsv")) {
delimiter = "\t";
} else if (collectionFormat.equals("pipes")) {
delimiter = "|";
}
StringBuilder sb = new StringBuilder();
for (Object item : valueCollection) {
sb.append(delimiter);
sb.append(parameterToString(item));
}
params.add(new Pair(name, sb.substring(1)));
return params;
}
public static void initializeInstance() {
initializeInstance(null);
}
public static void initializeInstance(Cache cache) {
initializeInstance(cache, null, 0, null, 30);
}
public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) {
INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout);
setUserAgent("OpenAPI-Generator/1.0.0/android");
// Setup authentications (key: authentication name, value: authentication).
INSTANCE.authentications = new HashMap<String, Authentication>();
INSTANCE.authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
// TODO: comment out below as OAuth does not exist
// INSTANCE.authentications.put("petstore_auth", new OAuth());
// Prevent the authentications from being modified.
INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications);
}
private ApiInvoker(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) {
if (cache == null)
cache = new NoCache();
if (network == null) {
HttpStack stack = new HurlStack();
network = new BasicNetwork(stack);
}
if (delivery == null) {
initConnectionRequest(cache, network);
} else {
initConnectionRequest(cache, network, threadPoolSize, delivery);
}
this.connectionTimeout = connectionTimeout;
}
public static ApiInvoker getInstance() {
if (INSTANCE == null)
initializeInstance();
return INSTANCE;
}
public void addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
}
public String escapeString(String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
return str;
}
}
public static Object deserialize(String json, String containerType, Clreplaced cls) throws ApiException {
try {
if ("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
return JsonUtil.deserializeToList(json, cls);
} else if (String.clreplaced.equals(cls)) {
if (json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 1);
else
return json;
} else {
return JsonUtil.deserializeToObject(json, cls);
}
} catch (JsonParseException e) {
throw new ApiException(500, e.getMessage());
}
}
public static String serialize(Object obj) throws ApiException {
try {
if (obj != null)
return JsonUtil.serialize(obj);
else
return null;
} catch (Exception e) {
throw new ApiException(500, e.getMessage());
}
}
/**
* Get authentications (key: authentication name, value: authentication).
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
/**
* Helper method to set username for the first HTTP basic authentication.
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set preplacedword for the first HTTP basic authentication.
*/
public void setPreplacedword(String preplacedword) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPreplacedword(preplacedword);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
*/
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null)
throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
}
}
public String invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException {
try {
RequestFuture<String> future = RequestFuture.newFuture();
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future);
if (request != null) {
mRequestQueue.add(request);
return future.get(connectionTimeout, TimeUnit.SECONDS);
} else {
return "no data";
}
} catch (UnsupportedEncodingException ex) {
throw new ApiException(0, "UnsupportedEncodingException");
}
}
public void invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
try {
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener);
if (request != null) {
mRequestQueue.add(request);
}
} catch (UnsupportedEncodingException ex) {
throw new ApiException(0, "UnsupportedEncodingException");
}
}
public Request<String> createRequest(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException, UnsupportedEncodingException {
StringBuilder b = new StringBuilder();
b.append("?");
updateParamsForAuth(authNames, queryParams, headerParams);
if (queryParams != null) {
for (Pair queryParam : queryParams) {
if (!queryParam.getName().isEmpty()) {
b.append(escapeString(queryParam.getName()));
b.append("=");
b.append(escapeString(queryParam.getValue()));
b.append("&");
}
}
}
String querystring = b.substring(0, b.length() - 1);
String url = host + path + querystring;
HashMap<String, String> headers = new HashMap<String, String>();
for (String key : headerParams.keySet()) {
headers.put(key, headerParams.get(key));
}
for (String key : defaultHeaderMap.keySet()) {
if (!headerParams.containsKey(key)) {
headers.put(key, defaultHeaderMap.get(key));
}
}
headers.put("Accept", "application/json");
// URL encoded string from form parameters
String formParamStr = null;
// for form data
if ("application/x-www-form-urlencoded".equals(contentType)) {
StringBuilder formParamBuilder = new StringBuilder();
// encode the form params
for (String key : formParams.keySet()) {
String value = formParams.get(key);
if (value != null && !"".equals(value.trim())) {
if (formParamBuilder.length() > 0) {
formParamBuilder.append("&");
}
try {
formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8"));
} catch (Exception e) {
// move on to next
}
}
}
formParamStr = formParamBuilder.toString();
}
Request request = null;
if ("GET".equals(method)) {
request = new GetRequest(url, headers, null, stringRequest, errorListener);
} else if ("POST".equals(method)) {
request = null;
if (formParamStr != null) {
request = new PostRequest(url, headers, contentType, new StringEnreplacedy(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEnreplacedy) {
request = new PostRequest(url, headers, null, (HttpEnreplacedy) body, stringRequest, errorListener);
} else {
request = new PostRequest(url, headers, contentType, new StringEnreplacedy(serialize(body), "UTF-8"), stringRequest, errorListener);
}
} else {
request = new PostRequest(url, headers, null, null, stringRequest, errorListener);
}
} else if ("PUT".equals(method)) {
request = null;
if (formParamStr != null) {
request = new PutRequest(url, headers, contentType, new StringEnreplacedy(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEnreplacedy) {
request = new PutRequest(url, headers, null, (HttpEnreplacedy) body, stringRequest, errorListener);
} else {
request = new PutRequest(url, headers, contentType, new StringEnreplacedy(serialize(body), "UTF-8"), stringRequest, errorListener);
}
} else {
request = new PutRequest(url, headers, null, null, stringRequest, errorListener);
}
} else if ("DELETE".equals(method)) {
request = null;
if (formParamStr != null) {
request = new DeleteRequest(url, headers, contentType, new StringEnreplacedy(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEnreplacedy) {
request = new DeleteRequest(url, headers, null, (HttpEnreplacedy) body, stringRequest, errorListener);
} else {
request = new DeleteRequest(url, headers, contentType, new StringEnreplacedy(serialize(body), "UTF-8"), stringRequest, errorListener);
}
} else {
request = new DeleteRequest(url, headers, null, null, stringRequest, errorListener);
}
} else if ("PATCH".equals(method)) {
request = null;
if (formParamStr != null) {
request = new PatchRequest(url, headers, contentType, new StringEnreplacedy(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEnreplacedy) {
request = new PatchRequest(url, headers, null, (HttpEnreplacedy) body, stringRequest, errorListener);
} else {
request = new PatchRequest(url, headers, contentType, new StringEnreplacedy(serialize(body), "UTF-8"), stringRequest, errorListener);
}
} else {
request = new PatchRequest(url, headers, null, null, stringRequest, errorListener);
}
}
if (request != null) {
request.setRetryPolicy(new DefaultRetryPolicy((int) TimeUnit.SECONDS.toMillis(this.connectionTimeout), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
return request;
}
private void initConnectionRequest(Cache cache, Network network) {
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
}
private void initConnectionRequest(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) {
mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery);
mRequestQueue.start();
}
public void stopQueue() {
mRequestQueue.stop();
}
}
19
Source : MapBoxWebServiceApi.java
with BSD 2-Clause "Simplified" License
from onaio
with BSD 2-Clause "Simplified" License
from onaio
/**
* Created by Ephraim Kigamba - [email protected] on 16/11/2017.
*/
public clreplaced MapBoxWebServiceApi {
private String mapboxApiUrl = "https://api.mapbox.com", stylesPath = "/styles/v1";
private RequestQueue requestQueue;
private String mapboxAccessToken;
public MapBoxWebServiceApi(Context context, @NonNull String mapboxAccessToken) {
requestQueue = Volley.newRequestQueue(context);
this.mapboxAccessToken = mapboxAccessToken;
}
public void retrieveStyleJSON(@NonNull final String username, @NonNull final String styleId, @NonNull final Response.Listener<String> responseListener, @NonNull final Response.ErrorListener errorListener) {
if (username.isEmpty() || styleId.isEmpty()) {
errorListener.onErrorResponse(new VolleyError("Invalid username OR styleId"));
return;
}
String url = mapboxApiUrl + stylesPath + "/" + username + "/" + styleId + "?access_token=" + mapboxAccessToken;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response != null && !response.isEmpty()) {
MapBoxStyleStorage mapBoxStyleStorage = new MapBoxStyleStorage();
mapBoxStyleStorage.cacheStyle("mapbox://styles/" + username + File.separator + styleId, response);
}
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
String cachedStyle = (new MapBoxStyleStorage()).getCachedStyle("mapbox://styles/" + username + File.separator + styleId);
if (!TextUtils.isEmpty(cachedStyle)) {
responseListener.onResponse(cachedStyle);
return;
}
}
errorListener.onErrorResponse(error);
}
});
requestQueue.add(stringRequest);
}
public void retrieveStyleJSON(@NonNull String mapBoxStyleURL, @NonNull Response.Listener<String> responseListener, @NonNull Response.ErrorListener errorListener) {
if (!mapBoxStyleURL.matches(Constants.MAP_BOX_URL_FORMAT)) {
errorListener.onErrorResponse(new VolleyError("Invalid MapBox Style URL "));
return;
}
String[] styleParts = mapBoxStyleURL.split("/");
String username = styleParts[styleParts.length - 2];
String styleId = styleParts[styleParts.length - 1];
retrieveStyleJSON(username, styleId, responseListener, errorListener);
}
}
19
Source : DisplayShortenedUrlActivity.java
with GNU General Public License v3.0
from michaelachmann
with GNU General Public License v3.0
from michaelachmann
/*
* Triggers the API Request and starts the showShortenedLink() or apiError() functions accordingly
* TODO: Swap to JSON Version!
* TODO: Add to custom clreplaced
*/
private void shortenUrl() {
// Instantiate Volley for Networking
RequestQueue queue = Volley.newRequestQueue(this);
// Setup variables
String encodedOriginalUrl = null;
// Tries to encode the URL
try {
encodedOriginalUrl = URLEncoder.encode(originalUrl, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// replacedembles the URL and starts the API-Request
String url = apiUrl + "/api/v2/action/shorten?key=" + apiKey + "&url=" + encodedOriginalUrl;
// Actual Request to the API
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// If we receive a proper Response we set the response as the shortened URL
shortUrl = response;
// Trigger function which uses clreplaced-wide shortUrl variable in order to
// update the View with the actual shortened URL
showShortenedUrl();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
apiError(error);
}
});
// For volley we need to add our request to the queue. The queue starts automatically
// Do NOT add a queue.start(), it provokes errors.
queue.add(stringRequest);
}
19
Source : ImageLoader.java
with Apache License 2.0
from luocheng1111
with Apache License 2.0
from luocheng1111
/**
* Helper that handles loading and caching images from remote URLs.
*
* The simple way to use this clreplaced is to call {@link com.android.volley.toolbox.ImageLoader#get(String, com.android.volley.toolbox.ImageLoader.ImageListener)}
* and to preplaced in the default image listener provided by
* {@link com.android.volley.toolbox.ImageLoader#getImageListener(android.widget.ImageView, int, int)}. Note that all function calls to
* this clreplaced must be made from the main thead, and all responses will be delivered to the main
* thread as well.
*/
public clreplaced ImageLoader {
/**
* RequestQueue for dispatching ImageRequests onto.
*/
private final RequestQueue mRequestQueue;
/**
* Amount of time to wait after first response arrives before delivering all responses.
*/
private int mBatchResponseDelayMs = 100;
/**
* The cache implementation to be used as an L1 cache before calling into volley.
*/
private final ImageCache mCache;
/**
* HashMap of Cache keys -> BatchedImageRequest used to track in-flight requests so
* that we can coalesce multiple requests to the same URL into a single network request.
*/
private final HashMap<String, BatchedImageRequest> mInFlightRequests = new HashMap<String, BatchedImageRequest>();
/**
* HashMap of the currently pending responses (waiting to be delivered).
*/
private final HashMap<String, BatchedImageRequest> mBatchedResponses = new HashMap<String, BatchedImageRequest>();
/**
* Handler to the main thread.
*/
private final Handler mHandler = new Handler(Looper.getMainLooper());
/**
* Runnable for in-flight response delivery.
*/
private Runnable mRunnable;
/**
* Simple cache adapter interface. If provided to the ImageLoader, it
* will be used as an L1 cache before dispatch to Volley. Implementations
* must not block. Implementation with an LruCache is recommended.
*/
public interface ImageCache {
public Bitmap getBitmap(String url);
public void putBitmap(String url, Bitmap bitmap);
}
/**
* Constructs a new ImageLoader.
* @param queue The RequestQueue to use for making image requests.
* @param imageCache The cache to use as an L1 cache.
*/
public ImageLoader(RequestQueue queue, ImageCache imageCache) {
mRequestQueue = queue;
mCache = imageCache;
}
/**
* The default implementation of ImageListener which handles basic functionality
* of showing a default image until the network response is received, at which point
* it will switch to either the actual image or the error image.
* @param view The imageView that the listener is replacedociated with.
* @param defaultImageResId Default image resource ID to use, or 0 if it doesn't exist.
* @param errorImageResId Error image resource ID to use, or 0 if it doesn't exist.
*/
public static ImageListener getImageListener(final ImageView view, final int defaultImageResId, final int errorImageResId) {
return new ImageListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (errorImageResId != 0) {
view.setImageResource(errorImageResId);
}
}
@Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null) {
view.setImageBitmap(response.getBitmap());
} else if (defaultImageResId != 0) {
view.setImageResource(defaultImageResId);
}
}
};
}
/**
* Interface for the response handlers on image requests.
*
* The call flow is this:
* 1. Upon being attached to a request, onResponse(response, true) will
* be invoked to reflect any cached data that was already available. If the
* data was available, response.getBitmap() will be non-null.
*
* 2. After a network response returns, only one of the following cases will happen:
* - onResponse(response, false) will be called if the image was loaded.
* or
* - onErrorResponse will be called if there was an error loading the image.
*/
public interface ImageListener extends ErrorListener {
/**
* Listens for non-error changes to the loading of the image request.
*
* @param response Holds all information pertaining to the request, as well
* as the bitmap (if it is loaded).
* @param isImmediate True if this was called during ImageLoader.get() variants.
* This can be used to differentiate between a cached image loading and a network
* image loading in order to, for example, run an animation to fade in network loaded
* images.
*/
public void onResponse(ImageContainer response, boolean isImmediate);
}
/**
* Checks if the item is available in the cache.
* @param requestUrl The url of the remote image
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @return True if the item exists in cache, false otherwise.
*/
public boolean isCached(String requestUrl, int maxWidth, int maxHeight) {
return isCached(requestUrl, maxWidth, maxHeight, ScaleType.CENTER_INSIDE);
}
/**
* Checks if the item is available in the cache.
*
* @param requestUrl The url of the remote image
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @param scaleType The scaleType of the imageView.
* @return True if the item exists in cache, false otherwise.
*/
public boolean isCached(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType) {
throwIfNotOnMainThread();
String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
return mCache.getBitmap(cacheKey) != null;
}
/**
* Returns an ImageContainer for the requested URL.
*
* The ImageContainer will contain either the specified default bitmap or the loaded bitmap.
* If the default was returned, the {@link com.android.volley.toolbox.ImageLoader} will be invoked when the
* request is fulfilled.
*
* @param requestUrl The URL of the image to be loaded.
*/
public ImageContainer get(String requestUrl, final ImageListener listener) {
return get(requestUrl, listener, 0, 0);
}
/**
* Equivalent to calling {@link #get(String, com.android.volley.toolbox.ImageLoader.ImageListener, int, int, android.widget.ImageView.ScaleType)} with
* {@code Scaletype == ScaleType.CENTER_INSIDE}.
*/
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight) {
return get(requestUrl, imageListener, maxWidth, maxHeight, ScaleType.CENTER_INSIDE);
}
/**
* Issues a bitmap request with the given URL if that image is not available
* in the cache, and returns a bitmap container that contains all of the data
* relating to the request (as well as the default image if the requested
* image is not available).
* @param requestUrl The url of the remote image
* @param imageListener The listener to call when the remote image is loaded
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @param scaleType The ImageViews ScaleType used to calculate the needed image size.
* @return A container object that contains all of the properties of the request, as well as
* the currently available image (default if remote is not loaded).
*/
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight, ScaleType scaleType) {
// only fulfill requests that were initiated from the main thread.
throwIfNotOnMainThread();
final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
// Try to look up the request in the cache of remote images.
Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
if (cachedBitmap != null) {
// Return the cached bitmap.
ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
imageListener.onResponse(container, true);
return container;
}
// The bitmap did not exist in the cache, fetch it!
ImageContainer imageContainer = new ImageContainer(null, requestUrl, cacheKey, imageListener);
// Update the caller to let them know that they should use the default bitmap.
imageListener.onResponse(imageContainer, true);
// Check to see if a request is already in-flight.
BatchedImageRequest request = mInFlightRequests.get(cacheKey);
if (request != null) {
// If it is, add this request to the list of listeners.
request.addContainer(imageContainer);
return imageContainer;
}
// The request is not already in flight. Send the new request to the network and
// track it.
Request<Bitmap> newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey);
mRequestQueue.add(newRequest);
mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer));
return imageContainer;
}
protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType, final String cacheKey) {
return new ImageRequest(requestUrl, new Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
onGetImageSuccess(cacheKey, response);
}
}, maxWidth, maxHeight, scaleType, Config.RGB_565, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onGetImageError(cacheKey, error);
}
});
}
/**
* Sets the amount of time to wait after the first response arrives before delivering all
* responses. Batching can be disabled entirely by preplaceding in 0.
* @param newBatchedResponseDelayMs The time in milliseconds to wait.
*/
public void setBatchedResponseDelay(int newBatchedResponseDelayMs) {
mBatchResponseDelayMs = newBatchedResponseDelayMs;
}
/**
* Handler for when an image was successfully loaded.
* @param cacheKey The cache key that is replacedociated with the image request.
* @param response The bitmap that was returned from the network.
*/
protected void onGetImageSuccess(String cacheKey, Bitmap response) {
// cache the image that was fetched.
mCache.putBitmap(cacheKey, response);
// remove the request from the list of in-flight requests.
BatchedImageRequest request = mInFlightRequests.remove(cacheKey);
if (request != null) {
// Update the response bitmap.
request.mResponseBitmap = response;
// Send the batched response
batchResponse(cacheKey, request);
}
}
/**
* Handler for when an image failed to load.
* @param cacheKey The cache key that is replacedociated with the image request.
*/
protected void onGetImageError(String cacheKey, VolleyError error) {
// Notify the requesters that something failed via a null result.
// Remove this request from the list of in-flight requests.
BatchedImageRequest request = mInFlightRequests.remove(cacheKey);
if (request != null) {
// Set the error for this request
request.setError(error);
// Send the batched response
batchResponse(cacheKey, request);
}
}
/**
* Container object for all of the data surrounding an image request.
*/
public clreplaced ImageContainer {
/**
* The most relevant bitmap for the container. If the image was in cache, the
* Holder to use for the final bitmap (the one that pairs to the requested URL).
*/
private Bitmap mBitmap;
private final ImageListener mListener;
/**
* The cache key that was replacedociated with the request
*/
private final String mCacheKey;
/**
* The request URL that was specified
*/
private final String mRequestUrl;
/**
* Constructs a BitmapContainer object.
* @param bitmap The final bitmap (if it exists).
* @param requestUrl The requested URL for this container.
* @param cacheKey The cache key that identifies the requested URL for this container.
*/
public ImageContainer(Bitmap bitmap, String requestUrl, String cacheKey, ImageListener listener) {
mBitmap = bitmap;
mRequestUrl = requestUrl;
mCacheKey = cacheKey;
mListener = listener;
}
/**
* Releases interest in the in-flight request (and cancels it if no one else is listening).
*/
public void cancelRequest() {
if (mListener == null) {
return;
}
BatchedImageRequest request = mInFlightRequests.get(mCacheKey);
if (request != null) {
boolean canceled = request.removeContainerAndCancelIfNecessary(this);
if (canceled) {
mInFlightRequests.remove(mCacheKey);
}
} else {
// check to see if it is already batched for delivery.
request = mBatchedResponses.get(mCacheKey);
if (request != null) {
request.removeContainerAndCancelIfNecessary(this);
if (request.mContainers.size() == 0) {
mBatchedResponses.remove(mCacheKey);
}
}
}
}
/**
* Returns the bitmap replacedociated with the request URL if it has been loaded, null otherwise.
*/
public Bitmap getBitmap() {
return mBitmap;
}
/**
* Returns the requested URL for this container.
*/
public String getRequestUrl() {
return mRequestUrl;
}
}
/**
* Wrapper clreplaced used to map a Request to the set of active ImageContainer objects that are
* interested in its results.
*/
private clreplaced BatchedImageRequest {
/**
* The request being tracked
*/
private final Request<?> mRequest;
/**
* The result of the request being tracked by this item
*/
private Bitmap mResponseBitmap;
/**
* Error if one occurred for this response
*/
private VolleyError mError;
/**
* List of all of the active ImageContainers that are interested in the request
*/
private final LinkedList<ImageContainer> mContainers = new LinkedList<ImageContainer>();
/**
* Constructs a new BatchedImageRequest object
* @param request The request being tracked
* @param container The ImageContainer of the person who initiated the request.
*/
public BatchedImageRequest(Request<?> request, ImageContainer container) {
mRequest = request;
mContainers.add(container);
}
/**
* Set the error for this response
*/
public void setError(VolleyError error) {
mError = error;
}
/**
* Get the error for this response
*/
public VolleyError getError() {
return mError;
}
/**
* Adds another ImageContainer to the list of those interested in the results of
* the request.
*/
public void addContainer(ImageContainer container) {
mContainers.add(container);
}
/**
* Detatches the bitmap container from the request and cancels the request if no one is
* left listening.
* @param container The container to remove from the list
* @return True if the request was canceled, false otherwise.
*/
public boolean removeContainerAndCancelIfNecessary(ImageContainer container) {
mContainers.remove(container);
if (mContainers.size() == 0) {
mRequest.cancel();
return true;
}
return false;
}
}
/**
* Starts the runnable for batched delivery of responses if it is not already started.
* @param cacheKey The cacheKey of the response being delivered.
* @param request The BatchedImageRequest to be delivered.
*/
private void batchResponse(String cacheKey, BatchedImageRequest request) {
mBatchedResponses.put(cacheKey, request);
// If we don't already have a batch delivery runnable in flight, make a new one.
// Note that this will be used to deliver responses to all callers in mBatchedResponses.
if (mRunnable == null) {
mRunnable = new Runnable() {
@Override
public void run() {
for (BatchedImageRequest bir : mBatchedResponses.values()) {
for (ImageContainer container : bir.mContainers) {
// If one of the callers in the batched request canceled the request
// after the response was received but before it was delivered,
// skip them.
if (container.mListener == null) {
continue;
}
if (bir.getError() == null) {
container.mBitmap = bir.mResponseBitmap;
container.mListener.onResponse(container, false);
} else {
container.mListener.onErrorResponse(bir.getError());
}
}
}
mBatchedResponses.clear();
mRunnable = null;
}
};
// Post the runnable.
mHandler.postDelayed(mRunnable, mBatchResponseDelayMs);
}
}
private void throwIfNotOnMainThread() {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalStateException("ImageLoader must be invoked from the main thread.");
}
}
/**
* Creates a cache key for use with the L1 cache.
* @param url The URL of the request.
* @param maxWidth The max-width of the output.
* @param maxHeight The max-height of the output.
* @param scaleType The scaleType of the imageView.
*/
private static String getCacheKey(String url, int maxWidth, int maxHeight, ScaleType scaleType) {
return new StringBuilder(url.length() + 12).append("#W").append(maxWidth).append("#H").append(maxHeight).append("#S").append(scaleType.ordinal()).append(url).toString();
}
}
19
Source : VolleyHelper.java
with Apache License 2.0
from luocheng1111
with Apache License 2.0
from luocheng1111
/**
* Author: Tau.Chen
* Email: [email protected] | [email protected]
* Date: 2015/3/20.
* Description:
*/
public clreplaced VolleyHelper {
private RequestQueue requestQueue = null;
private static volatile VolleyHelper instance = null;
private VolleyHelper() {
}
public static VolleyHelper getInstance() {
if (null == instance) {
synchronized (VolleyHelper.clreplaced) {
if (null == instance) {
instance = new VolleyHelper();
}
}
}
return instance;
}
/**
* init volley helper
*
* @param context
*/
public void init(Context context) {
requestQueue = Volley.newRequestQueue(context, new OkHttpStack(new OkHttpClient()));
}
/**
* get request queue
*
* @return
*/
public RequestQueue getRequestQueue() {
if (null != requestQueue) {
return requestQueue;
} else {
throw new IllegalArgumentException("RequestQueue is not initialized.");
}
}
}
19
Source : HttpClient.java
with MIT License
from LN-Zap
with MIT License
from LN-Zap
/**
* Singleton to handle the volley http RequestQueue
*/
public clreplaced HttpClient {
private static HttpClient mHttpClientInstance;
private RequestQueue mRequestQueue;
private HttpClient() {
mRequestQueue = Volley.newRequestQueue(App.getAppContext());
}
public static synchronized HttpClient getInstance() {
if (mHttpClientInstance == null) {
mHttpClientInstance = new HttpClient();
}
return mHttpClientInstance;
}
public RequestQueue getRequestQueue() {
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(tag);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
19
Source : VolleyController.java
with MIT License
from LaQuay
with MIT License
from LaQuay
public clreplaced VolleyController {
private static VolleyController instance;
private RequestQueue fRequestQueue;
private VolleyCore volley;
private VolleyController(Context ctx) {
volley = new VolleyCore(ctx);
fRequestQueue = volley.getRequestQueue();
}
public static VolleyController getInstance(Context ctx) {
if (instance == null) {
createInstance(ctx);
}
return instance;
}
private synchronized static void createInstance(Context ctx) {
if (instance == null) {
instance = new VolleyController(ctx);
}
}
public void addToQueue(Request request) {
if (request != null) {
request.setTag(this);
if (fRequestQueue == null)
fRequestQueue = volley.getRequestQueue();
request.setRetryPolicy(new DefaultRetryPolicy(60000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
fRequestQueue.add(request);
}
}
public void onConnectionFailed(String error) {
// Toast.makeText(ctx, error, Toast.LENGTH_SHORT).show();
}
public void removeAllDataInQueue() {
if (fRequestQueue != null) {
fRequestQueue.cancelAll(this);
}
}
private clreplaced VolleyCore {
private RequestQueue mRequestQueue;
private VolleyCore(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
}
public RequestQueue getRequestQueue() {
return mRequestQueue;
}
}
}
19
Source : ImageLoader.java
with Apache License 2.0
from jiahao42
with Apache License 2.0
from jiahao42
/**
* Helper that handles loading and caching images from remote URLs.
*
* The simple way to use this clreplaced is to call {@link ImageLoader#get(String, ImageListener)}
* and to preplaced in the default image listener provided by
* {@link ImageLoader#getImageListener(ImageView, int, int)}. Note that all function calls to
* this clreplaced must be made from the main thead, and all responses will be delivered to the main
* thread as well.
*/
public clreplaced ImageLoader {
/**
* RequestQueue for dispatching ImageRequests onto.
*/
private final RequestQueue mRequestQueue;
/**
* Amount of time to wait after first response arrives before delivering all responses.
*/
private int mBatchResponseDelayMs = 100;
/**
* The cache implementation to be used as an L1 cache before calling into volley.
*/
private final ImageCache mCache;
/**
* HashMap of Cache keys -> BatchedImageRequest used to track in-flight requests so
* that we can coalesce multiple requests to the same URL into a single network request.
*/
private final HashMap<String, BatchedImageRequest> mInFlightRequests = new HashMap<String, BatchedImageRequest>();
/**
* HashMap of the currently pending responses (waiting to be delivered).
*/
private final HashMap<String, BatchedImageRequest> mBatchedResponses = new HashMap<String, BatchedImageRequest>();
/**
* Handler to the main thread.
*/
private final Handler mHandler = new Handler(Looper.getMainLooper());
/**
* Runnable for in-flight response delivery.
*/
private Runnable mRunnable;
/**
* Simple cache adapter interface. If provided to the ImageLoader, it
* will be used as an L1 cache before dispatch to Volley. Implementations
* must not block. Implementation with an LruCache is recommended.
*/
public interface ImageCache {
Bitmap getBitmap(String url);
void putBitmap(String url, Bitmap bitmap);
}
/**
* Constructs a new ImageLoader.
* @param queue The RequestQueue to use for making image requests.
* @param imageCache The cache to use as an L1 cache.
*/
public ImageLoader(RequestQueue queue, ImageCache imageCache) {
mRequestQueue = queue;
mCache = imageCache;
}
/**
* The default implementation of ImageListener which handles basic functionality
* of showing a default image until the network response is received, at which point
* it will switch to either the actual image or the error image.
* @param view The imageView that the listener is replacedociated with.
* @param defaultImageResId Default image resource ID to use, or 0 if it doesn't exist.
* @param errorImageResId Error image resource ID to use, or 0 if it doesn't exist.
*/
public static ImageListener getImageListener(final ImageView view, final int defaultImageResId, final int errorImageResId) {
return new ImageListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (errorImageResId != 0) {
view.setImageResource(errorImageResId);
}
}
@Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null) {
view.setImageBitmap(response.getBitmap());
} else if (defaultImageResId != 0) {
view.setImageResource(defaultImageResId);
}
}
};
}
/**
* Interface for the response handlers on image requests.
*
* The call flow is this:
* 1. Upon being attached to a request, onResponse(response, true) will
* be invoked to reflect any cached data that was already available. If the
* data was available, response.getBitmap() will be non-null.
*
* 2. After a network response returns, only one of the following cases will happen:
* - onResponse(response, false) will be called if the image was loaded.
* or
* - onErrorResponse will be called if there was an error loading the image.
*/
public interface ImageListener extends ErrorListener {
/**
* Listens for non-error changes to the loading of the image request.
*
* @param response Holds all information pertaining to the request, as well
* as the bitmap (if it is loaded).
* @param isImmediate True if this was called during ImageLoader.get() variants.
* This can be used to differentiate between a cached image loading and a network
* image loading in order to, for example, run an animation to fade in network loaded
* images.
*/
void onResponse(ImageContainer response, boolean isImmediate);
}
/**
* Checks if the item is available in the cache.
* @param requestUrl The url of the remote image
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @return True if the item exists in cache, false otherwise.
*/
public boolean isCached(String requestUrl, int maxWidth, int maxHeight) {
return isCached(requestUrl, maxWidth, maxHeight, ScaleType.CENTER_INSIDE);
}
/**
* Checks if the item is available in the cache.
*
* @param requestUrl The url of the remote image
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @param scaleType The scaleType of the imageView.
* @return True if the item exists in cache, false otherwise.
*/
public boolean isCached(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType) {
throwIfNotOnMainThread();
String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
return mCache.getBitmap(cacheKey) != null;
}
/**
* Returns an ImageContainer for the requested URL.
*
* The ImageContainer will contain either the specified default bitmap or the loaded bitmap.
* If the default was returned, the {@link ImageLoader} will be invoked when the
* request is fulfilled.
*
* @param requestUrl The URL of the image to be loaded.
*/
public ImageContainer get(String requestUrl, final ImageListener listener) {
return get(requestUrl, listener, 0, 0);
}
/**
* Equivalent to calling {@link #get(String, ImageListener, int, int, ScaleType)} with
* {@code Scaletype == ScaleType.CENTER_INSIDE}.
*/
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight) {
return get(requestUrl, imageListener, maxWidth, maxHeight, ScaleType.CENTER_INSIDE);
}
/**
* Issues a bitmap request with the given URL if that image is not available
* in the cache, and returns a bitmap container that contains all of the data
* relating to the request (as well as the default image if the requested
* image is not available).
* @param requestUrl The url of the remote image
* @param imageListener The listener to call when the remote image is loaded
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @param scaleType The ImageViews ScaleType used to calculate the needed image size.
* @return A container object that contains all of the properties of the request, as well as
* the currently available image (default if remote is not loaded).
*/
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight, ScaleType scaleType) {
// only fulfill requests that were initiated from the main thread.
throwIfNotOnMainThread();
final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
// Try to look up the request in the cache of remote images.
Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
if (cachedBitmap != null) {
// Return the cached bitmap.
ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
imageListener.onResponse(container, true);
return container;
}
// The bitmap did not exist in the cache, fetch it!
ImageContainer imageContainer = new ImageContainer(null, requestUrl, cacheKey, imageListener);
// Update the caller to let them know that they should use the default bitmap.
imageListener.onResponse(imageContainer, true);
// Check to see if a request is already in-flight.
BatchedImageRequest request = mInFlightRequests.get(cacheKey);
if (request != null) {
// If it is, add this request to the list of listeners.
request.addContainer(imageContainer);
return imageContainer;
}
// The request is not already in flight. Send the new request to the network and
// track it.
Request<Bitmap> newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey);
mRequestQueue.add(newRequest);
mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer));
return imageContainer;
}
protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType, final String cacheKey) {
return new ImageRequest(requestUrl, new Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
onGetImageSuccess(cacheKey, response);
}
}, maxWidth, maxHeight, scaleType, Config.RGB_565, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onGetImageError(cacheKey, error);
}
});
}
/**
* Sets the amount of time to wait after the first response arrives before delivering all
* responses. Batching can be disabled entirely by preplaceding in 0.
* @param newBatchedResponseDelayMs The time in milliseconds to wait.
*/
public void setBatchedResponseDelay(int newBatchedResponseDelayMs) {
mBatchResponseDelayMs = newBatchedResponseDelayMs;
}
/**
* Handler for when an image was successfully loaded.
* @param cacheKey The cache key that is replacedociated with the image request.
* @param response The bitmap that was returned from the network.
*/
protected void onGetImageSuccess(String cacheKey, Bitmap response) {
// cache the image that was fetched.
mCache.putBitmap(cacheKey, response);
// remove the request from the list of in-flight requests.
BatchedImageRequest request = mInFlightRequests.remove(cacheKey);
if (request != null) {
// Update the response bitmap.
request.mResponseBitmap = response;
// Send the batched response
batchResponse(cacheKey, request);
}
}
/**
* Handler for when an image failed to load.
* @param cacheKey The cache key that is replacedociated with the image request.
*/
protected void onGetImageError(String cacheKey, VolleyError error) {
// Notify the requesters that something failed via a null result.
// Remove this request from the list of in-flight requests.
BatchedImageRequest request = mInFlightRequests.remove(cacheKey);
if (request != null) {
// Set the error for this request
request.setError(error);
// Send the batched response
batchResponse(cacheKey, request);
}
}
/**
* Container object for all of the data surrounding an image request.
*/
public clreplaced ImageContainer {
/**
* The most relevant bitmap for the container. If the image was in cache, the
* Holder to use for the final bitmap (the one that pairs to the requested URL).
*/
private Bitmap mBitmap;
private final ImageListener mListener;
/**
* The cache key that was replacedociated with the request
*/
private final String mCacheKey;
/**
* The request URL that was specified
*/
private final String mRequestUrl;
/**
* Constructs a BitmapContainer object.
* @param bitmap The final bitmap (if it exists).
* @param requestUrl The requested URL for this container.
* @param cacheKey The cache key that identifies the requested URL for this container.
*/
public ImageContainer(Bitmap bitmap, String requestUrl, String cacheKey, ImageListener listener) {
mBitmap = bitmap;
mRequestUrl = requestUrl;
mCacheKey = cacheKey;
mListener = listener;
}
/**
* Releases interest in the in-flight request (and cancels it if no one else is listening).
*/
public void cancelRequest() {
if (mListener == null) {
return;
}
BatchedImageRequest request = mInFlightRequests.get(mCacheKey);
if (request != null) {
boolean canceled = request.removeContainerAndCancelIfNecessary(this);
if (canceled) {
mInFlightRequests.remove(mCacheKey);
}
} else {
// check to see if it is already batched for delivery.
request = mBatchedResponses.get(mCacheKey);
if (request != null) {
request.removeContainerAndCancelIfNecessary(this);
if (request.mContainers.size() == 0) {
mBatchedResponses.remove(mCacheKey);
}
}
}
}
/**
* Returns the bitmap replacedociated with the request URL if it has been loaded, null otherwise.
*/
public Bitmap getBitmap() {
return mBitmap;
}
/**
* Returns the requested URL for this container.
*/
public String getRequestUrl() {
return mRequestUrl;
}
}
/**
* Wrapper clreplaced used to map a Request to the set of active ImageContainer objects that are
* interested in its results.
*/
private clreplaced BatchedImageRequest {
/**
* The request being tracked
*/
private final Request<?> mRequest;
/**
* The result of the request being tracked by this item
*/
private Bitmap mResponseBitmap;
/**
* Error if one occurred for this response
*/
private VolleyError mError;
/**
* List of all of the active ImageContainers that are interested in the request
*/
private final LinkedList<ImageContainer> mContainers = new LinkedList<ImageContainer>();
/**
* Constructs a new BatchedImageRequest object
* @param request The request being tracked
* @param container The ImageContainer of the person who initiated the request.
*/
public BatchedImageRequest(Request<?> request, ImageContainer container) {
mRequest = request;
mContainers.add(container);
}
/**
* Set the error for this response
*/
public void setError(VolleyError error) {
mError = error;
}
/**
* Get the error for this response
*/
public VolleyError getError() {
return mError;
}
/**
* Adds another ImageContainer to the list of those interested in the results of
* the request.
*/
public void addContainer(ImageContainer container) {
mContainers.add(container);
}
/**
* Detatches the bitmap container from the request and cancels the request if no one is
* left listening.
* @param container The container to remove from the list
* @return True if the request was canceled, false otherwise.
*/
public boolean removeContainerAndCancelIfNecessary(ImageContainer container) {
mContainers.remove(container);
if (mContainers.size() == 0) {
mRequest.cancel();
return true;
}
return false;
}
}
/**
* Starts the runnable for batched delivery of responses if it is not already started.
* @param cacheKey The cacheKey of the response being delivered.
* @param request The BatchedImageRequest to be delivered.
*/
private void batchResponse(String cacheKey, BatchedImageRequest request) {
mBatchedResponses.put(cacheKey, request);
// If we don't already have a batch delivery runnable in flight, make a new one.
// Note that this will be used to deliver responses to all callers in mBatchedResponses.
if (mRunnable == null) {
mRunnable = new Runnable() {
@Override
public void run() {
for (BatchedImageRequest bir : mBatchedResponses.values()) {
for (ImageContainer container : bir.mContainers) {
// If one of the callers in the batched request canceled the request
// after the response was received but before it was delivered,
// skip them.
if (container.mListener == null) {
continue;
}
if (bir.getError() == null) {
container.mBitmap = bir.mResponseBitmap;
container.mListener.onResponse(container, false);
} else {
container.mListener.onErrorResponse(bir.getError());
}
}
}
mBatchedResponses.clear();
mRunnable = null;
}
};
// Post the runnable.
mHandler.postDelayed(mRunnable, mBatchResponseDelayMs);
}
}
private void throwIfNotOnMainThread() {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalStateException("ImageLoader must be invoked from the main thread.");
}
}
/**
* Creates a cache key for use with the L1 cache.
* @param url The URL of the request.
* @param maxWidth The max-width of the output.
* @param maxHeight The max-height of the output.
* @param scaleType The scaleType of the imageView.
*/
private static String getCacheKey(String url, int maxWidth, int maxHeight, ScaleType scaleType) {
return new StringBuilder(url.length() + 12).append("#W").append(maxWidth).append("#H").append(maxHeight).append("#S").append(scaleType.ordinal()).append(url).toString();
}
}
19
Source : SplashActivity.java
with Apache License 2.0
from jiahao42
with Apache License 2.0
from jiahao42
public clreplaced SplashActivity extends Activity {
// 延迟六秒
private final int SPLASH_DISPLAY_LENGHT = 5000;
private ImageView splash_img;
private RequestQueue mQueue;
private final SplashActivity splashActivity = this;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_splash);
splash_img = (ImageView) findViewById(R.id.splash_img);
progressBar = (ProgressBar) findViewById(R.id.progress);
mQueue = Volley.newRequestQueue(splashActivity);
new Handler().postDelayed(new Runnable() {
public void run() {
Intent mainIntent = new Intent(SplashActivity.this, MainActivity.clreplaced);
progressBar.setVisibility(View.INVISIBLE);
SplashActivity.this.startActivity(mainIntent);
SplashActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == Symbol.RECEIVE_SUCCESS) {
Bundle bundle = msg.getData();
String url = bundle.getString("url");
Log.d("----URL----", url);
getPicture(url);
}
}
};
/**
* 请求最新开机图片的Url
*/
new Thread(new Runnable() {
@Override
public void run() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://news-at.zhihu.com/api/4/start-image/1080*1776", null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String imgUrl = response.getString("img");
Message msg = new Message();
msg.what = Symbol.RECEIVE_SUCCESS;
Bundle bundle = new Bundle();
bundle.putString("url", imgUrl);
Log.d("In Thread", imgUrl);
msg.setData(bundle);
handler.sendMessage(msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Fetching url", "Failed");
}
});
mQueue.add(jsonObjectRequest);
mQueue.start();
}
}).start();
}
/**
* 根据得到的Url来请求图片
* @param url url
*/
private void getPicture(final String url) {
new Thread(new Runnable() {
@Override
public void run() {
ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
splash_img.setImageBitmap(response);
}
}, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Fetching img", "Failed");
}
});
mQueue.add(imageRequest);
mQueue.start();
}
}).start();
}
}
19
Source : ApiBll.java
with GNU General Public License v3.0
from itmad
with GNU General Public License v3.0
from itmad
/**
* @ Created by Dlg
* @ <p>replacedle: ApiBll</p>
* @ <p>Description: 和服务端交互的业务类</p>
* @ date: 2018/9/21
* @ QQ群:524901982
*/
public clreplaced ApiBll {
private static ApiBll mApiBll;
private RequestQueue mQueue;
public static ApiBll getInstance() {
if (mApiBll == null) {
mApiBll = new ApiBll();
mApiBll.mQueue = Volley.newRequestQueue(HKApplication.app);
}
return mApiBll;
}
/**
* 检查是否需要发送新二维码
*/
public void checkQR() {
if (!Configer.getInstance().getUrl().toLowerCase().startsWith("http")) {
// 防止首次启动还没有配置,就一直去轮循
return;
}
mQueue.add(new FastJsonRequest(Configer.getInstance().getUrl() + Configer.getInstance().getPage() + "?command=ask", succ, null));
mQueue.start();
}
/**
* 发送服务器所需要的二维码字符串给服务器
* 服务器如果有新订单,就会立马返回新的订单,手机端就不用再等下次轮循了
*
* @param qrBean 要发送的二维码参数
*/
public void sendQR(QrBean qrBean) throws UnsupportedEncodingException {
StringBuilder stringBuilder = new StringBuilder(Configer.getInstance().getUrl()).append(Configer.getInstance().getPage()).append("?command=addqr").append("&url=").append(URLEncoder.encode(qrBean.getUrl(), "utf-8")).append("&mark_sell=").append(URLEncoder.encode(qrBean.getMark_sell(), "utf-8"));
mQueue.add(new FastJsonRequest(stringBuilder.toString(), succ, null));
mQueue.start();
dealTaskList();
LogUtils.show("发送二维码:" + stringBuilder.toString());
}
/**
* 向服务器发送支付成功的消息
* 如果因为一些原因,暂时没有通知成功,会保存任务,下次再尝试
*
* @param qrBean 订单详情信息
*/
public void payQR(final QrBean qrBean) {
StringBuilder url = null;
try {
url = new StringBuilder(Configer.getInstance().getUrl()).append(Configer.getInstance().getPage()).append("?command=do").append("&mark_sell=").append(URLEncoder.encode(qrBean.getMark_sell(), "utf-8")).append("&money=").append(qrBean.getMoney()).append("&order_id=").append(URLEncoder.encode(qrBean.getOrder_id(), "utf-8")).append("&mark_buy=").append(URLEncoder.encode(qrBean.getMark_buy(), "utf-8"));
mQueue.add(new FastJsonRequest(url.toString(), null, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error == null || error.networkResponse == null || error.networkResponse.statusCode < 500) {
// 如果是服务器错误,自己检查代码,不然会一直发送成功订单造成多次支付!
addTaskList(qrBean);
}
}
}));
mQueue.start();
LogUtils.show("发送订单" + url.toString());
} catch (Exception e) {
addTaskList(qrBean);
}
}
/**
* 处理以前没有完成的任务
*/
private void dealTaskList() {
SaveUtils saveUtils = new SaveUtils();
List<QrBean> list = saveUtils.getJsonArray(SaveUtils.TASK_LIST, QrBean.clreplaced);
if (list != null) {
// 先清空任务,如果呆会儿在payQR里又失败的话,会自动又添加的。
saveUtils.putJson(SaveUtils.TASK_LIST, null).commit();
for (QrBean qrBean : list) {
payQR(qrBean);
}
}
}
/**
* 添加未完成的任务列表
* 一定要用static的synchronized方式,上面的dealTaskList在某情况下可能会有问题
* 但个人方案就暂不考虑这么极端的情况了
*
* @param qrBean
*/
private synchronized static void addTaskList(QrBean qrBean) {
SaveUtils saveUtils = new SaveUtils();
List<QrBean> list = saveUtils.getJsonArray(SaveUtils.TASK_LIST, QrBean.clreplaced);
if (list == null) {
list = new ArrayList<>();
}
list.add(qrBean);
saveUtils.putJson(SaveUtils.TASK_LIST, list).commit();
}
/**
* 当询问是否需要生成二维码返回成功后的操作
*/
private final Response.Listener<BaseMsg> succ = new Response.Listener<BaseMsg>() {
@Override
public void onResponse(BaseMsg response) {
if (response == null) {
return;
}
QrBean qrBean = response.getData(QrBean.clreplaced);
if (qrBean != null && qrBean.getMoney() > 0 && !TextUtils.isEmpty(qrBean.getMark_sell())) {
LogUtils.show("服务器需要新二维码:" + qrBean.getMoney() + "|" + qrBean.getMark_sell() + "|" + qrBean.getChannel());
if (qrBean.getChannel().contentEquals(QrBean.WECHAT)) {
HookWechat.getInstance().creatQrTask(qrBean.getMoney(), qrBean.getMark_sell());
} else if (qrBean.getChannel().contentEquals(QrBean.ALIPAY)) {
HookAlipay.getInstance().creatQrTask(qrBean.getMoney(), qrBean.getMark_sell());
}
}
}
};
}
19
Source : MyApplication.java
with Apache License 2.0
from InnoFang
with Apache License 2.0
from InnoFang
/**
* Author: Inno Fang
* Time: 2016/12/23 17:09
* Description:
*/
public clreplaced MyApplication extends Application {
private static final String TAG = "MyApplication";
public static RequestQueue sRequestQueue;
@Override
public void onCreate() {
super.onCreate();
sRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
public static RequestQueue getHttpQueues() {
return sRequestQueue;
}
}
19
Source : MyApplication.java
with MIT License
from huluhive
with MIT License
from huluhive
/**
* Created by Akshay Raj on 7/17/2016.
* Snow Corporation Inc.
* www.bmnepali.org
*/
public clreplaced MyApplication extends Application {
public static final String TAG = MyApplication.clreplaced.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
19
Source : DemoHttpClient.java
with Apache License 2.0
from hsllany
with Apache License 2.0
from hsllany
/**
* @author Yang Tao, 17/5/30.
*/
public clreplaced DemoHttpClient implements HNHttpClient {
private static RequestQueue sQueue = Volley.newRequestQueue(DemoApplication.instance);
@Override
public void send(final HttpRequest request, final RequestCallback callback) {
Request<String> stringRequest = new StringRequest(request.getMethod(), request.getUrl(), new Response.Listener<String>() {
@Override
public void onResponse(String response) {
HttpResponse.Builder builder = new HttpResponse.Builder();
builder.setStatusCode(200);
builder.setBody(response.getBytes());
if (callback != null) {
callback.onResponse(builder.build());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
HttpResponse.Builder builder = new HttpResponse.Builder();
builder.setError(error);
if (callback != null) {
callback.onResponse(builder.build());
}
}
});
sQueue.add(stringRequest);
}
}
19
Source : MainActivity.java
with MIT License
from henrymorgen
with MIT License
from henrymorgen
public clreplaced MainActivity extends AppCompatActivity {
private static final String TAG = "Volley";
private ImageView iv_image;
private Button bt_send;
private NetworkImageView nv_image;
private RequestQueue mQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_image = (ImageView) this.findViewById(R.id.iv_image);
bt_send = (Button) this.findViewById(R.id.bt_send);
nv_image = (NetworkImageView) this.findViewById(R.id.nv_image);
mQueue = Volley.newRequestQueue(getApplicationContext());
bt_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// UseStringRequest();
UseJsonRequest();
// UseImageRequest();
// UseImageLoader();
// UseNetworkImageView();
}
});
}
private void UseStringRequest() {
// 创建请求队列
StringRequest mStringRequest = new StringRequest(Request.Method.GET, "https://www.baidu.com", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
});
// 将请求添加在请求队列中
mQueue.add(mStringRequest);
}
private void UseJsonRequest() {
String requestBody = "ip=59.108.54.37";
JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://ip.taobao.com/service/getIpInfo.php?ip=59.108.54.37", new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
IpModel ipModel = new Gson().fromJson(response.toString(), IpModel.clreplaced);
if (null != ipModel && null != ipModel.getData()) {
String city = ipModel.getData().getCity();
Log.d(TAG, city);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
});
mQueue.add(mJsonObjectRequest);
}
private void UseImageRequest() {
ImageRequest imageRequest = new ImageRequest("http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg", new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
iv_image.setImageBitmap(response);
}
}, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
iv_image.setImageResource(R.drawable.ico_default);
}
});
mQueue.add(imageRequest);
}
private void UseImageLoader() {
ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
ImageLoader.ImageListener listener = ImageLoader.getImageListener(iv_image, R.drawable.ico_default, R.drawable.ico_default);
imageLoader.get("http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg", listener);
}
private void UseNetworkImageView() {
ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
nv_image.setDefaultImageResId(R.drawable.ico_default);
nv_image.setErrorImageResId(R.drawable.ico_default);
nv_image.setImageUrl("http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg", imageLoader);
}
}
19
Source : ImageLoader.java
with Apache License 2.0
from HanyeeWang
with Apache License 2.0
from HanyeeWang
/**
* Helper that handles loading and caching images from remote URLs.
*
* The simple way to use this clreplaced is to call {@link ImageLoader#get(String, ImageListener)}
* and to preplaced in the default image listener provided by
* {@link ImageLoader#getImageListener(ImageView, int, int)}. Note that all function calls to
* this clreplaced must be made from the main thead, and all responses will be delivered to the main
* thread as well.
*/
public clreplaced ImageLoader {
/**
* RequestQueue for dispatching ImageRequests onto.
*/
private final RequestQueue mRequestQueue;
/**
* Amount of time to wait after first response arrives before delivering all responses.
*/
private int mBatchResponseDelayMs = 100;
/**
* The cache implementation to be used as an L1 cache before calling into volley.
*/
private final ImageCache mCache;
/**
* HashMap of Cache keys -> BatchedImageRequest used to track in-flight requests so
* that we can coalesce multiple requests to the same URL into a single network request.
*/
private final HashMap<String, BatchedImageRequest> mInFlightRequests = new HashMap<String, BatchedImageRequest>();
/**
* HashMap of the currently pending responses (waiting to be delivered).
*/
private final HashMap<String, BatchedImageRequest> mBatchedResponses = new HashMap<String, BatchedImageRequest>();
/**
* Handler to the main thread.
*/
private final Handler mHandler = new Handler(Looper.getMainLooper());
/**
* Runnable for in-flight response delivery.
*/
private Runnable mRunnable;
/**
* Simple cache adapter interface. If provided to the ImageLoader, it
* will be used as an L1 cache before dispatch to Volley. Implementations
* must not block. Implementation with an LruCache is recommended.
*/
public interface ImageCache {
public Bitmap getBitmap(String url);
public void putBitmap(String url, Bitmap bitmap);
}
/**
* Constructs a new ImageLoader.
* @param queue The RequestQueue to use for making image requests.
* @param imageCache The cache to use as an L1 cache.
*/
public ImageLoader(RequestQueue queue, ImageCache imageCache) {
mRequestQueue = queue;
mCache = imageCache;
}
/**
* The default implementation of ImageListener which handles basic functionality
* of showing a default image until the network response is received, at which point
* it will switch to either the actual image or the error image.
* @param view The imageView that the listener is replacedociated with.
* @param defaultImageResId Default image resource ID to use, or 0 if it doesn't exist.
* @param errorImageResId Error image resource ID to use, or 0 if it doesn't exist.
*/
public static ImageListener getImageListener(final ImageView view, final int defaultImageResId, final int errorImageResId) {
return new ImageListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (errorImageResId != 0) {
view.setImageResource(errorImageResId);
}
}
@Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null) {
view.setImageBitmap(response.getBitmap());
} else if (defaultImageResId != 0) {
view.setImageResource(defaultImageResId);
}
}
};
}
/**
* Interface for the response handlers on image requests.
*
* The call flow is this:
* 1. Upon being attached to a request, onResponse(response, true) will
* be invoked to reflect any cached data that was already available. If the
* data was available, response.getBitmap() will be non-null.
*
* 2. After a network response returns, only one of the following cases will happen:
* - onResponse(response, false) will be called if the image was loaded.
* or
* - onErrorResponse will be called if there was an error loading the image.
*/
public interface ImageListener extends ErrorListener {
/**
* Listens for non-error changes to the loading of the image request.
*
* @param response Holds all information pertaining to the request, as well
* as the bitmap (if it is loaded).
* @param isImmediate True if this was called during ImageLoader.get() variants.
* This can be used to differentiate between a cached image loading and a network
* image loading in order to, for example, run an animation to fade in network loaded
* images.
*/
public void onResponse(ImageContainer response, boolean isImmediate);
}
/**
* Checks if the item is available in the cache.
* @param requestUrl The url of the remote image
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @return True if the item exists in cache, false otherwise.
*/
public boolean isCached(String requestUrl, int maxWidth, int maxHeight) {
return isCached(requestUrl, maxWidth, maxHeight, ScaleType.CENTER_INSIDE);
}
/**
* Checks if the item is available in the cache.
*
* @param requestUrl The url of the remote image
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @param scaleType The scaleType of the imageView.
* @return True if the item exists in cache, false otherwise.
*/
public boolean isCached(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType) {
throwIfNotOnMainThread();
String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
return mCache.getBitmap(cacheKey) != null;
}
/**
* Returns an ImageContainer for the requested URL.
*
* The ImageContainer will contain either the specified default bitmap or the loaded bitmap.
* If the default was returned, the {@link ImageLoader} will be invoked when the
* request is fulfilled.
*
* @param requestUrl The URL of the image to be loaded.
*/
public ImageContainer get(String requestUrl, final ImageListener listener) {
return get(requestUrl, listener, 0, 0);
}
/**
* Equivalent to calling {@link #get(String, ImageListener, int, int, ScaleType)} with
* {@code Scaletype == ScaleType.CENTER_INSIDE}.
*/
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight) {
return get(requestUrl, imageListener, maxWidth, maxHeight, ScaleType.CENTER_INSIDE);
}
/**
* Issues a bitmap request with the given URL if that image is not available
* in the cache, and returns a bitmap container that contains all of the data
* relating to the request (as well as the default image if the requested
* image is not available).
* @param requestUrl The url of the remote image
* @param imageListener The listener to call when the remote image is loaded
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @param scaleType The ImageViews ScaleType used to calculate the needed image size.
* @return A container object that contains all of the properties of the request, as well as
* the currently available image (default if remote is not loaded).
*/
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight, ScaleType scaleType) {
// only fulfill requests that were initiated from the main thread.
throwIfNotOnMainThread();
final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
// Try to look up the request in the cache of remote images.
Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
if (cachedBitmap != null) {
// Return the cached bitmap.
ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
imageListener.onResponse(container, true);
return container;
}
// The bitmap did not exist in the cache, fetch it!
ImageContainer imageContainer = new ImageContainer(null, requestUrl, cacheKey, imageListener);
// Update the caller to let them know that they should use the default bitmap.
imageListener.onResponse(imageContainer, true);
// Check to see if a request is already in-flight.
BatchedImageRequest request = mInFlightRequests.get(cacheKey);
if (request != null) {
// If it is, add this request to the list of listeners.
request.addContainer(imageContainer);
return imageContainer;
}
// The request is not already in flight. Send the new request to the network and
// track it.
Request<Bitmap> newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey);
mRequestQueue.add(newRequest);
mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer));
return imageContainer;
}
protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType, final String cacheKey) {
return new ImageRequest(requestUrl, new Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
onGetImageSuccess(cacheKey, response);
}
}, maxWidth, maxHeight, scaleType, Config.RGB_565, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onGetImageError(cacheKey, error);
}
});
}
/**
* Sets the amount of time to wait after the first response arrives before delivering all
* responses. Batching can be disabled entirely by preplaceding in 0.
* @param newBatchedResponseDelayMs The time in milliseconds to wait.
*/
public void setBatchedResponseDelay(int newBatchedResponseDelayMs) {
mBatchResponseDelayMs = newBatchedResponseDelayMs;
}
/**
* Handler for when an image was successfully loaded.
* @param cacheKey The cache key that is replacedociated with the image request.
* @param response The bitmap that was returned from the network.
*/
protected void onGetImageSuccess(String cacheKey, Bitmap response) {
// cache the image that was fetched.
mCache.putBitmap(cacheKey, response);
// remove the request from the list of in-flight requests.
BatchedImageRequest request = mInFlightRequests.remove(cacheKey);
if (request != null) {
// Update the response bitmap.
request.mResponseBitmap = response;
// Send the batched response
batchResponse(cacheKey, request);
}
}
/**
* Handler for when an image failed to load.
* @param cacheKey The cache key that is replacedociated with the image request.
*/
protected void onGetImageError(String cacheKey, VolleyError error) {
// Notify the requesters that something failed via a null result.
// Remove this request from the list of in-flight requests.
BatchedImageRequest request = mInFlightRequests.remove(cacheKey);
if (request != null) {
// Set the error for this request
request.setError(error);
// Send the batched response
batchResponse(cacheKey, request);
}
}
/**
* Container object for all of the data surrounding an image request.
*/
public clreplaced ImageContainer {
/**
* The most relevant bitmap for the container. If the image was in cache, the
* Holder to use for the final bitmap (the one that pairs to the requested URL).
*/
private Bitmap mBitmap;
private final ImageListener mListener;
/**
* The cache key that was replacedociated with the request
*/
private final String mCacheKey;
/**
* The request URL that was specified
*/
private final String mRequestUrl;
/**
* Constructs a BitmapContainer object.
* @param bitmap The final bitmap (if it exists).
* @param requestUrl The requested URL for this container.
* @param cacheKey The cache key that identifies the requested URL for this container.
*/
public ImageContainer(Bitmap bitmap, String requestUrl, String cacheKey, ImageListener listener) {
mBitmap = bitmap;
mRequestUrl = requestUrl;
mCacheKey = cacheKey;
mListener = listener;
}
/**
* Releases interest in the in-flight request (and cancels it if no one else is listening).
*/
public void cancelRequest() {
if (mListener == null) {
return;
}
BatchedImageRequest request = mInFlightRequests.get(mCacheKey);
if (request != null) {
boolean canceled = request.removeContainerAndCancelIfNecessary(this);
if (canceled) {
mInFlightRequests.remove(mCacheKey);
}
} else {
// check to see if it is already batched for delivery.
request = mBatchedResponses.get(mCacheKey);
if (request != null) {
request.removeContainerAndCancelIfNecessary(this);
if (request.mContainers.size() == 0) {
mBatchedResponses.remove(mCacheKey);
}
}
}
}
/**
* Returns the bitmap replacedociated with the request URL if it has been loaded, null otherwise.
*/
public Bitmap getBitmap() {
return mBitmap;
}
/**
* Returns the requested URL for this container.
*/
public String getRequestUrl() {
return mRequestUrl;
}
}
/**
* Wrapper clreplaced used to map a Request to the set of active ImageContainer objects that are
* interested in its results.
*/
private clreplaced BatchedImageRequest {
/**
* The request being tracked
*/
private final Request<?> mRequest;
/**
* The result of the request being tracked by this item
*/
private Bitmap mResponseBitmap;
/**
* Error if one occurred for this response
*/
private VolleyError mError;
/**
* List of all of the active ImageContainers that are interested in the request
*/
private final LinkedList<ImageContainer> mContainers = new LinkedList<ImageContainer>();
/**
* Constructs a new BatchedImageRequest object
* @param request The request being tracked
* @param container The ImageContainer of the person who initiated the request.
*/
public BatchedImageRequest(Request<?> request, ImageContainer container) {
mRequest = request;
mContainers.add(container);
}
/**
* Set the error for this response
*/
public void setError(VolleyError error) {
mError = error;
}
/**
* Get the error for this response
*/
public VolleyError getError() {
return mError;
}
/**
* Adds another ImageContainer to the list of those interested in the results of
* the request.
*/
public void addContainer(ImageContainer container) {
mContainers.add(container);
}
/**
* Detatches the bitmap container from the request and cancels the request if no one is
* left listening.
* @param container The container to remove from the list
* @return True if the request was canceled, false otherwise.
*/
public boolean removeContainerAndCancelIfNecessary(ImageContainer container) {
mContainers.remove(container);
if (mContainers.size() == 0) {
mRequest.cancel();
return true;
}
return false;
}
}
/**
* Starts the runnable for batched delivery of responses if it is not already started.
* @param cacheKey The cacheKey of the response being delivered.
* @param request The BatchedImageRequest to be delivered.
*/
private void batchResponse(String cacheKey, BatchedImageRequest request) {
mBatchedResponses.put(cacheKey, request);
// If we don't already have a batch delivery runnable in flight, make a new one.
// Note that this will be used to deliver responses to all callers in mBatchedResponses.
if (mRunnable == null) {
mRunnable = new Runnable() {
@Override
public void run() {
for (BatchedImageRequest bir : mBatchedResponses.values()) {
for (ImageContainer container : bir.mContainers) {
// If one of the callers in the batched request canceled the request
// after the response was received but before it was delivered,
// skip them.
if (container.mListener == null) {
continue;
}
if (bir.getError() == null) {
container.mBitmap = bir.mResponseBitmap;
container.mListener.onResponse(container, false);
} else {
container.mListener.onErrorResponse(bir.getError());
}
}
}
mBatchedResponses.clear();
mRunnable = null;
}
};
// Post the runnable.
mHandler.postDelayed(mRunnable, mBatchResponseDelayMs);
}
}
private void throwIfNotOnMainThread() {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalStateException("ImageLoader must be invoked from the main thread.");
}
}
/**
* Creates a cache key for use with the L1 cache.
* @param url The URL of the request.
* @param maxWidth The max-width of the output.
* @param maxHeight The max-height of the output.
* @param scaleType The scaleType of the imageView.
*/
private static String getCacheKey(String url, int maxWidth, int maxHeight, ScaleType scaleType) {
return new StringBuilder(url.length() + 12).append("#W").append(maxWidth).append("#H").append(maxHeight).append("#S").append(scaleType.ordinal()).append(url).toString();
}
}
19
Source : RemoteDataSource.java
with Apache License 2.0
from googlecodelabs
with Apache License 2.0
from googlecodelabs
/**
* Makes a request to the json endpoint and parses the result as a {@link PostList} object.
*/
public clreplaced RemoteDataSource implements DataSource {
private final String mUrl;
private final RequestQueue mRequestQueue;
public RemoteDataSource(String url) {
mUrl = url;
mRequestQueue = new RequestQueue(new NoCache(), new BasicNetwork(new HurlStack()));
mRequestQueue.start();
}
@Override
public void getPosts(@NonNull final GetPostsCallback getPostsCallback) {
GsonRequest<PostList> gsonRequest = new GsonRequest<>(mUrl, PostList.clreplaced, null, new Response.Listener<PostList>() {
@Override
public void onResponse(PostList list) {
getPostsCallback.onPostsLoaded(list.posts);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
getPostsCallback.onPostsNotAvailable(volleyError.getMessage(), volleyError.getCause());
// + "\n" + volleyError.toString()
}
});
mRequestQueue.add(gsonRequest);
}
@Override
public void getPostImage(@NonNull String url, @NonNull GetImageCallback getImageCallback) {
}
}
19
Source : ImageLoader.java
with Apache License 2.0
from google
with Apache License 2.0
from google
/**
* Helper that handles loading and caching images from remote URLs.
*
* <p>The simple way to use this clreplaced is to call {@link ImageLoader#get(String, ImageListener)} and
* to preplaced in the default image listener provided by {@link ImageLoader#getImageListener(ImageView,
* int, int)}. Note that all function calls to this clreplaced must be made from the main thread, and all
* responses will be delivered to the main thread as well. Custom {@link ResponseDelivery}s which
* don't use the main thread are not supported.
*/
public clreplaced ImageLoader {
/**
* RequestQueue for dispatching ImageRequests onto.
*/
private final RequestQueue mRequestQueue;
/**
* Amount of time to wait after first response arrives before delivering all responses.
*/
private int mBatchResponseDelayMs = 100;
/**
* The cache implementation to be used as an L1 cache before calling into volley.
*/
private final ImageCache mCache;
/**
* HashMap of Cache keys -> BatchedImageRequest used to track in-flight requests so that we can
* coalesce multiple requests to the same URL into a single network request.
*/
private final HashMap<String, BatchedImageRequest> mInFlightRequests = new HashMap<>();
/**
* HashMap of the currently pending responses (waiting to be delivered).
*/
private final HashMap<String, BatchedImageRequest> mBatchedResponses = new HashMap<>();
/**
* Handler to the main thread.
*/
private final Handler mHandler = new Handler(Looper.getMainLooper());
/**
* Runnable for in-flight response delivery.
*/
private Runnable mRunnable;
/**
* Simple cache adapter interface. If provided to the ImageLoader, it will be used as an L1
* cache before dispatch to Volley. Implementations must not block. Implementation with an
* LruCache is recommended.
*/
public interface ImageCache {
@Nullable
Bitmap getBitmap(String url);
void putBitmap(String url, Bitmap bitmap);
}
/**
* Constructs a new ImageLoader.
*
* @param queue The RequestQueue to use for making image requests.
* @param imageCache The cache to use as an L1 cache.
*/
public ImageLoader(RequestQueue queue, ImageCache imageCache) {
mRequestQueue = queue;
mCache = imageCache;
}
/**
* The default implementation of ImageListener which handles basic functionality of showing a
* default image until the network response is received, at which point it will switch to either
* the actual image or the error image.
*
* @param view The imageView that the listener is replacedociated with.
* @param defaultImageResId Default image resource ID to use, or 0 if it doesn't exist.
* @param errorImageResId Error image resource ID to use, or 0 if it doesn't exist.
*/
public static ImageListener getImageListener(final ImageView view, final int defaultImageResId, final int errorImageResId) {
return new ImageListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (errorImageResId != 0) {
view.setImageResource(errorImageResId);
}
}
@Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null) {
view.setImageBitmap(response.getBitmap());
} else if (defaultImageResId != 0) {
view.setImageResource(defaultImageResId);
}
}
};
}
/**
* Interface for the response handlers on image requests.
*
* <p>The call flow is this: 1. Upon being attached to a request, onResponse(response, true)
* will be invoked to reflect any cached data that was already available. If the data was
* available, response.getBitmap() will be non-null.
*
* <p>2. After a network response returns, only one of the following cases will happen: -
* onResponse(response, false) will be called if the image was loaded. or - onErrorResponse will
* be called if there was an error loading the image.
*/
public interface ImageListener extends ErrorListener {
/**
* Listens for non-error changes to the loading of the image request.
*
* @param response Holds all information pertaining to the request, as well as the bitmap
* (if it is loaded).
* @param isImmediate True if this was called during ImageLoader.get() variants. This can be
* used to differentiate between a cached image loading and a network image loading in
* order to, for example, run an animation to fade in network loaded images.
*/
void onResponse(ImageContainer response, boolean isImmediate);
}
/**
* Checks if the item is available in the cache.
*
* @param requestUrl The url of the remote image
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @return True if the item exists in cache, false otherwise.
*/
public boolean isCached(String requestUrl, int maxWidth, int maxHeight) {
return isCached(requestUrl, maxWidth, maxHeight, ScaleType.CENTER_INSIDE);
}
/**
* Checks if the item is available in the cache.
*
* <p>Must be called from the main thread.
*
* @param requestUrl The url of the remote image
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @param scaleType The scaleType of the imageView.
* @return True if the item exists in cache, false otherwise.
*/
@MainThread
public boolean isCached(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType) {
Threads.throwIfNotOnMainThread();
String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
return mCache.getBitmap(cacheKey) != null;
}
/**
* Returns an ImageContainer for the requested URL.
*
* <p>The ImageContainer will contain either the specified default bitmap or the loaded bitmap.
* If the default was returned, the {@link ImageLoader} will be invoked when the request is
* fulfilled.
*
* @param requestUrl The URL of the image to be loaded.
*/
public ImageContainer get(String requestUrl, final ImageListener listener) {
return get(requestUrl, listener, /* maxWidth= */
0, /* maxHeight= */
0);
}
/**
* Equivalent to calling {@link #get(String, ImageListener, int, int, ScaleType)} with {@code
* Scaletype == ScaleType.CENTER_INSIDE}.
*/
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight) {
return get(requestUrl, imageListener, maxWidth, maxHeight, ScaleType.CENTER_INSIDE);
}
/**
* Issues a bitmap request with the given URL if that image is not available in the cache, and
* returns a bitmap container that contains all of the data relating to the request (as well as
* the default image if the requested image is not available).
*
* <p>Must be called from the main thread.
*
* @param requestUrl The url of the remote image
* @param imageListener The listener to call when the remote image is loaded
* @param maxWidth The maximum width of the returned image.
* @param maxHeight The maximum height of the returned image.
* @param scaleType The ImageViews ScaleType used to calculate the needed image size.
* @return A container object that contains all of the properties of the request, as well as the
* currently available image (default if remote is not loaded).
*/
@MainThread
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight, ScaleType scaleType) {
// only fulfill requests that were initiated from the main thread.
Threads.throwIfNotOnMainThread();
final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
// Try to look up the request in the cache of remote images.
Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
if (cachedBitmap != null) {
// Return the cached bitmap.
ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, /* cacheKey= */
null, /* listener= */
null);
imageListener.onResponse(container, true);
return container;
}
// The bitmap did not exist in the cache, fetch it!
ImageContainer imageContainer = new ImageContainer(null, requestUrl, cacheKey, imageListener);
// Update the caller to let them know that they should use the default bitmap.
imageListener.onResponse(imageContainer, true);
// Check to see if a request is already in-flight or completed but pending batch delivery.
BatchedImageRequest request = mInFlightRequests.get(cacheKey);
if (request == null) {
request = mBatchedResponses.get(cacheKey);
}
if (request != null) {
// If it is, add this request to the list of listeners.
request.addContainer(imageContainer);
return imageContainer;
}
// The request is not already in flight. Send the new request to the network and
// track it.
Request<Bitmap> newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey);
mRequestQueue.add(newRequest);
mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer));
return imageContainer;
}
protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType, final String cacheKey) {
return new ImageRequest(requestUrl, new Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
onGetImageSuccess(cacheKey, response);
}
}, maxWidth, maxHeight, scaleType, Config.RGB_565, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onGetImageError(cacheKey, error);
}
});
}
/**
* Sets the amount of time to wait after the first response arrives before delivering all
* responses. Batching can be disabled entirely by preplaceding in 0.
*
* @param newBatchedResponseDelayMs The time in milliseconds to wait.
*/
public void setBatchedResponseDelay(int newBatchedResponseDelayMs) {
mBatchResponseDelayMs = newBatchedResponseDelayMs;
}
/**
* Handler for when an image was successfully loaded.
*
* @param cacheKey The cache key that is replacedociated with the image request.
* @param response The bitmap that was returned from the network.
*/
protected void onGetImageSuccess(String cacheKey, Bitmap response) {
// cache the image that was fetched.
mCache.putBitmap(cacheKey, response);
// remove the request from the list of in-flight requests.
BatchedImageRequest request = mInFlightRequests.remove(cacheKey);
if (request != null) {
// Update the response bitmap.
request.mResponseBitmap = response;
// Send the batched response
batchResponse(cacheKey, request);
}
}
/**
* Handler for when an image failed to load.
*
* @param cacheKey The cache key that is replacedociated with the image request.
*/
protected void onGetImageError(String cacheKey, VolleyError error) {
// Notify the requesters that something failed via a null result.
// Remove this request from the list of in-flight requests.
BatchedImageRequest request = mInFlightRequests.remove(cacheKey);
if (request != null) {
// Set the error for this request
request.setError(error);
// Send the batched response
batchResponse(cacheKey, request);
}
}
/**
* Container object for all of the data surrounding an image request.
*/
public clreplaced ImageContainer {
/**
* The most relevant bitmap for the container. If the image was in cache, the Holder to use
* for the final bitmap (the one that pairs to the requested URL).
*/
private Bitmap mBitmap;
private final ImageListener mListener;
/**
* The cache key that was replacedociated with the request
*/
private final String mCacheKey;
/**
* The request URL that was specified
*/
private final String mRequestUrl;
/**
* Constructs a BitmapContainer object.
*
* @param bitmap The final bitmap (if it exists).
* @param requestUrl The requested URL for this container.
* @param cacheKey The cache key that identifies the requested URL for this container.
*/
public ImageContainer(Bitmap bitmap, String requestUrl, String cacheKey, ImageListener listener) {
mBitmap = bitmap;
mRequestUrl = requestUrl;
mCacheKey = cacheKey;
mListener = listener;
}
/**
* Releases interest in the in-flight request (and cancels it if no one else is listening).
*
* <p>Must be called from the main thread.
*/
@MainThread
public void cancelRequest() {
Threads.throwIfNotOnMainThread();
if (mListener == null) {
return;
}
BatchedImageRequest request = mInFlightRequests.get(mCacheKey);
if (request != null) {
boolean canceled = request.removeContainerAndCancelIfNecessary(this);
if (canceled) {
mInFlightRequests.remove(mCacheKey);
}
} else {
// check to see if it is already batched for delivery.
request = mBatchedResponses.get(mCacheKey);
if (request != null) {
request.removeContainerAndCancelIfNecessary(this);
if (request.mContainers.size() == 0) {
mBatchedResponses.remove(mCacheKey);
}
}
}
}
/**
* Returns the bitmap replacedociated with the request URL if it has been loaded, null otherwise.
*/
public Bitmap getBitmap() {
return mBitmap;
}
/**
* Returns the requested URL for this container.
*/
public String getRequestUrl() {
return mRequestUrl;
}
}
/**
* Wrapper clreplaced used to map a Request to the set of active ImageContainer objects that are
* interested in its results.
*/
private static clreplaced BatchedImageRequest {
/**
* The request being tracked
*/
private final Request<?> mRequest;
/**
* The result of the request being tracked by this item
*/
private Bitmap mResponseBitmap;
/**
* Error if one occurred for this response
*/
private VolleyError mError;
/**
* List of all of the active ImageContainers that are interested in the request
*/
private final List<ImageContainer> mContainers = new ArrayList<>();
/**
* Constructs a new BatchedImageRequest object
*
* @param request The request being tracked
* @param container The ImageContainer of the person who initiated the request.
*/
public BatchedImageRequest(Request<?> request, ImageContainer container) {
mRequest = request;
mContainers.add(container);
}
/**
* Set the error for this response
*/
public void setError(VolleyError error) {
mError = error;
}
/**
* Get the error for this response
*/
public VolleyError getError() {
return mError;
}
/**
* Adds another ImageContainer to the list of those interested in the results of the
* request.
*/
public void addContainer(ImageContainer container) {
mContainers.add(container);
}
/**
* Detaches the bitmap container from the request and cancels the request if no one is left
* listening.
*
* @param container The container to remove from the list
* @return True if the request was canceled, false otherwise.
*/
public boolean removeContainerAndCancelIfNecessary(ImageContainer container) {
mContainers.remove(container);
if (mContainers.size() == 0) {
mRequest.cancel();
return true;
}
return false;
}
}
/**
* Starts the runnable for batched delivery of responses if it is not already started.
*
* @param cacheKey The cacheKey of the response being delivered.
* @param request The BatchedImageRequest to be delivered.
*/
private void batchResponse(String cacheKey, BatchedImageRequest request) {
mBatchedResponses.put(cacheKey, request);
// If we don't already have a batch delivery runnable in flight, make a new one.
// Note that this will be used to deliver responses to all callers in mBatchedResponses.
if (mRunnable == null) {
mRunnable = new Runnable() {
@Override
public void run() {
for (BatchedImageRequest bir : mBatchedResponses.values()) {
for (ImageContainer container : bir.mContainers) {
// If one of the callers in the batched request canceled the
// request
// after the response was received but before it was delivered,
// skip them.
if (container.mListener == null) {
continue;
}
if (bir.getError() == null) {
container.mBitmap = bir.mResponseBitmap;
container.mListener.onResponse(container, false);
} else {
container.mListener.onErrorResponse(bir.getError());
}
}
}
mBatchedResponses.clear();
mRunnable = null;
}
};
// Post the runnable.
mHandler.postDelayed(mRunnable, mBatchResponseDelayMs);
}
}
/**
* Creates a cache key for use with the L1 cache.
*
* @param url The URL of the request.
* @param maxWidth The max-width of the output.
* @param maxHeight The max-height of the output.
* @param scaleType The scaleType of the imageView.
*/
private static String getCacheKey(String url, int maxWidth, int maxHeight, ScaleType scaleType) {
return new StringBuilder(url.length() + 12).append("#W").append(maxWidth).append("#H").append(maxHeight).append("#S").append(scaleType.ordinal()).append(url).toString();
}
}
19
Source : RequestQueueWrapper.java
with Apache License 2.0
from google
with Apache License 2.0
from google
public static RequestQueueWrapper wrapping(RequestQueue innerQueue) {
return new RequestQueueWrapper() {
@Override
public <T> Request<T> add(Request<T> request) {
return innerQueue.add(request);
}
};
}
19
Source : SearchEngine.java
with Apache License 2.0
from FirebaseExtended
with Apache License 2.0
from FirebaseExtended
/**
* A fake search engine to help simulate the complete work flow.
*/
public clreplaced SearchEngine {
private static final String TAG = "SearchEngine";
public interface SearchResultListener {
void onSearchCompleted(DetectedObject object, List<Product> productList);
}
private final RequestQueue searchRequestQueue;
private final ExecutorService requestCreationExecutor;
public SearchEngine(Context context) {
searchRequestQueue = Volley.newRequestQueue(context);
requestCreationExecutor = Executors.newSingleThreadExecutor();
}
public void search(DetectedObject object, SearchResultListener listener) {
// Crops the object image out of the full image is expensive, so do it off the UI thread.
Tasks.call(requestCreationExecutor, () -> createRequest(object)).addOnSuccessListener(productRequest -> searchRequestQueue.add(productRequest.setTag(TAG))).addOnFailureListener(e -> {
Log.e(TAG, "Failed to create product search request!", e);
// Remove the below dummy code after your own product search backed hooked up.
List<Product> productList = new ArrayList<>();
for (int i = 0; i < 8; i++) {
productList.add(new Product(/* imageUrl= */
"", "Product replacedle " + i, "Product subreplacedle " + i));
}
listener.onSearchCompleted(object, productList);
});
}
private static JsonObjectRequest createRequest(DetectedObject searchingObject) throws Exception {
byte[] objectImageData = searchingObject.getImageData();
if (objectImageData == null) {
throw new Exception("Failed to get object image data!");
}
// Hooks up with your own product search backend here.
throw new Exception("Hooks up with your own product search backend.");
}
public void shutdown() {
searchRequestQueue.cancelAll(TAG);
requestCreationExecutor.shutdown();
}
}
19
Source : UpdateChecker.java
with Mozilla Public License 2.0
from feifadaima
with Mozilla Public License 2.0
from feifadaima
/**
* Created by Stardust on 2017/4/9.
*/
public clreplaced UpdateChecker implements Response.Listener<String>, Response.ErrorListener {
private static final String LOG_TAG = UpdateChecker.clreplaced.getName();
private RequestQueue mRequestQueue;
private static final String UPDATE_URL = "https://raw.githubusercontent.com/hyb1996/NoRootScriptDroid/master/version.json";
public interface Callback {
void onSuccess(UpdateInfo result);
void onError(Exception exception);
}
public static UpdateInfo savedResult;
private final int mTimeOut = 3000;
private Callback mCallback;
public UpdateChecker(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
}
private UpdateInfo parse(String json) {
Gson gson = new Gson();
Type type = new TypeToken<UpdateInfo>() {
}.getType();
UpdateInfo result = gson.fromJson(json, type);
Log.i(LOG_TAG, result.toString());
return result;
}
public void check(final Callback callback) {
mCallback = callback;
StringRequest request = new StringRequest(Request.Method.GET, UPDATE_URL, this, this);
request.setRetryPolicy(new DefaultRetryPolicy(mTimeOut, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.setTag("update-check");
request.setShouldCache(false);
mRequestQueue.add(request);
}
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
mCallback.onError(error);
mCallback = null;
}
@Override
public void onResponse(String response) {
try {
UpdateInfo result = parse(response);
savedResult = result;
if (mCallback == null)
return;
if (result.isValid()) {
mCallback.onSuccess(result);
} else {
mCallback.onError(new UpdateDataInvalidException());
}
} catch (Exception e) {
e.printStackTrace();
mCallback.onError(e);
}
mCallback = null;
}
public void cancel() {
mRequestQueue.cancelAll("update-check");
}
public static clreplaced UpdateInfo extends JSONObject {
public int versionCode;
public String releaseNotes;
public String versionName;
public List<Download> downloads;
public List<OldVersion> oldVersions;
public int deprecated;
public String downloadUrl;
public boolean isValid() {
return downloads != null && !downloads.isEmpty() && versionCode > 0 && !TextUtils.isEmpty(versionName) && !TextUtils.isEmpty(releaseNotes);
}
public OldVersion getOldVersion(int versionCode) {
for (OldVersion oldVersion : oldVersions) {
if (oldVersion.versionCode == versionCode) {
return oldVersion;
}
}
return null;
}
@Override
public String toString() {
return "UpdateInfo{" + "versionCode=" + versionCode + ", releaseNotes='" + releaseNotes + '\'' + ", versionName='" + versionName + '\'' + ", downloads=" + downloads + ", oldVersions=" + oldVersions + ", deprecated=" + deprecated + ", downloadUrl='" + downloadUrl + '\'' + '}';
}
}
public static clreplaced OldVersion extends JSONObject {
public int versionCode;
public String issues;
@Override
public String toString() {
return "OldVersion{" + "versionCode=" + versionCode + ", issues='" + issues + '\'' + '}';
}
}
public static clreplaced Download extends JSONObject {
public String name;
public String url;
@Override
public String toString() {
return "Download{" + "name='" + name + '\'' + ", url='" + url + '\'' + '}';
}
}
public static clreplaced UpdateDataInvalidException extends RuntimeException {
}
}
19
Source : AppController.java
with MIT License
from DevipriyaSarkar
with MIT License
from DevipriyaSarkar
public clreplaced AppController extends Application {
private static final String TAG = AppController.clreplaced.getSimpleName();
public static final String START_PHONE_VERIFICATION_URL = "https://api.authy.com/protected/json/phones/verification/start";
public static final String VERIFY_CODE_URL = "https://api.authy.com/protected/json/phones/verification/check";
public static final String TWILIO_API_KEY = "<YOUR_TWILIO_API_KEY>";
public static final String GOOGLE_MAPS_DISTANCE_MATRIX_API_KEY = "<YOUR_DISTANCE_MATRIX_API_KEY>";
public static final int SOCKET_TIMEOUT_MS = 5000;
private RequestQueue mRequestQueue;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
19
Source : AppController.java
with BSD 2-Clause "Simplified" License
from Denny966
with BSD 2-Clause "Simplified" License
from Denny966
public clreplaced AppController extends Application {
public static final String TAG = "OLD SCHOOL COMPANION";
private RequestQueue mRequestQueue;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
FloatingViewService.init(this);
new UpdateDbTask(this).execute();
createNotificationChannel();
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
req.setRetryPolicy(new DefaultRetryPolicy(5000, 2, 2));
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.app_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(BuildConfig.APPLICATION_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.clreplaced);
notificationManager.createNotificationChannel(channel);
}
}
}
19
Source : RestHelper.java
with Apache License 2.0
from dbbahnhoflive
with Apache License 2.0
from dbbahnhoflive
public clreplaced RestHelper {
@NonNull
private final RequestQueue queue;
public RestHelper(@NonNull RequestQueue queue) {
this.queue = queue;
}
public <T> Request<T> add(Request<T> request) {
return queue.add(request);
}
}
19
Source : NetworkConstant.java
with MIT License
from covidsafe
with MIT License
from covidsafe
public clreplaced NetworkConstant {
public static String BASE_URL = "https://csapi.azurefd.net/api/";
public static String API_VERSION = "2020-04-15";
public static int TIMEOUT = 10;
static RequestQueue requestQueue;
static Gson gson;
public static void init(Activity av) {
gson = new Gson();
// Instantiate the cache
// 1MB cap
Cache cache = new DiskBasedCache(av.getCacheDir(), 1024 * 1024);
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
requestQueue = new RequestQueue(cache, network);
// Start the queue
requestQueue.start();
}
}
19
Source : MainActivity.java
with GNU General Public License v3.0
from codex-iter
with GNU General Public License v3.0
from codex-iter
private void getName(final String... param) {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest(Request.Method.POST, param[0] + "/studentinfo", response -> {
try {
if (response.equals("404")) {
processLoginViewsStatus();
resetUserPreplacedViews();
Snackbar snackbar = Snackbar.make(activityMainBinding.mainLayout, "Wrong Credentials", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
JSONObject jobj = new JSONObject(response);
JSONArray jarr = jobj.getJSONArray("detail");
JSONObject jobj1 = jarr.getJSONObject(0);
if (!jobj1.has("name") || !jobj1.has(STUDENT_BRANCH)) {
throw new InvalidResponseFetchNameException();
}
if (jobj1.has("academicyear")) {
if (!jobj1.getString("academicyear").isEmpty()) {
academic_year = jobj1.getString("academicyear");
}
}
String studentName = jobj1.getString("name");
String student_branch = jobj1.getString(STUDENT_BRANCH);
MainActivity.this.getAttendanceAPI(this.sharedPreferences.getString(API, api), param[1], param[2], academic_year, studentName, student_branch);
}
} catch (JSONException | InvalidResponseFetchNameException e) {
processLoginViewsStatus();
resetUserPreplacedViews();
Snackbar snackbar = Snackbar.make(activityMainBinding.mainLayout, "Invalid API Response", Snackbar.LENGTH_SHORT);
snackbar.show();
} catch (Exception e) {
processLoginViewsStatus();
resetUserPreplacedViews();
Snackbar snackbar = Snackbar.make(activityMainBinding.mainLayout, "Something went wrong few things may not work properly", Snackbar.LENGTH_SHORT);
snackbar.show();
}
}, error -> {
processLoginViewsStatus();
if (error instanceof AuthFailureError) {
resetUserPreplacedViews();
Snackbar snackbar = Snackbar.make(activityMainBinding.mainLayout, "Wrong Credentials!", Snackbar.LENGTH_SHORT);
snackbar.show();
} else if (error instanceof ServerError) {
if (preferredStudent == null) {
resetUserPreplacedViews();
Snackbar snackbar = Snackbar.make(activityMainBinding.mainLayout, "Cannot connect to ITER servers right now.", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
MainActivity.this.getAttendanceAPI(this.sharedPreferences.getString(API, api), param[1], param[2], preferredStudent.getAcademic_year(), preferredStudent.getName(), preferredStudent.getBranch());
}
} else if (error instanceof NetworkError) {
if (preferredStudent == null) {
resetUserPreplacedViews();
Snackbar snackbar = Snackbar.make(activityMainBinding.mainLayout, "Cannot establish connection", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
MainActivity.this.getAttendanceAPI(this.sharedPreferences.getString(API, api), param[1], param[2], preferredStudent.getAcademic_year(), preferredStudent.getName(), preferredStudent.getBranch());
}
} else if (error instanceof TimeoutError) {
if (!track) {
activityMainBinding.bottomLogin.progressBar.setVisibility(View.VISIBLE);
activityMainBinding.bottomLogin.loginButton.setVisibility(View.GONE);
activityMainBinding.bottomLogin.user.setEnabled(false);
activityMainBinding.bottomLogin.preplaced.setEnabled(false);
activityMainBinding.bottomLogin.user.setFocusable(true);
activityMainBinding.bottomLogin.preplaced.setFocusable(true);
activityMainBinding.bottomLogin.preplacedwordLayout.setEndIconMode(TextInputLayout.END_ICON_NONE);
track = true;
activityMainBinding.bottomLogin.loginButton.performClick();
} else {
if (preferredStudent == null) {
resetUserPreplacedViews();
Snackbar snackbar = Snackbar.make(activityMainBinding.mainLayout, "Cannot connect to ITER servers right now.Try again", Snackbar.LENGTH_SHORT);
snackbar.show();
track = false;
} else {
MainActivity.this.getAttendanceAPI(this.sharedPreferences.getString(API, api), param[1], param[2], preferredStudent.getAcademic_year(), preferredStudent.getName(), preferredStudent.getBranch());
}
}
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("user", param[1]);
params.put("preplaced", param[2]);
return params;
}
};
queue.add(postRequest);
}
19
Source : AttendanceActivity.java
with GNU General Public License v3.0
from codex-iter
with GNU General Public License v3.0
from codex-iter
private void getResultAPI(final String... param) {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest(Request.Method.POST, param[0] + "/result", response -> {
if (response.equals("900")) {
hideBottomSheetDialog();
Snackbar snackbar = Snackbar.make(activityAttendanceBinding.mainLayout, "Results not found", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
hideBottomSheetDialog();
Intent intent = new Intent(AttendanceActivity.this, ResultActivity.clreplaced);
response += "kkk" + param[1];
intent.putExtra(RESULTS, response);
startActivity(intent);
}
}, error -> {
hideBottomSheetDialog();
Intent intent = new Intent(AttendanceActivity.this, ResultActivity.clreplaced);
if (error instanceof AuthFailureError) {
Snackbar snackbar = Snackbar.make(activityAttendanceBinding.mainLayout, "Wrong Credentials!", Snackbar.LENGTH_SHORT);
snackbar.show();
} else if (error instanceof ServerError) {
if (preferredStudent == null) {
Snackbar snackbar = Snackbar.make(activityAttendanceBinding.mainLayout, "Wrong Credentials!", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
intent.putExtra(RESULTS, preferredStudent.getOfflineResult());
startActivity(intent);
}
} else if (error instanceof NetworkError) {
if (preferredStudent == null) {
Snackbar snackbar = Snackbar.make(activityAttendanceBinding.mainLayout, "Cannot establish connection", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
intent.putExtra(RESULTS, preferredStudent.getOfflineResult());
startActivity(intent);
}
} else {
if (preferredStudent == null) {
Snackbar snackbar = Snackbar.make(activityAttendanceBinding.mainLayout, "Cannot establish connection", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
intent.putExtra(RESULTS, preferredStudent.getOfflineResult());
startActivity(intent);
}
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("user", param[1]);
params.put("preplaced", param[2]);
return params;
}
};
queue.add(postRequest);
}
See More Examples