Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

May 01, 2019

How to save an Android Activity state using save instance state

      On this blog am going to explain how to save activity state when the activity is destroyed, I have been working on the android SDK platform, and it is a little unclear how to save an application's state.


You're explicitly destroying your activity such as by pressing back. Actually, the scenario in which this savedInstanceState is used, is when Android destroys your activity for recreation. For example, If you change the language of your phone while the activity was running (and so different resources from your project need to be loaded). Another very common scenario is when you rotate your phone to the side so that the activity is recreated and displayed in landscape. You can use this technique to store instance values for your application (selections, unsaved text, etc.).


To overcome this issue you need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter, This bundle will be passed to onCreate if the process is killed and restarted.


@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  savedInstanceState.putBoolean("KeyBoolean", true);
  savedInstanceState.putDouble("KeyDouble", 1.9);
  savedInstanceState.putInt("KeyInt", 1);
  savedInstanceState.putString("KeyString", "Welcome back to Android");
}


The Bundle is essentially a way of storing the values as  Name-Value Pair, and it will get passed in to onCreate() and also  onRestoreInstanceState(Bundle savedInstanceState) where you would then extract the values like this,


@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  boolean myBoolean = savedInstanceState.getBoolean("KeyBoolean");
  double myDouble = savedInstanceState.getDouble("KeyDouble");
  int myInt = savedInstanceState.getInt("KeyInt");
  String myString = savedInstanceState.getString("KeyString");
}





April 29, 2019

Location Permission checking in Android

                        On this Blog I am going to explain about how to integrate Location Permission checking on your android application. Here is the steps,



Step 1 

        First we need to add the permission for Location Access. For this we need to add the following permissions on our applications AndroidManifest.xml file Here is the permissions we need to add, 

<uses-permission android:name="android.permission.INTERNET" />
<permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Step 2

New we are going to make a function checkLocationPermission() to check the location permission, This  function will return a Boolean value based on the location permission. If the user granted the permission it will return true otherwise it will return false and also it will request for the permission. Here is the function,

LOCATION_REQUEST_CODE
is one constant variable, On your application you can define your own value, I defiled this variable on my Constants.java Class file.

public static final int LOCATION_REQUEST_CODE = 4505;



private boolean checkLocationPermission() {
        boolean permission = false;
        try {
            if (ActivityCompat.checkSelfPermission(HomeActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                permission = true;
            } else
                ActivityCompat.requestPermissions(HomeActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.LOCATION_REQUEST_CODE);
        } catch (Exception e) {
        }
        return permission;
    }

Step 3

Now we need to check the permission on the  onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)  function. Which is a default function in Activity class.  Here is the Method,

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
    case Constants.LOCATION_REQUEST_CODE:
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // permission granted, Add your code after giving permission
       }else{
            //show some warning, or Add your code permission not granded
       }
        break;
     }









---------------
Thanks For Reading, Wish you a Happy Coding....





April 14, 2019

Android Location Tracking In Using Service

             
                                  On this Blog I am going to explain about location update when the applications is running on background. In some cases we need to send location updated to our server when the application is on background. For this I am using startForeground() function.  

     Here LocationService.java is my Service Class which I used to get the location update on Background.


LocationService.java

public class LocationService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;

    private static final String TAG = "LocationService";
    private static final int LOCATION_INTERVAL = 10000;
    private static final int FASTEST_INTERVAL = 10000;
    @Override
    public void onCreate() {

        if (isGooglePlayServicesAvailable()) {
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(LOCATION_INTERVAL);
            mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            //mLocationRequest.setSmallestDisplacement(10.0f);  /* min dist for location change, here it is 10 meter */
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();

            mGoogleApiClient.connect();
        }
    }

    //Check Google play is available or not
    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
        return ConnectionResult.SUCCESS == status;
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "Connected");
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.d(TAG, "Connection suspended");
    }

    protected void startLocationUpdates() {
        Log.d(TAG, "Start Location Updates");
        try {
            int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
        } catch (IllegalStateException e) {
        }
    }


    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            Log.d(TAG, "Location Changed: " + location.getLatitude() + "," + location.getLongitude());
            //Send Broadcast
            Intent intent = new Intent(getPackageName());
            intent.putExtra(Constants.LocationUpdated, location);
            sendBroadcast(intent);
        }

    }


   /* LocationListener[] mLocationListeners = new LocationListener[]{
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };*/


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder builder = new Notification.Builder(this, Constants.LOCATION_CHANNEL_ID)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(Constants.LocationChange)
                    .setAutoCancel(true);

            Notification notification = builder.build();
            startForeground(1, notification);
        } else {
             NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(Constants.LocationChange)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(1, notification);
        }
        return START_NOT_STICKY;
    }


    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed:: " + connectionResult.getErrorMessage());
    }
}


