Tuesday, July 30, 2019

Whitout Header Asp.net API


Dependencies.java


 implementation files('libs/ksoap2-android-assembly-3.1.1-jar-with-dependencies.jar')


 MainActivity.java


 private class checkVersion extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params)
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            SoapObject request = new SoapObject(Webservice.NAMESPACE, Webservice.sel_app_version);

            PropertyInfo tokenPI = new PropertyInfo();
            tokenPI.setName("token");
            tokenPI.setValue(Webservice.Token);
            tokenPI.setType(String.class);
            request.addProperty(tokenPI);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(request);
            HttpTransportSE androidHttpTransport = new HttpTransportSE(Webservice.URL);
            try {
                androidHttpTransport.call(Webservice.NAMESPACE + Webservice.sel_app_version, envelope);
                androidHttpTransport.getServiceConnection().setRequestProperty("Connection", "close");
            } catch (IOException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            }
            SoapPrimitive response = null;
            try {
                response = (SoapPrimitive) envelope.getResponse();
            } catch (SoapFault soapFault) {
                soapFault.printStackTrace();
            } catch (Exception e) {
            }
            String res = null;
            if (androidHttpTransport != null) {
                if (response != null) {
                    res = response.toString();
                } else {
                    res = null;
                }
                androidHttpTransport.reset();
                try {
                    androidHttpTransport.getServiceConnection().disconnect();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return res;
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null && !result.equals("[]")) {
                //Log.e("Admin", "Chk--" + result);
                try {
                    JSONObject j = new JSONObject(result);
                    String success = j.getString("Success");
                    if (success.equals("1")) {
                        Gson gson = new Gson();
                        JSONArray jsonArray = j.getJSONArray("result");
                        UserBean bean = new UserBean();
                        for (int i = 0; jsonArray.length() > i; i++) {
                            bean = gson.fromJson(jsonArray.get(i).toString(), UserBean.class);
                            String appver = appVersion();
                            if (!appver.equals(bean.getVer())) {
                                confirmDialog("App new version available! Update app.");
                            }
                        }

                    } else {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
           
            super.onPostExecute(result);
        }
    }

Asp.net Api



Dependancy

  implementation 'com.google.code.ksoap2-android:ksoap2-android:3.6.2'



package com.softwisdom.e_building_user;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.onesignal.OneSignal;
import com.softwisdom.e_building_user.Bean.UserBean;
import com.softwisdom.e_building_user.action.ConnectionDetector;
import com.softwisdom.e_building_user.action.Webservice;
import com.softwisdom.e_building_user.onesignal.MyNotificationOpenedHandler;
import com.softwisdom.e_building_user.onesignal.MyNotificationReceivedHandler;
import com.softwisdom.e_building_user.preference.LoginPreferences;
import com.google.gson.Gson;

import org.jetbrains.annotations.TestOnly;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;


public class LoginActivity extends AppCompatActivity {

    protected TextView tvSignIn,tvForget,tvSkipRegister;
    private TextView tvSignUp;
    private Activity activity = LoginActivity.this;
    private ImageView img_google;
    private EditText etMobile, etPassword;
    private LoginPreferences loginPreferences;
    private ConnectionDetector connectionDetector;
    private ProgressDialog dialog;
    private String token;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_login);

        initVariables();
        initView();
        setListners();
        tokenGenerate();
    }

    public void initVariables() {
        loginPreferences = new LoginPreferences(activity);
        connectionDetector = new ConnectionDetector(activity);
    }

    /*One signal token generation*/
    private void tokenGenerate()
    {
        OneSignal.startInit(this)
                .setNotificationOpenedHandler(new MyNotificationOpenedHandler())
                .setNotificationReceivedHandler(new MyNotificationReceivedHandler())
                .autoPromptLocation(true)
                .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                .init();
        OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
            @Override
            public void idsAvailable(String userId, String registrationId) {
                token = userId;
                Log.e("token==", token);
                if (registrationId != null) {
                    // Log.e("debug", "registrationId:" + registrationId);
                }

            }
        });
    }

    private void initView() {
        tvSignUp = (TextView) findViewById(R.id.tvSignUp);
        tvSignIn = (TextView) findViewById(R.id.tvSignIn);
        tvForget = (TextView) findViewById(R.id.tvForget);
        tvSkipRegister = (TextView) findViewById(R.id.tvSkipRegister);
        etMobile = (EditText) findViewById(R.id.etMobile);
        etPassword = (EditText) findViewById(R.id.etPassword);
        img_google = (ImageView) findViewById(R.id.img_google);
    }

    public void setListners() {
        tvSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(activity,OtpActivity.class);
                intent.putExtra("type","r");
                startActivity(intent);

                finish();
            }
        });

        tvSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String mobile = etMobile.getText().toString();
                String password = etPassword.getText().toString();

                if (!mobile.isEmpty() && mobile.length() == 10 && !password.isEmpty()) {
                    if (connectionDetector.isConnectingToInternet()) {
                        new Login().execute( mobile,password);
                    } else {
                        Toast.makeText(activity, getResources().getString(R.string.please_check_internet_connection), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (mobile.isEmpty()) {
                        etMobile.setError(getResources().getString(R.string.enter_mobile));
                        etMobile.requestFocus();
                    } else if (mobile.length() != 10) {
                        etMobile.setError(getResources().getString(R.string.mobile_should_be_10_digits));
                        etMobile.requestFocus();
                    } else if (password.isEmpty()) {
                        etPassword.setError(getResources().getString(R.string.enter_password));
                        etPassword.requestFocus();
                    }
                }
            }
        });

        tvForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(activity,ForgetPasswordActivity.class));
                finish();
            }
        });

        tvSkipRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!loginPreferences.isUserLoggedIn()) {
                    Intent intent = new Intent(activity, OtpActivity.class);
                    intent.putExtra("type", "g");
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    private class Login extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(activity);
            dialog.setMessage(getResources().getString(R.string.please_wait));
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            SoapObject soapObject = new SoapObject(Webservice.NAMESPACE, Webservice.USER_LOGIN);

            Element authHeader = new Element();
            authHeader.setNamespace(Webservice.NAMESPACE);
            authHeader.setName("AuthUser");

            Element username = new Element().createElement(Webservice.NAMESPACE, "UserName");
            username.addChild(Node.TEXT, Webservice.USERNAME);
            authHeader.addChild(Node.ELEMENT, username);

            Element pass = new Element().createElement(Webservice.NAMESPACE, "Password");
            pass.addChild(Node.TEXT, Webservice.PASSWORD);
            authHeader.addChild(Node.ELEMENT, pass);


            Element Token = new Element().createElement(Webservice.NAMESPACE, "Token");
            Token.addChild(Node.TEXT, Webservice.TOKEN);
            authHeader.addChild(Node.ELEMENT, Token);

            soapObject.addProperty("mobile_no", params[0]);
            soapObject.addProperty("password", params[1]);
            soapObject.addProperty("device_id", token);

            Log.e("Login_Request", soapObject.toString());

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.headerOut = new Element[]{authHeader};
            envelope.dotNet = true;

            envelope.setOutputSoapObject(soapObject);

            HttpTransportSE androidHttpTransport = new HttpTransportSE(Webservice.URL);
            try {
                androidHttpTransport.call(Webservice.NAMESPACE + Webservice.USER_LOGIN, envelope);
                androidHttpTransport.getServiceConnection().setRequestProperty("Connection", "close");
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("IError", e.toString());
            } catch (XmlPullParserException e) {
                e.printStackTrace();
                Log.e("IXml", e.toString());
            }
            SoapPrimitive response = null;
            try {
                response = (SoapPrimitive) envelope.getResponse();
            } catch (SoapFault soapFault) {
                soapFault.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            String res = null;
            if (androidHttpTransport != null) {
                if (response != null) {
                    res = response.toString();
                } else {
                    res = null;
                }
                androidHttpTransport.reset();
                try {
                    androidHttpTransport.getServiceConnection().disconnect();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return res;
        }

        @Override
        protected void onPostExecute(String result) {
            dialog.dismiss();
            if (result != null && !result.equals("[]")) {
                Log.e("Login Response==", result);
                try {
                    JSONObject obj = new JSONObject(result);
                    String success = obj.getString("Success");
                    if (success.equals("1")) {
                        JSONArray jsonArray = obj.getJSONArray("result");
                        UserBean bean = new UserBean();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            Gson gson = new Gson();
                            bean = gson.fromJson(obj.getJSONArray("result").get(0).toString(), UserBean.class);
                        }

                       /* if(bean.getTemp_status().equals("false"))
                        {
                            Toast.makeText(activity, "You are not approved", Toast.LENGTH_SHORT).show();


                        }
                        else
                        {
                            Toast.makeText(activity, "Login Successfully", Toast.LENGTH_SHORT).show();

                            loginPreferences.createUserLoginSession(bean.getUser_id()
                                    ,bean.getName(),bean.getProfile_pic(),bean.getPro_type(),bean.getPro_id(),bean.getWing_id()
                                    ,bean.getOffice_no(),bean.getTemp_status(),bean.getStatus(),bean.getCreate_by()
                                    ,bean.getCreate_date());

                            startActivity(new Intent(activity,HomeActivity.class));
                            finish();
                        }*/
                        Toast.makeText(activity, "" + getResources().getString(R.string.login_successfully), Toast.LENGTH_SHORT).show();

                        loginPreferences.createUserLoginSession(bean.getUser_id(), bean.getName(), bean.getProfile_pic(), bean.getPassword(), bean.getMobile_no(),bean.getEmail(),"r");

                        loginPreferences.setLoginStatus(true);
                        Webservice.isFirstTimeOpen=true;
                        Intent intent = new Intent(activity, MainActivity.class);
                        startActivity(intent);
                        finish();


                    } else {
                        Toast.makeText(activity, "" + getResources().getString(R.string.invalid_username_and_passsword), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {

                Toast.makeText(activity, getResources().getString(R.string.no_data_found), Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(result);

        }
    }
}

Retrofit Display data

Dependencies


implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit:retrofit:1.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.google.android.material:material:1.0.0-rc01'//AndroidX



APIclient.java


package com.example.retrofit.Reset;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class APIclient
{
    public static final String BASEURL="http://sktechnocast.com";
    public static Retrofit retrofit=null;

    public static Retrofit getClient()
    {
        if(retrofit==null)
        {
            retrofit=new Retrofit.Builder().baseUrl(BASEURL)
                    .addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
    }
}



APIinterface.java


package com.example.retrofit.Reset;

import com.example.retrofit.Model.Getdata;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;


public interface APIinterface {

    @GET("/android/Monika/IT_Programing/company_logo.php")
    //Call<Getdata>GetAlldata();
   // Call<JsonElement>GetAlldata();
    //public String Getdata(Callback<String> callback);
    Call<JsonObject> GetAlldata();


}


MainActivity.java



package com.example.retrofit;


import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.retrofit.Adapter.DisplaydataAdpter;
import com.example.retrofit.Model.Getdata;
import com.example.retrofit.Reset.APIclient;
import com.example.retrofit.Reset.APIinterface;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import retrofit.RestAdapter;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private Activity activity = MainActivity.this;
    private RecyclerView rvdata;
    private ArrayList<Getdata> listdata;
    private DisplaydataAdpter adpter;
    private EditText txt_nm, txt_city;
    private Button btn_submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initComponent();
        Setlisner();
    }

    public void init() {
        rvdata = (RecyclerView) findViewById(R.id.rvdata);
        txt_nm = (EditText) findViewById(R.id.txt_nm);
        txt_city = (EditText) findViewById(R.id.txt_city);
        btn_submit = (Button) findViewById(R.id.btn_submit);
    }

    public void initComponent() {
        listdata = new ArrayList<Getdata>();
    }

    private void Setlisner() {
        Displaydata();
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    private void Displaydata()
    {
        APIinterface api = APIclient.getClient().create(APIinterface.class);
        Call<JsonObject> call = api.GetAlldata();
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                JsonObject jsonObject = response.body();
                Log.e("result==",response.body().toString());
                String success = response.body().get("success").toString();
                if (success.equals("1"))
                {
                    JsonArray jsonArray = jsonObject.getAsJsonArray("result");
                    Gson gson = new Gson();
                    for (int i = 0; i < jsonArray.size(); i++)
                    {
                        Getdata bean = new Getdata();
                        bean = gson.fromJson(jsonArray.get(i).toString(), Getdata.class);
                        listdata.add(bean);
                    }
                    rvdata.setLayoutManager(new LinearLayoutManager(activity));
                    adpter = new DisplaydataAdpter(activity, listdata);
                    rvdata.setAdapter(adpter);
                }
                else {
                    Toast.makeText(MainActivity.this, "no data found", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {

            }
        });
    }

}






GogoleMap

Dependencies


    implementation 'pub.devrel:easypermissions:0.2.0'//permission
    implementation 'com.google.android.gms:play-services-maps:16.0.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    apply plugin: 'com.google.gms.google-services'



Androidmanifest.xml


    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" />



SplashActivity.java


package com.example.e_building_design;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;



import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class SplashActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{

    private ImageView iv_logo;
    private String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };

    private Activity activity=SplashActivity.this;
    public String token;
  //  private LoginPreferences loginPreferences;
   // private ConnectionDetector connectionDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        initView();
    }

    private void initView() {
 
        iv_logo = (ImageView) findViewById(R.id.iv_logo);

       Animation aniFade = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);
        iv_logo.startAnimation(aniFade);
        if (!EasyPermissions.hasPermissions(activity, permissions)) {
            EasyPermissions.requestPermissions(activity, "Please allow app", 1, permissions);
        } else {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                   if (new LoginPreferences(activity).isUserLoggedIn()) {
                        if(connectionDetector.isConnectingToInternet()) {
                         new Login().execute();

                        }
                    } else {*/
                        startActivity(new Intent(activity, LoginActivity.class));
                        finish();
                    //}
                }
            }, 3500);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (!EasyPermissions.hasPermissions(activity, permissions)) {
            EasyPermissions.requestPermissions(activity, "Please allow app", 1, permissions);

        } else {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                   /* startActivity(new Intent(activity, LoginActivity.class));
                    finish();*/
                 /*  if (new LoginPreferences(activity).isUserLoggedIn()) {
                        if(connectionDetector.isConnectingToInternet()) {
                                    new Login().execute();

                        }
                    } else {*/
                        startActivity(new Intent(activity, LoginActivity.class));
                        finish();
                    //}
                }
            }, 3000);
        }
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }


    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        finish();
    }

}


