Java Android中的自定义异步Http客户端
我使用,但我认为这可以应用于异步任务(本机任务) 我经常在很多单独的课堂上使用它。onStart、onFailure和onRetry在任何地方都是相同的,只是复制粘贴,只是onSuccess不同 我想让我的代码尽可能干净,并重用我已经编写的代码,所以我的问题是,如何在一个单独的“文件”中进行自定义,并重用它。我只需要“OnSuccess”函数。多谢各位 --------------------------------------- GET和POST解决方案(感谢furkan3ayraktar) 第一个文件请求侦听器Java Android中的自定义异步Http客户端,java,android,android-asynctask,Java,Android,Android Asynctask,我使用,但我认为这可以应用于异步任务(本机任务) 我经常在很多单独的课堂上使用它。onStart、onFailure和onRetry在任何地方都是相同的,只是复制粘贴,只是onSuccess不同 我想让我的代码尽可能干净,并重用我已经编写的代码,所以我的问题是,如何在一个单独的“文件”中进行自定义,并重用它。我只需要“OnSuccess”函数。多谢各位 --------------------------------------- GET和POST解决方案(感谢furkan3ayraktar)
package com.classicharmony.krakenmessages.utils.AsyncHttp;
import org.apache.http.Header;
public interface RequestListener {
public void onSuccess(int statusCode, Header[] headers, byte[] response);
}
第二个文件请求处理程序
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
public class RequestHandler {
private static RequestHandler instance;
private AsyncHttpClient client;
private static final boolean SHOW_DEBUG_ALERT_DIALOG = true;
private RequestHandler() {
client = new AsyncHttpClient();
}
public static RequestHandler getInstance() {
if (instance == null) {
instance = new RequestHandler();
}
return instance;
}
public void make_get_Request(final Context context, final String url, final RequestListener listener) {
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onStart() {
Log.v("▒▒▒▒▒▒▒ GET ", url);
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
listener.onSuccess(statusCode, headers, response);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
Log.e("▒▒▒▒▒▒▒ GET FAILED ", url);
Log.e("▒▒▒▒▒▒▒ GET FAILED ", e.getLocalizedMessage());
if (DUtils.isDebuggable(context) && SHOW_DEBUG_ALERT_DIALOG) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("▒▒▒▒▒ ERROR ▒▒▒▒▒");
String error_msg;
if (errorResponse != null) {
try {
error_msg = String.valueOf(new String(errorResponse, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
error_msg = e.getLocalizedMessage();
}
} else {
error_msg = e.getLocalizedMessage();
}
builder.setMessage(context.getClass().getSimpleName() + " -> " + error_msg)
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
@Override
public void onRetry(int retryNo) {
Log.e("▒▒▒▒▒▒▒ RETRYING ", "....." + String.valueOf(retryNo));
}
});
}
public void make_post_Request(final Context context, final StringEntity entity, final String url, final RequestListener listener) {
client.post(context, url, entity, "application/json", new AsyncHttpResponseHandler() {
@Override
public void onStart() {
Log.v("▒▒▒▒▒▒▒ POST ", url);
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
listener.onSuccess(statusCode, headers, response);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
Log.e("▒▒▒▒▒▒▒ POST FAILED ", url);
Log.e("▒▒▒▒▒▒▒ POST FAILED ", context.getClass().getSimpleName() + " -> " + e.getLocalizedMessage());
if (DUtils.isDebuggable(context) && SHOW_DEBUG_ALERT_DIALOG) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("▒▒▒▒▒ ERROR ▒▒▒▒▒");
String error_msg;
if (errorResponse != null) {
try {
error_msg = String.valueOf(new String(errorResponse, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
error_msg = e.getLocalizedMessage();
}
} else {
error_msg = e.getLocalizedMessage();
}
builder.setMessage(context.getClass().getSimpleName() + " -> " + error_msg)
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
@Override
public void onRetry(int retryNo) {
Log.e("▒▒▒▒▒▒▒ RETRYING ", "....." + String.valueOf(retryNo));
}
});
}
}
第三个“实用程序”显示对话框或不显示对话框
public static boolean isDebuggable(Context ctx) {
boolean debuggable = false;
X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");
try {
PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
Signature signatures[] = pinfo.signatures;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
for (int i = 0; i < signatures.length; i++) {
ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
if (debuggable)
break;
}
} catch (PackageManager.NameNotFoundException e) {
//debuggable variable will remain false
} catch (CertificateException e) {
//debuggable variable will remain false
}
return debuggable;
}
您可以创建自己的空版本的
AsyncHttpResponseHandler
,它不实现onSuccess
方法
public abstract class OWADVLHttpResponseHandler extends AsyncHttpResponseHandler {
@Override
public void onStart() {}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {}
@Override
public void onRetry(int retryNo) {}
}
您的代码将如下所示:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new OWADVLHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
....
}
});
显然,您可以在基类中的非重写方法中填充一些内容。创建公共请求处理程序和侦听器。您还可以为每个需要的请求创建不同的请求方法,如makeRequest,还可以创建不同的侦听器。这是我常用的一个简单模式
public class RequestHandler{
private static RequestHandler instance;
private AsyncHttpClient client;
private RequestHandler(){
client = new AsyncHttpClient();
}
public static RequestHandler getInstance(){
if(instance == null){
instance = new RequestHandler();
}
return instance;
}
// You can add more parameters if you need here.
public void makeRequest(String url, RequestListener listener){
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
//Some debugging code here
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
listener.onSuccess(statusCode, headers, response);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Some debugging code here, show retry dialog, feedback etc.
}
@Override
public void onRetry(int retryNo) {
//Some debugging code here-------
}
});
}
}
public interface RequestListener{
public void onSuccess(int statusCode, Header[] headers, byte[] response);
}
然后在任何你想要的地方使用如下
RequestHandler handler = RequestHandler.getInstance();
handler.makeRequest("http://www.google.com", new RequestListener(){
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// do whatever you want here.
}
});
首先,创建一个抽象基类来实现常见的行为。大概是这样的:
public abstract class AsyncHttpResponesHandlerBase implements AsyncHttpResponseHandler {
@Override
public void onStart() {
// called before request is started
// Some debugging code here
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Some debugging code here, show retry dialog, feedback etc.
}
@Override
public void onRetry(int retryNo) {
//Some debugging code here-------
}
}
然后根据从基类继承的url,实现onSuccess()
方法来处理响应
public class GoogleGetHandler extends AsyncHttpResponesHandlerBase {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
// do the Google specific handling
}
}
您可以按如下方式发出HTTP请求:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new GoogleGetHandler());
因此,如果您想调用更多的URL,只需继续基于基类创建新的子类,以便继承常见的故障处理。*********************************************
*********************************************
Calling Api USing Retrofit
*********************************************
**Dependancies** :-
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'com.google.code.gson:gson:2.2.4'
enter code here
**Model**
use the Pozo class
**Api Call**
-> getLogin() // use the method
//API call for Login
private void getLogin()
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("email_id", edit_email.getText().toString());
requestParams.put("password", edit_password.getText().toString());
Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
ShowProgress();
}
@Override
public void onFinish() {
super.onFinish();
Hideprogress();
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("", "Login RESPONSE-" + response);
Login login = new Gson().fromJson(String.valueOf(response), Login.class);
edit_email.setText("");
edit_password.setText("");
if (login.getStatus().equals("true")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
mdToast.show();
Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
hideKeyboard(SignInActivity.this);
Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("", throwable.getMessage());
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
});
}
implements LocationListener {
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private String vendorId, vendorName, vendorPhone, vendorImg, vendorDistance, vendorStar, vendorRate, vendorAddress, vendorSummary, vendorOtherService;
LocationManager locationManager;
private FusedLocationProviderClient mFusedLocationProviderClient;
private boolean mLocationPermissionGranted;
private Location mLastKnownLocation;
init()
{
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
@Click
public void lnrCurrentLocation() {
getLocationPermission();
getDeviceLocation();
}
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted)
{
final Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
MarkerOptions markerOptions = new MarkerOptions();
if (task.isSuccessful()) {
mLastKnownLocation = task.getResult();
if(mLastKnownLocation!=null)
{
Double lat = mLastKnownLocation.getLatitude();
Double lng = mLastKnownLocation.getLongitude();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(AddAddressActivity.this, Locale.getDefault());
try {
Log.e("latitude", "inside latitude--" + lat);
addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
edtAddress.setText(address );
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (lat != null && lng != null) {
fastSave.saveString(Constant.CURR_LAT, String.valueOf(mLastKnownLocation.getLatitude()));
fastSave.saveString(Constant.CURR_LON, String.valueOf(mLastKnownLocation.getLongitude()));
} else {
getDeviceLocation();
}
}
}
}
});
}
else {
Log.d("@permision","======== Permision not found =========");
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
}
void getLocation() {
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
"GOOGLE MAP IN ANDROID"
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-maps:11.8.0'
implementation 'com.github.pedroSG94:AutoPermissions:1.0.3'
<meta-data
android:name="@string/permissions_loader_meta_key"
android:value="android.permission.WRITE_EXTERNAL_STORAGE, android.permission.CAMERA,android.permission.ACCESS_FINE_LOCATION,android.permission.ACCESS_COARSE_LOCATION" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
implements OnMapReadyCallback, AutoPermissionsListener {
private GoogleMap mMap;
AutoPermissions.Companion.loadActivityPermissions(DashboardActivity.this, 1);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
AutoPermissions.Companion.parsePermissions(DashboardActivity.this, requestCode, permissions, this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(0.0, 0.0);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
@Override
public void onDenied(int i, String[] strings) {
}
@Override
public void onGranted(int i, String[] strings) {
}
使用改型调用Api
*********************************************
**从属关系**:-
实现'com.android.support:recyclerview-v7:27.1.1'
实现'com.squareup.picasso:picasso:2.5.2'
实现'com.android.support:cardview-v7:27.1.1'
实现'com.loopj.android:android异步http:1.4.9'
实现'com.google.code.gson:gson:2.2.4'
在这里输入代码
**模型**
使用Pozo类
**Api调用**
->getLogin()//使用该方法
//用于登录的API调用
私有void getLogin()
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG)不可触摸,
WindowManager.LayoutParams.FLAG(不可触摸);
AsyncHttpClient=新的AsyncHttpClient();
RequestParams RequestParams=新的RequestParams();
requestParams.put(“email_id”,edit_email.getText().toString());
requestParams.put(“密码”,编辑_password.getText().toString());
Log.e(“,”登录URL==>“+URL.LOGIN+requestParams);
Log.d(“设备令牌”,“设备令牌”+FirebaseInstanceId.getInstance().getToken());
client.post(url.LOGIN、requestParams、新的JsonHttpResponseHandler(){
@凌驾
public void onStart(){
super.onStart();
ShowProgress();
}
@凌驾
公共无效onFinish(){
super.onFinish();
Hideprogress();
}
@凌驾
成功时的公共void(int statusCode,Header[]headers,JSONObject响应){
super.onSuccess(状态码、头、响应);
Log.e(“,”登录响应-“+响应);
Login Login=new Gson().fromJson(String.valueOf(response),Login.class);
编辑_email.setText(“”);
编辑_password.setText(“”);
if(login.getStatus().equals(“true”)){
getWindow().clearFlags(WindowManager.LayoutParams.FLAG\u不可触摸);
MDToast MDToast=MDToast.makeText(SignInActivity.this,String.valueOf(“用户登录成功!”),
MDToast.LENGTH\u SHORT,MDToast.TYPE\u SUCCESS);
mdToast.show();
Utils.WriteSharePrefrence(SignInActivity.this,Util_Main.Constant.EMAIL,login.getData().getEmailId());
Utils.WriteSharePrefrence(SignInActivity.this、Constant.USERID、login.getData().getId());
Utils.WriteSharePrefrence(SignInActivity.this、Constant.USERNAME、login.getData().getFirstName());
Utils.WriteSharePrefrence(SignInActivity.this、Constant.PROFILE、login.getData().getProfileImage());
隐藏板(signiancivity.this);
意向意向=新意向(SignenActivity.this、DashboardActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
星触觉(意向);
完成();
}否则{
getWindow().clearFlags(WindowManager.LayoutParams.FLAG\u不可触摸);
MDToast MDToast=MDToast.makeText(SignenActivity.this,String.valueOf(“登录被拒绝”),
MDToast.LENGTH\u SHORT,MDToast.TYPE\u错误);
mdToast.show();
}
}
@凌驾
public void onFailure(int statusCode,Header[]headers,String responseString,Throwable Throwable){
super.onFailure(状态码、标题、响应字符串、可丢弃);
Log.e(“,throwable.getMessage());
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new GoogleGetHandler());
*********************************************
Calling Api USing Retrofit
*********************************************
**Dependancies** :-
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'com.google.code.gson:gson:2.2.4'
enter code here
**Model**
use the Pozo class
**Api Call**
-> getLogin() // use the method
//API call for Login
private void getLogin()
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("email_id", edit_email.getText().toString());
requestParams.put("password", edit_password.getText().toString());
Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
ShowProgress();
}
@Override
public void onFinish() {
super.onFinish();
Hideprogress();
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("", "Login RESPONSE-" + response);
Login login = new Gson().fromJson(String.valueOf(response), Login.class);
edit_email.setText("");
edit_password.setText("");
if (login.getStatus().equals("true")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
mdToast.show();
Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
hideKeyboard(SignInActivity.this);
Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("", throwable.getMessage());
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
});
}
implements LocationListener {
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private String vendorId, vendorName, vendorPhone, vendorImg, vendorDistance, vendorStar, vendorRate, vendorAddress, vendorSummary, vendorOtherService;
LocationManager locationManager;
private FusedLocationProviderClient mFusedLocationProviderClient;
private boolean mLocationPermissionGranted;
private Location mLastKnownLocation;
init()
{
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
@Click
public void lnrCurrentLocation() {
getLocationPermission();
getDeviceLocation();
}
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted)
{
final Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
MarkerOptions markerOptions = new MarkerOptions();
if (task.isSuccessful()) {
mLastKnownLocation = task.getResult();
if(mLastKnownLocation!=null)
{
Double lat = mLastKnownLocation.getLatitude();
Double lng = mLastKnownLocation.getLongitude();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(AddAddressActivity.this, Locale.getDefault());
try {
Log.e("latitude", "inside latitude--" + lat);
addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
edtAddress.setText(address );
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (lat != null && lng != null) {
fastSave.saveString(Constant.CURR_LAT, String.valueOf(mLastKnownLocation.getLatitude()));
fastSave.saveString(Constant.CURR_LON, String.valueOf(mLastKnownLocation.getLongitude()));
} else {
getDeviceLocation();
}
}
}
}
});
}
else {
Log.d("@permision","======== Permision not found =========");
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
}
void getLocation() {
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
"GOOGLE MAP IN ANDROID"
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-maps:11.8.0'
implementation 'com.github.pedroSG94:AutoPermissions:1.0.3'
<meta-data
android:name="@string/permissions_loader_meta_key"
android:value="android.permission.WRITE_EXTERNAL_STORAGE, android.permission.CAMERA,android.permission.ACCESS_FINE_LOCATION,android.permission.ACCESS_COARSE_LOCATION" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
implements OnMapReadyCallback, AutoPermissionsListener {
private GoogleMap mMap;
AutoPermissions.Companion.loadActivityPermissions(DashboardActivity.this, 1);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
AutoPermissions.Companion.parsePermissions(DashboardActivity.this, requestCode, permissions, this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(0.0, 0.0);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
@Override
public void onDenied(int i, String[] strings) {
}
@Override
public void onGranted(int i, String[] strings) {
}
-----------------------------------------------------
LATEST Calling Api USing Retrofit
Api Call USING RETROFIT With GET & POST
-----------------------------------------------------
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
implementation "com.android.support:cardview-v7:28.0.0"
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
1] GET API WITH DISPLAY DATA IN RECYCLERVIEW :-
ApiInterface
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface
{
@GET("/photos")
Call<List<RetroPhoto>> getAllPhotos();
}
RestApiClient
mport retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RestApiClient {
private static Retrofit retrofit;
private static final String BASE_URL = "https://jsonplaceholder.typicode.com";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private CustomAdapter adapter;
private RecyclerView recyclerView;
ProgressDialog progressDoalog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMessage("Loading....");
progressDoalog.show();
/*Create handle for the RetrofitInstance interface*/
ApiInterface service = RestApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<List<RetroPhoto>> call = service.getAllPhotos();
call.enqueue(new Callback<List<RetroPhoto>>() {
@Override
public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {
progressDoalog.dismiss();
generateDataList(response.body());
}
@Override
public void onFailure(Call<List<RetroPhoto>> call, Throwable t) {
progressDoalog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<RetroPhoto> photoList) {
recyclerView = findViewById(R.id.customRecyclerView);
adapter = new CustomAdapter(this, photoList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}
activity_main
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/customRecyclerView"
android:layout_height="match_parent"
/>
custom_row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/coverImage"
android:layout_width="80dp"
android:layout_height="80dp" />
<TextView
android:id="@+id/title"
android:textSize="15dp"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
RetroPhoto
import com.google.gson.annotations.SerializedName;
public class RetroPhoto {
@SerializedName("albumId")
private Integer albumId;
@SerializedName("id")
private Integer id;
@SerializedName("title")
private String title;
@SerializedName("url")
private String url;
@SerializedName("thumbnailUrl")
private String thumbnailUrl;
public RetroPhoto(Integer albumId, Integer id, String title, String url, String thumbnailUrl) {
this.albumId = albumId;
this.id = id;
this.title = title;
this.url = url;
this.thumbnailUrl = thumbnailUrl;
}
public Integer getAlbumId() {
return albumId;
}
public void setAlbumId(Integer albumId) {
this.albumId = albumId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
CustomAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
private List<RetroPhoto> dataList;
private Context context;
public CustomAdapter(Context context,List<RetroPhoto> dataList){
this.context = context;
this.dataList = dataList;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
public final View mView;
TextView txtTitle;
private ImageView coverImage;
CustomViewHolder(View itemView) {
super(itemView);
mView = itemView;
txtTitle = mView.findViewById(R.id.title);
coverImage = mView.findViewById(R.id.coverImage);
}
}
@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.custom_row, parent, false);
return new CustomViewHolder(view);
}
@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
holder.txtTitle.setText(dataList.get(position).getTitle());
Picasso.get().load(dataList.get(position).getThumbnailUrl()).into(holder.coverImage);
// Picasso.Builder builder = new Picasso.Builder(context);
// builder.downloader(new OkHttp3Downloader(context));
// builder.build().load(dataList.get(position).getThumbnailUrl())
// .placeholder((R.drawable.ic_launcher_background))
// .error(R.drawable.ic_launcher_background)
// .into(holder.coverImage);
}
@Override
public int getItemCount() {
return dataList.size();
}
}
2] POST API WITH LOGIN :-
ApiInterface
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface ApiInterface
{
@FormUrlEncoded
@POST("/login")
// void Login(@FieldMap Map<String, String> map, Callback<Login> callback);
Call<Login> Login(@FieldMap Map<String, String> map);
}
RestApiClient
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RestApiClient {
private static Retrofit retrofit;
private static final String BASE_URL = "http://wwwdemo.com/api/";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMessage("Loading....");
progressDoalog.show();
Map<String, String> map = new HashMap<>();
map.put("email", edit_email.getText().toString());
map.put("password", edit_password.getText().toString());
map.put("device_type", "android");
map.put("device_token", "dfgdf");
ApiInterface service = RestApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<Login> call = service.Login(map);
call.enqueue(new Callback<Login>() {
@Override
public void onResponse(Call<Login> call, Response<Login> response) {
progressDoalog.dismiss();
if (response.body().getStatus().equals("success")) {
Toast.makeText(MainActivity.this, "Login Successfully", Toast.LENGTH_SHORT).show();
Log.d("login", "===== Success ====");
} else {
Toast.makeText(MainActivity.this, "Login Denied!", Toast.LENGTH_SHORT).show();
Log.d("login", "===== Fail ====");
}
}
@Override
public void onFailure (Call < Login > call, Throwable t){
progressDoalog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
Log.d("login", "===== Failure ====");
}
});
}
OTHER TIP
1 pass header is require token only.
@Header("Authorization") String Authorization
2 to pass parameter vie Hasmap
Map<String, String> map = new HashMap<>();
@FieldMap Map<String, String> map
3 image upload with input
@Multipart
@POST("api")
Call<Upload> uploadapi(@Header("Authorization") String token, @Part List<MultipartBody.Part> files, @PartMap Map<String, RequestBody> map);
ArrayList<MultipartBody.Part> multipart = new ArrayList<>();
Map<String, RequestBody> map = new HashMap<>();
map.put("key", RequestBody.create(MediaType.parse("text/plain"), value));
multipart.add(Utility.prepareFilePart(Activity.this, "document_file", picturePath));
public static MultipartBody.Part prepareFilePart(Context context, String partName, String filePath) {
if(filePath!=null) {
File file = new File(filePath);
Log.d("TAG", "prepareFilePart: " + filePath);
// RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(Uri.fromFile(file))), file);
// Libaray Required
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// Multipart Camera and Gallery
// RequestBody requestBody = RequestBody.create(MediaType.parse(context.getContentResolver().getType(FileProvider.getUriForFile(context, "com.sine.provider", file))), file);
return MultipartBody.Part.createFormData(partName, file.getName(), requestBody);
}
else {
return MultipartBody.Part.createFormData(partName,"");
}
}
4] void Login(@FieldMap Map<String, String> map, Callback<Login> callback);
RetrofitClient.getInstance().getmRestClient().Login(map, new Callback<Login>() {
@Override
public void success(Login loginResponse, Response response) {
}
}
@Override
public void failure(RetrofitError error) {
}
});
public class RetrofitClient {
private final static String TAG = RetrofitClient.class.getSimpleName();
private static final Object LOCK = new Object();
private static FinalWrapper<RetrofitClient> helperWrapper;
private final RestClient mRestClient;
private RetrofitClient() {
// Rest client without basic authorization
mRestClient = ServiceGenerator.createService(RestClient.class);
}
public static RetrofitClient getInstance() {
FinalWrapper<RetrofitClient> wrapper = helperWrapper;
if (wrapper == null) {
synchronized (LOCK) {
if (helperWrapper == null) {
helperWrapper = new FinalWrapper<>(new RetrofitClient());
}
wrapper = helperWrapper;
}
}
return wrapper.value;
}
public RestClient getmRestClient() {
return mRestClient;
}
ServiceGenerator
public class ServiceGenerator {
private ServiceGenerator() {
}
public static <S> S createService(Class<S> serviceClass) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(Constant.BASE_URL)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(okHttpClient));
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, String username, String password) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(Constant.BASE_URL_USERS)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(okHttpClient));
if (username != null && password != null) {
// concatenate username and password with colon for authentication
final String credentials = username + ":" + password;
builder.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
// create Base64 encodet string
String string = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Accept", "application/json");
request.addHeader("Authorization", string);
}
});
}
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
public class FinalWrapper<T> {
public final T value;
public FinalWrapper(T value) {
this.value = value;
}
}
5
@GET("/place/autocomplete/json?")
void getplacesLocationList(@Query("input") String str_input,@Query("radius") String radius, @Query("key") String key, Callback<PlacesLocation> callback);
6 pass fist above only post method
interface
@Headers("Content-Type:application/json;charset=UTF-8")
@POST("api/")
Call<Response> get(@Body RequestBody requestBody);
Apiclient
public class ApiClient {
public static final String Tag = "ApiClient";
private static final int CONNECTION_TIMEOUT = 30; //seconds
private static final int READ_TIMEOUT = 20; //seconds
private static final int WRITE_TIMEOUT = 20; //seconds
private static MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
private static MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/*");
private static Retrofit retrofit = null;
private static Gson gson;
public static Retrofit getClient() {
if (retrofit == null) {
OkHttpClient okHttpClient;
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient().newBuilder().connectTimeout
(CONNECTION_TIMEOUT,
TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).writeTimeout(WRITE_TIMEOUT,
TimeUnit.SECONDS).addInterceptor(interceptor).build();
} else {
okHttpClient = new OkHttpClient().newBuilder().connectTimeout
(CONNECTION_TIMEOUT,
TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).writeTimeout(WRITE_TIMEOUT,
TimeUnit.SECONDS).build();
}
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build();
}
return retrofit;
}
@NonNull
public static RequestBody makeTextRequestBody(Object stringData) {
return RequestBody.create(MEDIA_TYPE_TEXT, String.valueOf(stringData));
}
@NonNull
public static RequestBody makeGSONRequestBody(Object jsonObject) {
if (gson == null) {
gson = new Gson();
}
return RequestBody.create(MEDIA_TYPE_TEXT, gson.toJson(jsonObject));
}
@NonNull
public static String JSONResponse(Object jsonObject) {
if (gson == null) {
gson = new Gson();
}
String params = gson.toJson(jsonObject);
return params;
}
@NonNull
public static RequestBody makeJSONRequestBody(JSONObject jsonObject) {
String params = jsonObject.toString();
return RequestBody.create(MEDIA_TYPE_TEXT, params);
}
public static JSONObject JSONObject(Object jsonObject) {
if (gson == null) {
gson = new Gson();
}
try {
return new JSONObject(String.valueOf(gson.toJsonTree(jsonObject)
.getAsJsonObject()));
} catch (JSONException e) {
AppLog.handleException(Tag, e);
}
return null;
}
}
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, "");
jsonObject.put(key, "");
jsonObject.put(key, "");
jsonObject.put(key, "");
} catch (JSONException e) {
}
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<Response> aaa = apiInterface.apiname(ApiClient
.makeJSONRequestBody(jsonObject));
aaa.enqueue(new Callback<Response>() {
@Override
public void onResponse(Call<Response> call, Response<Response> response) {
}
}
@Override
public void onFailure(Call<Response> call, Throwable t)
{
}
});