Once you create the Service Class you need to add this service class to AndroidManifest.xml file, Also You need to add the Location permissions if you didn't added on your Manifest file, Here is my Manifest file,

AndroidManifest.xml 


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="Your Package Here ">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:name=".AppController"
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:icon="@drawable/logo_squre"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:launchMode="singleInstance"
        android:roundIcon="@drawable/logo_circle"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".HomeActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".service.LocationService" />
    </application>

</manifest>


On the next step you need to create the Notification channel on your application class. We are using createNotificationChannel()method to Create Notification channel, Here us my Application class,


AppController.java


public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        createNotificationChannel();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }


    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    Constants.LOCATION_CHANNEL_ID,
                    getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }

}


Next step is to integrate the service class on our Activity class. To handle the broadcast we need to register the Broadcast Receiver on the Activity class. Here I am going to use createBroadcastReceiver() method for Register the Broadcast Receiver.  This method will Invoke in  onCreate(Bundle savedInstanceState) method like,  Here is my method for register the receiver,


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

            //To Register the Receiver 
            broadcastReceiver = createBroadcastReceiver();
            registerReceiver(broadcastReceiver, new IntentFilter(getPackageName()));
    }


    //Method for Register Broadcast receiver 
    private BroadcastReceiver createBroadcastReceiver() {
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    if (intent.hasExtra(Constants.LocationUpdated)){
                        Location location = AppController.getInstance().getCurrentLocation();
                        if (location != null) {
                            Log.e("Broadcast: ", "New Location: " + location.getLatitude() + "," + location.getLongitude());
                          
                        }
                    }
                }
            }
        };

    }


To start and stop the location location service am using startLocationService()  and stopLocationService() method.

    //Service Intent Decleration 
    Intent locationServiceIntent;


    //Start Location Service
    public void startLocationService() {
        if (locationServiceIntent == null)
            locationServiceIntent = new Intent(this, LocationService.class);
        if (!Helper.isServiceRunning(HomeActivity.this, LocationService.class)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(locationServiceIntent);
            } else {
                startService(locationServiceIntent);
            }
        }
    }


    //Stop Location service
    public void stopLocationService() {
        if (locationServiceIntent != null && Helper.isServiceRunning(HomeActivity.this, LocationService.class))
            stopService(locationServiceIntent);
    }






---------------
Thanks For Reading, Wish you a Happy Coding....


















April 04, 2019

How to get Notification on Back Stack Change On android

            On this blog I am going to explain How to we can get notification on the fragment change on our Activity Class. In Some Cases we need to get the notification when the fragment is changed. We are using OnBackStackChangedListener for this. Here is the way we are doing it,


First we need to add the Listener on onCreate method of Activity Class . For this I have Created a function addPopBackStackListener(). Here is the way we initializing the  Listener

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


   }

Here is my addPopBackStackListener() function,

   private void addPopBackStackListener() {
        getSupportFragmentManager().addOnBackStackChangedListener(
            new FragmentManager.OnBackStackChangedListener() {
                public void onBackStackChanged() {
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    if (fragmentManager != null && fragmentManager.getFragments() != null) {                   
                    int count = fragmentManager.getFragments().size();
                        if (count > 0) {
                            Fragment fragment = fragmentManager.getFragments().get(count- 1);
                               
                            Log.v(TAG, "Class: " + fragment.getClass().getSimpleName());

                            /* Using instanceof keyword you can find out which fragment is loaded*/
                            if (fragment instanceof HomeFragment) {
                                 /*Add your code to Perform Action when Home Fragment is Loaded*/  

                            } 
                           
                        }
                    }                 
                }
            });
    }



---------------
Thanks For Reading, Wish you a Happy Coding....

July 10, 2018

How to make an API call in android Kotlin using retrofit library

     On this blog I am going to explain How to make an API call with the Help of Retrofit Library on Kotlin. Here is the steps to integrated API call using retrofit library in android Kotlin. With the help of and Interface class I am calling this API.


        First you need to add the dependency library on your app level build.gradle file.