MapsActivity.java



package com.example.e_building_design;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

import java.io.IOException;
import java.util.List;
import java.util.Locale;



public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleMap.OnMyLocationButtonClickListener,
        GoogleMap.OnMyLocationClickListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener, GoogleMap.OnMapClickListener {

    private GoogleMap mMap;
    private GoogleMap.OnMapClickListener mCustomOnMapClickListener;
    CameraUpdate cameraUpdate;
    Marker marker;
    double lat, lng;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    private GoogleApiClient googleApiClient;
    final static int REQUEST_LOCATION = 199;
    // check GPS enable or not
    private LocationManager locationManager;
    private int flag = 0;

    private EditText txt_address;
    private static final long MIN_TIME = 10000; //10000 millisecond = 10 second
    private static final float MIN_DISTANCE = 100; //1000 meter = 1km

    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        txt_address = (EditText) findViewById(R.id.txt_address);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);


        // Acquire a reference to the system Location Manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!hasGPSDevice(MapsActivity.this)) {
            Toast.makeText(MapsActivity.this, "Gps not Supported", Toast.LENGTH_SHORT).show();
        }

        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(MapsActivity.this)) {
            Log.e("keshav", "Gps not enabled");
            flag=0;
            enableLoc();
        } else {
            Log.e("keshav", "Gps already enabled");


        }
        mapFragment.getMapAsync(this);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
        //Get a fast fix with the last known location
        mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);



    }

    protected synchronized void buildGoogleApiClient() {
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onMapReady(final GoogleMap googleMap) {
        this.mMap = googleMap;
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
        mMap.setOnMapClickListener(this);
        mMap.setOnMyLocationClickListener(this);

    }


    public String getAddress(Context ctx, double lat, double lng) {
        String fullAdd = null;
        try {
            Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                fullAdd = address.getAddressLine(0);

            }


        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return fullAdd;
    }

    private boolean hasGPSDevice(Context context) {
        final LocationManager mgr = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (mgr == null)
            return false;
        final List<String> providers = mgr.getAllProviders();
        if (providers == null)
            return false;
        return providers.contains(LocationManager.GPS_PROVIDER);
    }


    private void enableLoc() {
        if (googleApiClient == null)
        {
            googleApiClient = new GoogleApiClient.Builder(MapsActivity.this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {
                        }

                        @Override
                        public void onConnectionSuspended(int i) {
                            googleApiClient.connect();
                        }
                    })
                    .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult connectionResult) {

                            Log.d("Location error", "Location error " + connectionResult.getErrorCode());
                        }
                    }).build();
            googleApiClient.connect();

            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);

            builder.setAlwaysShow(true);

            PendingResult<LocationSettingsResult> result =
                    LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();

                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.SUCCESS:
                            // All location settings are satisfied. The client can initialize location
                            // requests here.

                            Log.e("onResult", "SUCCESS");
                           // flag = 0;
                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try
                            {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(MapsActivity.this, REQUEST_LOCATION);
                                // finish();
                            }
                            catch (IntentSender.SendIntentException e)
                            {
                                // Ignore the error.
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // Location settings are not satisfied. However, we have no way to fix the
                            // settings so we won't show the dialog.

                            Log.e("onResult", "UNAVAILABLE");
                            break;

                    }
                }
            });
        }
    }

    @Override
    public void onLocationChanged(Location location)
    {
        Log.e("Flag==", String.valueOf(flag));
        try {
            if (flag == 0)
            {

                flag = 1;
                lat = location.getLatitude();
                lng = location.getLongitude();

                LatLng sydney = new LatLng(lat, lng);
               // mMap.clear();
                String Address = getAddress(MapsActivity.this, lat, lng);
                cameraUpdate = CameraUpdateFactory.newLatLng(sydney);
                marker = mMap.addMarker(new MarkerOptions().position(sydney));
                marker.showInfoWindow();
                mMap.moveCamera(cameraUpdate);
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 15));

                txt_address.setText(Address);

                Log.e("Address==", Address);
                Log.e("latituted==", String.valueOf(lat));
                Log.e("longtituted==", String.valueOf(lng));
            }

        }catch (Exception e)
        {
            e.printStackTrace();
            Log.e("Error==",e.toString());
        }


    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }

    @Override
    public boolean onMyLocationButtonClick() {
        return false;
    }

    @Override
    public void onMyLocationClick(@NonNull Location location) {

    }


    @Override
    public void onMapClick(LatLng latLng) {
        if(mMap!=null)
        mMap.clear();
        marker = mMap.addMarker(new MarkerOptions().position(latLng));
        // marker.showInfoWindow();
        cameraUpdate = CameraUpdateFactory.newLatLng(latLng);
        mMap.animateCamera(cameraUpdate);

        String location = String.valueOf(latLng).replace("lat/lng: (", "");
        String address[] = location.replace(")", "").split(",");
        lat = Double.parseDouble(address[0]);
        lng = Double.parseDouble(address[1]);

        String Address = getAddress(MapsActivity.this, lat, lng);
        txt_address.setText(Address);
        Log.e("Address1==", Address);
        Log.e("latituted1==", String.valueOf(address[0]));
        Log.e("longtituted1==", String.valueOf(address[1]));
    }
}


activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:focusableInTouchMode="true"
    android:orientation="vertical"
    tools:context=".MapsActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center" />
    </LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>



Google Integration

Dependencies

    implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation 'com.google.firebase:firebase-auth:18.1.0'
    implementation 'com.google.firebase:firebase-core:17.0.1'
    implementation 'com.google.code.gson:gson:2.8.5'


 classpath 'com.google.gms:google-services:4.3.0'
 maven { url 'https://maven.google.com' }



MainActivity.java

package com.example.e_building_design;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

import static com.google.firebase.auth.GoogleAuthProvider.*;

public class LoginActivity extends AppCompatActivity {

    protected TextView tvSignIn;
    private TextView tvSignUp;
    private Activity activity = LoginActivity.this;
    private ImageView img_google;
    private GoogleSignInClient googleSignInClient;
    private SignInButton googleSignInButton;
    private static final int RC_SIGN_IN = 234;
    //creating a GoogleSignInClient object
    GoogleSignInClient mGoogleSignInClient;

    //And also a Firebase Auth object
    FirebaseAuth mAuth;
    private static final String TAG = "LoginActivity";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_login);


        initView();
     


        // FirebaseApp.initializeApp(activity);
        mAuth = FirebaseAuth.getInstance();

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.key))
                .requestEmail()
                .build();

        //Then we will get the GoogleSignInClient object from GoogleSignIn class
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        img_google.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signIn();
            }
        });
    }

    private void initView() {
        tvSignUp = (TextView) findViewById(R.id.tvSignUp);
        tvSignIn = (TextView) findViewById(R.id.tvSignIn);
        img_google = (ImageView) findViewById(R.id.img_google);
    }



    @Override
    protected void onStart() {
        super.onStart();

        //if the user is already signed in
        //we will close this activity
        //and take the user to profile activity
        if (mAuth.getCurrentUser() != null) {
           // finish();
          //  startActivity(new Intent(this, ProfileActivity.class));
            Toast.makeText(activity, "user is already signed in", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //if the requestCode is the Google Sign In code that we defined at starting
        if (requestCode == RC_SIGN_IN) {

            //Getting the GoogleSignIn Task
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                //Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);

                //authenticating with firebase
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        //getting the auth credential
        AuthCredential credential = getCredential(acct.getIdToken(), null);

        //Now using firebase we are signing in the user here
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();

                            Log.e("Username=", user.getDisplayName());
                            Log.e("Email=", user.getEmail());
                           // Log.e("Mobile=", user.getPhoneNumber());

                            Toast.makeText(activity, "User Signed In", Toast.LENGTH_SHORT).show();
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(activity, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();

                        }


                    }
                });
    }


    //this method is called on click
    private void signIn() {
        //getting the google signin intent
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();

        //starting the activity for result
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
}