compile 'com.google.code.gson:gson:2.8.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile('com.squareup.retrofit2:retrofit:2.1.0') {
    exclude module: 'okhttp'
}
compile 'com.squareup.retrofit2:converter-gson:2.2.0'


I am having a Constants.java class there I defiled my Base Url of my API like,


class Constants {
    companion object AppConstants {
        const val BaseUrl = "http://api.shidhin.net/";
    }
}


                      Next Step, I Created a new class ApiClient.java class, which we are used to invoke the API Call. Here is My ApiClient.java class,


class ApiClient {
    companion object {
        fun create(): ApiInterface {
            val TIMEOUT:Long = 2 * 60 * 1000
            val retrofit = Retrofit.Builder()
                    .client(OkHttpClient().newBuilder().connectTimeout(TIMEOUT, TimeUnit.SECONDS).readTimeout(TIMEOUT, TimeUnit.SECONDS).writeTimeout(TIMEOUT, TimeUnit.SECONDS).build())
                    .addConverterFactory(GsonConverterFactory.create()).baseUrl(Constants.AppConstants.BaseUrl)
                    .build()
            return retrofit.create(ApiInterface::class.java)
        }
    }

    val apiServices by lazy {
        ApiClient.create()
    }

}


                                  Next Step, I Created a new Interface ApiInterface.java , which which will  helps to API Call.  On this Class we will define the API functions. On this I have POST method with Header value, Here is My ApiInterface.java class,


interface ApiInterface {

    @POST("api/shops/AddNewShopDetails")
    @Headers("Content-Type: application/json")
    fun addShopDetails(@Body  body: JsonObject): Call<CommonServiceResponse>
}


       For the above API calls we used a class  CommonServiceResponse to parse the API response, Here is those classes, Based on the API response the structure of these class can be changed,

Class to parse addShopDetails API

class CommonServiceResponse {
    @SerializedName("status")
    public var status: Boolean? = null
    @SerializedName("message")
    public var message: String? = null
}

                    Now we added all the Class files we needed to the API Integration. Now I will show you How to invoke API calls on our Application.







API Call:  addShopDetails


val request = JsonObject()
request.addProperty("token", token)
request.addProperty("shopName", shopName)
request.addProperty("shopAddress", shopAddress)
ApiClient().apiServices.addShopDetails(request).enqueue(object : Callback<CommonServiceResponse> {
    override fun onResponse(call: Call<CommonServiceResponse>?, response: Response<CommonServiceResponse>?) {
        if (response != null && response.body() != null ) {
            
             //Here Comes the code to parse the result
} } override fun onFailure(call: Call<CommonServiceResponse>?, t: Throwable?) { Log.v("ApiFailure", "api Call Failure") } })
---------------
Thanks For Reading, Wish you a Happy Coding....

July 09, 2018

How to make API call using Retrofit on Android java class file

     On this blog I am going to explain How to make an API call with the Help of Retrofit Library. Here is the steps to integrated API call using retrofit library in Java. With the help of and Interface class I am calling this API.


        First you need to add the dependency library on your app level build.gradle file.

compile 'com.google.code.gson:gson:2.8.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile('com.squareup.retrofit2:retrofit:2.1.0') {
    exclude module: 'okhttp'
}
compile 'com.squareup.retrofit2:converter-gson:2.2.0'


I am having a Constants.java class there I defiled my Base Url of my API like,

public class Constants {
    public static final String BaseUrl = "http://api.shidhin.net/"; 
}


                      Next Step, I Created a new class ApiClient.java class, which we are used to invoke the API Call. Here is My ApiClient.java class,


public class ApiClient {
    static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(50, TimeUnit.SECONDS)
            .writeTimeout(50, TimeUnit.SECONDS)
            .readTimeout(200, TimeUnit.SECONDS)
            .build();

    static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    static ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

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

}


                                  Next Step, I Created a new Interface ApiInterface.java , which which will  helps to API Call.  On this Class we will define the API functions. On this I have one GET method and two POST methods(One is with Header  and another without Header), Here is My ApiInterface.java class,


public interface ApiInterface {
    @GET("api/CountryList")
    Call<CountryListResponse> getCountryList();


    @FormUrlEncoded    
    @POST("api/Login")
    Call<LoginResponse> login(@Field("username") String username, 
           @Field("password") String password);

 
    @FormUrlEncoded    
    @POST("api/shops/AddNewShopDetails")
    Call<CommonServiceResponse> addShopDetails(@Header("Authorization") String authorization, 
           @Field("name") String shopName, @Field("address") String shopAddress);
}

 On the above ApiInterface.java class I added 3 functions 1 GET method and 2 POST method (1 Post method is without passing Header value and another method is by passing Header value). Here getCountryList is a GET method,  login is a POST method without passing Header Value and  is also a POST method and on this method I am passing the Header value.