Saturday, July 27, 2019

Image Upload With Retrofit


Dependencies


    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'



APIclient.java

package in.softwisdom.registration.reset;
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient
 {

        public static final String BASE_URL = "Your URL";

        static OkHttpClient httpClient = new OkHttpClient.Builder()
                .readTimeout(60L, TimeUnit.SECONDS)
                .connectTimeout(60L, TimeUnit.SECONDS)
                .addNetworkInterceptor(new Interceptor()
                {
                    public Response intercept(Interceptor.Chain paramAnonymousChain) throws IOException
                    {
                        return paramAnonymousChain.proceed(paramAnonymousChain.request().newBuilder().addHeader("test", "test").build());
                    }
        }).addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)).build();

        private static Retrofit retrofit = null;

        public static Retrofit getClient() {

            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL).client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
            }
            return retrofit;
        }
}

ApiInterface.java


package in.softwisdom.registration.reset;

import in.softwisdom.registration.model.RegistrationResponse;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public interface ApiInterface
{
    @Multipart
    @POST("register.php")
    public abstract Call<RegistrationResponse>
    register(@Part("name") RequestBody name,
                                        @Part("email") RequestBody email,
                                        @Part("mobile") RequestBody mobile,
                                        @Part("website") RequestBody website,
                                        @Part("facebook") RequestBody fb,
                                        @Part("address") RequestBody address,
                                        @Part("nos_of_stall") RequestBody stall,
                                        @Part MultipartBody.Part image);
}


RegistrationResponse.java


package in.softwisdom.registration.model;

import com.google.gson.annotations.SerializedName;

public class RegistrationResponse{

@SerializedName("result")
private String result;

@SerializedName("success")
private int success;

public void setResult(String result){
this.result = result;
}

public String getResult(){
return result;
}

public void setSuccess(int success){
this.success = success;
}

public int getSuccess(){
return success;
}

@Override
  public String toString(){
return 
"RegistrationResponse{" + 
"result = '" + result + '\'' + 
",success = '" + success + '\'' + 
"}";
}
}


MainActivity.java


package in.softwisdom.registration;
/*https://www.androidlearning.com/multipart-request-using-android-volley/*/
import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.Observable;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.CursorLoader;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
import in.softwisdom.registration.model.RegistrationModel;
import in.softwisdom.registration.model.RegistrationResponse;
import in.softwisdom.registration.reset.ApiClient;
import in.softwisdom.registration.reset.ApiInterface;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity 
{
    private Button fab_register;
    private Activity activity = MainActivity.this;
    private AlertDialog b;
    private EditText reg_name, reg_email, reg_mobile, reg_web, reg_fb, reg_adr, reg_stall;
    private ImageView reg_camera;
    private ImageView reg_profile;
    private Button btn_reg;
    private String filepath = "";
    private String TAG = "Registration";
    private String name, email, mobile, website, fb, address, stall;
    RequestBody requestFile,descName,descMobile,descEmail,descWebsite,descFb,descAddress,descStall ;
    Uri uri;
    InputStream is = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                    Uri.parse("package:" + getPackageName()));
            finish();
            startActivity(intent);
            return;
        }

        initComponent();
        setListeners();
    }

    public void initComponent() {
        fab_register = (Button) findViewById(R.id.fab_register);
    }

    public void setListeners() {
        fab_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                regDialog();

            }
        });
    }

    public void regDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
        LayoutInflater inflater = (activity).getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.registration_dialog, null);
        dialogBuilder.setView(dialogView);
        dialogBuilder.setCancelable(false);

        b = dialogBuilder.create();
        b.show();

        reg_name = dialogView.findViewById(R.id.reg_name);
        reg_email = dialogView.findViewById(R.id.reg_email);
        reg_mobile = dialogView.findViewById(R.id.reg_mobile);
        reg_stall = dialogView.findViewById(R.id.reg_stall);
        reg_web = dialogView.findViewById(R.id.reg_website);
        reg_fb = dialogView.findViewById(R.id.reg_fb);
        reg_adr = dialogView.findViewById(R.id.reg_adr);
        reg_camera = dialogView.findViewById(R.id.reg_camera);
        reg_profile = dialogView.findViewById(R.id.reg_profile);
        btn_reg = dialogView.findViewById(R.id.btn_reg);

        btn_reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                name = reg_name.getText().toString();
                email = reg_email.getText().toString();
                mobile = reg_mobile.getText().toString();
                website = reg_web.getText().toString();
                fb = reg_fb.getText().toString();
                address = reg_adr.getText().toString();
                stall = reg_stall.getText().toString();

                if (name.length() == 0) {
                    reg_name.setError("Enter Name");
                    return;
                }
                if (email.length() == 0) {
                    reg_email.setError("Enter Email");
                    return;
                }
                if (mobile.length() == 0) {
                    reg_mobile.setError("Enter Mobile");
                    return;
                }
                if (mobile.length() > 10 || mobile.length() < 10) {
                    reg_mobile.setError("Mobile No Should Be In 10 Digits");
                    return;
                }
                if (website.length() == 0) {
                    reg_web.setError("Enter Website Link");
                    return;
                }
                if (fb.length() == 0) {
                    reg_fb.setError("Enter Facebook");
                    return;
                }
                if (address.length() == 0) {
                    reg_adr.setError("Enter Address");
                    return;
                }
                if (stall.length() == 0) {
                    reg_stall.setError("Enter No. Of Stall");
                    return;
                }
                if (filepath == "") {
                    Toast.makeText(activity, "Select Profile Image", Toast.LENGTH_SHORT).show();
                    return;
                }
                registration();


            }
        });

        reg_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK 
                     && data != null && data.getData() != null)
       {
            uri = data.getData();
            filepath = getPath(uri);
            Log.e("uri==", String.valueOf(uri));
            Log.e("file path==", String.valueOf(filepath));
            try 
            {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                reg_profile.setImageBitmap(bitmap);
            } catch (IOException e) 
           {
                e.printStackTrace();
            }
        }
    }

   
    public void registration() {

        ApiInterface apiInterface=ApiClient.getClient().create(ApiInterface.class);
        File file;

        //default image
        if(filepath.length()==0) {

            file = new File(getCacheDir() + "/ic_user.jpeg");
            try {
                file.createNewFile();

                Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                        R.drawable.ic_user);
                //Bitmap bitmap = your bitmap;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80 /*ignored for PNG*/, bos);
                byte[] bitmapdata = bos.toByteArray();

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(bitmapdata);
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //select image
        else
        {
            file = new File(String.valueOf(filepath));
        }


        RequestBody descName = RequestBody.create(MediaType.parse("text/plain"),name);
        RequestBody descStall = RequestBody.create(MediaType.parse("text/plain"),stall);
        RequestBody descMobile = RequestBody.create(MediaType.parse("text/plain"),mobile);
        RequestBody descEmail = RequestBody.create(MediaType.parse("text/plain"),email);
        RequestBody descAddress = RequestBody.create(MediaType.parse("text/plain"),address);
        RequestBody descWebsite = RequestBody.create(MediaType.parse("text/plain"),website);
        RequestBody descFb = RequestBody.create(MediaType.parse("text/plain"),fb);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part f_path = MultipartBody.Part.createFormData("image_path", file.getPath(),
                requestFile);

        Call<RegistrationResponse> call=apiInterface.register(descName,descEmail,descMobile,descWebsite,
                descFb,descAddress,descStall,f_path);
      
        call.enqueue(new Callback<RegistrationResponse>() {
            @Override
            public void onResponse(Call<RegistrationResponse> call, Response<RegistrationResponse> response) {
                if (response.body().getSuccess() == 1){
                    Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onFailure(Call<RegistrationResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();

                 Log.e(TAG,"onFail==="+t.getMessage());

                 Log.e(TAG,"onFailString==="+t.toString());
            }
        });
    }



    private String getPath(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null,  null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/bg"
    tools:context=".MainActivity">

   <Button
       android:id="@+id/fab_register"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Registration"
       android:layout_gravity="center"/>


</FrameLayout>


registration_dialog.xml



<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:background="@drawable/register_design"
        android:orientation="vertical">

        <EditText
            android:id="@+id/reg_name"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="120dp"
            android:drawableLeft="@drawable/reg_name"
            android:textSize="15dp"
            android:paddingLeft="10dp"
            android:drawablePadding="15dp"
            android:textColorHint="@color/gray"
            android:textColor="@color/black"
            android:hint="Enter Name"
            android:maxLines="1"
            android:imeOptions="actionNext"
            android:background="@android:color/transparent"

            />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/gray"/>

        <EditText
            android:id="@+id/reg_email"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:drawableLeft="@drawable/reg_email"
            android:textSize="15dp"
            android:paddingLeft="10dp"
            android:textColorHint="@color/gray"
            android:drawablePadding="15dp"
            android:textColor="@color/black"
            android:maxLines="1"
            android:imeOptions="actionNext"
            android:background="@android:color/transparent"
            android:hint="Enter Email"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/gray"/>


        <EditText
            android:id="@+id/reg_mobile"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15dp"
            android:paddingLeft="10dp"
            android:drawableLeft="@drawable/reg_phone"
            android:drawablePadding="15dp"
            android:textColor="@color/black"
            android:textColorHint="@color/gray"
            android:inputType="number"
            android:maxLines="1"
            android:imeOptions="actionNext"
            android:background="@android:color/transparent"
            android:hint="Enter Mobile No."/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/gray"/>

        <EditText
            android:id="@+id/reg_website"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15dp"
            android:textColorHint="@color/gray"
            android:textColor="@color/black"
            android:paddingLeft="10dp"
            android:drawableLeft="@drawable/reg_web"
            android:drawablePadding="15dp"
            android:maxLines="1"
            android:imeOptions="actionNext"
            android:background="@android:color/transparent"
            android:hint="Enter Website Link"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/gray"/>

        <EditText
            android:id="@+id/reg_fb"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15dp"
            android:textColor="@color/black"
            android:paddingLeft="10dp"
            android:drawableLeft="@drawable/reg_fb"
            android:drawablePadding="15dp"
            android:textColorHint="@color/gray"
            android:maxLines="1"
            android:imeOptions="actionNext"
            android:background="@android:color/transparent"
            android:hint="Enter Facebook Link"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/gray"/>


        <EditText
            android:id="@+id/reg_adr"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="4"
            android:lines="4"
            android:textSize="15dp"
            android:paddingLeft="10dp"
            android:drawableLeft="@drawable/reg_add"
            android:drawablePadding="15dp"
            android:textColorHint="@color/gray"
            android:textColor="@color/black"
            android:background="@android:color/transparent"
            android:hint="Address"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/gray"/>

        <EditText
            android:id="@+id/reg_stall"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15dp"
            android:paddingLeft="10dp"
            android:drawableLeft="@drawable/reg_stall"
            android:drawablePadding="15dp"
            android:textColor="@color/black"
            android:textColorHint="@color/gray"
            android:inputType="number"
            android:maxLines="1"
            android:imeOptions="actionDone"
            android:background="@android:color/transparent"
            android:hint="No. Of Stall"/>

        <Button
            android:id="@+id/btn_reg"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textAllCaps="false"
            android:paddingLeft="10dp"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="5dp"
            android:textColorHint="@color/gray"
            android:background="@color/colorPrimary"
            android:textColor="@color/white"
            android:textSize="17dp"
            android:layout_marginRight="5dp"
            android:layout_marginBottom="20dp"
            android:text="Register"/>
    </LinearLayout>

    <com.github.siyamed.shapeimageview.CircularImageView
        android:id="@+id/reg_profile"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/dot_white"
        app:siBorderWidth="20dp"
        app:siBorderColor="@color/white"
        android:src="@drawable/user" />

    <ImageView
        android:id="@+id/reg_camera"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_marginTop="70dp"
        android:layout_marginLeft="30dp"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/reg_camera"/>

</FrameLayout>

Insert,Update and delete in Device Calender

Androidmanifest.xml < uses-permission android :name ="android.permission.WRITE_CALENDAR" /> < uses-permission androi...