Now I need to add these functions on my ApiClient.java class. We can add the function Like,



public class ApiClient {
    static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(50, TimeUnit.SECONDS)
            .writeTimeout(50, TimeUnit.SECONDS)
            .readTimeout(200, TimeUnit.SECONDS)
            .build();

    static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    static ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

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



    public static Call<CountryListResponse> getCountryList() {
        Call<CountryListResponse> call = apiService.getCountryList();
        return call;
    }


    public static Call<LoginResponse> login(String username, String password) {
        Call<LoginResponse> call = apiService.login(username, password);
        return call;
    }
    public static Call<CommonServiceResponse> addShopDetails(String token, String shopName, String shopAddress) {
        Call<CommonServiceResponse> call = apiService.addShopDetails(token, shopName, shopAddress);
        return call;
    }
}

                    For the above API calls we used 3 class (CountryListResponse, LoginResponse and CommonServiceResponse) to parse the API response, Here is those classes, Based on the API response the structure of these class can be changed,

Class to parse getCountryList API

public class CountryListResponse {
    @SerializedName("data")
    private ArrayList<Country> data;
    @SerializedName("count")
    private int count;
    @SerializedName("message")
    private String message;

    //Here you can add Getter and Setter for this class if you need
}

public class Country {
    @SerializedName("id")
    private int id;
    @SerializedName("name")
    private String name;
}



Class to parse login API


public class LoginResponse {
    @SerializedName("data")
    private Data data;
    @SerializedName("message")
    private String message;
    //Here you can add Getter and Setter for this class if you need

public static class Data{
        @SerializedName("token")
        private String token;

       //Here you can add Getter and Setter for this class if you need
}
}


Class to parse addShopDetails API

public class CommonServiceResponse {
    @SerializedName("data")
    private Object data;
    @SerializedName("count")
    private int count;
    @SerializedName("message")
    private String message;

    //Here you can add Getter and Setter for this class if you need

}


                    Now we added all the Class files we needed to the API Integration. Now I will show you How to invoke API calls on our Application.


API Call  : getCountryList

ApiClient.getCountryList().enqueue(new Callback<CountryListResponse>() {
    @Override    public void onResponse(Call<CountryListResponse> call, 
       retrofit2.Response<CountryListResponse> response) {
        if (response != null && response.body() != null) {
            if (response.body().getData() != null) {
                ArrayList<Country> countries = response.body().getData();
                //Here Comes the code to parse the result

}
        }
    }

    @Override    public void onFailure(Call<CountryListResponse> call, Throwable t) {
        Log.v("API", "API Error : " + t.getMessage());
    }
});



API Call :  login

ApiClient.login(username, password).enqueue(new Callback<LoginResponse>() {
    @Override    public void onResponse(Call<LoginResponse> call, retrofit2.Response<LoginResponse> response) {
        if (response != null && response.body() != null) {

            //Here Comes the code to parse the result
            
        }
    }

    @Override    public void onFailure(Call<LoginResponse> call, Throwable t) {
        Log.v("API", "API Error : " + t.getMessage());
    }
});





API Call:  addShopDetails

ApiClient.addShopDetails(token, shopName, shopAddress).enqueue(new Callback<CommonServiceResponse>() {
    @Override    public void onResponse(Call<CommonServiceResponse> call, retrofit2.Response<CommonServiceResponse> response) {
        if (response != null && response.body() != null) {
            
             //Here Comes the code to parse the result

        } 
    }

    @Override    public void onFailure(Call<CommonServiceResponse> call, Throwable t) {
       Log.v("API", "API Error : " + t.getMessage());
    }
});


---------------
Thanks For Reading, Wish you a Happy Coding....

June 21, 2018

SharedPreferences in Kotlin

                 On this blog I am going to explain how to use SharedPreferences in Android Kotlin. As you knew SharedPreferences is used for saving application data as key-value pair. You can find more about shared prederance from Here.


Here I am creating a new class AppSettings. With the help of this class we are going to save a String, Boolean, Int values..


Java Code


class AppSettings(context: Context) {
    val PREFS_FILENAME = "BMatesTechnologies"

    val UserID = "UserID"  //Int value
    val LoginStatus = "LoginStatus" //Boolean Value
    val UserEmail = "Email"  //String Value

    val prefs: SharedPreferences = context.getSharedPreferences(PREFS_FILENAME,
 Context.MODE_PRIVATE);


    var userId: Int
        get() = prefs.getInt(UserID,0 )
        set(value) = prefs.edit().putInt(UserID, 0).apply()

    var loginStatus: Boolean
        get() = prefs.getBoolean(LoginStatus, false)
        set(value) = prefs.edit().putBoolean(LoginStatus, value).apply()

    var email: String
        get() = prefs.getString(UserEmail, null)
        set(value) = prefs.edit().putString(UserEmail, value).apply()

}


I am using the following method to save or get values from the shared Preferance.


Initilize AppSettings

     var appSettings: AppSettings? = null


Declaration

     appSettings = AppSettings(applicationContext)


Assigning Values


     appSettings!!.loginStatus = true

     appSettings!!.email = "shidhi.shidhin@gmail.com"

     appSettings!!.userId = 1






---------------
Thanks For Reading, Wish you a Happy Coding....

June 20, 2018

Capture Image Using Camera

       On this blog I am going to Explain How to capture Image. Here I am using FileProvider for Capture Image. Here is the steps to integrate Image Capture using Camera on your application.

Add Camera Permission

         We need to Add the Camera permission on AndroidManifest.xml file like,


<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


Add File Provider

         We need to Add provider inside the application tag on AndroidManifest.xml file like,

<provider
   android:name="android.support.v4.content.FileProvider"
   android:authorities="${applicationId}.fileprovider"
   android:exported="false"
   android:grantUriPermissions="true">
      <meta-data
      android:name="android.support.FILE_PROVIDER_PATHS"
      android:resource="@xml/file_paths"></meta-data>
</provider>




Add file path

          Inside the  provider tag we added android:resource="@xml/file_paths", we need to add new folder xml(If the folder not exist inside the res folder) and inside the xml folder we need to add new resource file file_paths with the below content,


<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.android.myapplication/files/Pictures" />
</paths>


Java Code

          Here I am capturing the image using my function takePicture(), Before calling this function I am checking the camera permission using my function checkCameraPermissionGranded(), On the Camera Button Click I am using,


if (!checkCameraPermissionGranded())
    requestCameraPermission();
else                    
    takePicture();


Check Camera Permission
private boolean checkCameraPermissionGranded() {
        if (ActivityCompat.checkSelfPermission(HomeActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(HomeActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(HomeActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else
            return false;
}


Request Camera Permission


      If the permission is not given we will request permission for access camera for our application using requestCameraPermission() methid. Once user grand permission it will automatically execute override method onRequestPermissionsResult. 


    private void requestCameraPermission() {
        ActivityCompat.requestPermissions(HomeActivity.this, new String[]{android.Manifest.permission.CAMERA,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.CAPTURE_REQUEST_CODE);
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == Constants.CAPTURE_REQUEST_CODE) {
            if (checkCameraPermissionGranded())
                takePicture();
            else {
                requestCameraPermission();
                Toast.makeText(HomeActivity.this, "Permission Not Granded", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == Constants.LOCATION_REQUEST_CODE) {
            if (!checkLocationPermissionGranded()) {
                requestCameraPermission();
                Toast.makeText(HomeActivity.this, "Permission Not Granded", Toast.LENGTH_LONG).show();
            } else
                location = getUserLocation();
        }

    }


Capture Image

  Using takePicture() method we will capture Image , Once capture the image it will execute the override method  onActivityResult




private void takePicture() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
        }
        if (photoFile != null) {
            ProfilePicUri = FileProvider.getUriForFile(HomeActivity.this, "com.android.myapplication.fileprovider", photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, ProfilePicUri);
            startActivityForResult(takePictureIntent, Constants.IMAGE_CAPTURE_CAMERA);
        }
    }
}




@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Constants.IMAGE_CAPTURE_CAMERA && resultCode == RESULT_OK) {
        if (ProfilePicPath != null && ProfilePicPath.trim().length() > 0 && !ProfilePicPath.isEmpty()) {
            File image_file = new File(ProfilePicPath);
            if (image_file.exists()) {
                Bitmap newProfilePic = BitmapFactory.decodeFile(ProfilePicPath);
                // Code to manage the bitmap
            }
        }
    }
}






---------------

Thanks For Reading, Wish you a Happy Coding....