18 Aug 2021

Read large file from the external storage in Android

 Hi All,


There are many features or snippet of code, which we are using in our daily development.
Here I am sharing some common basic function for make our life easy and fast in the development. Below is the code written in the Kotlin.

File path can be : 
val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "test.txt")

  •  Read file from external storage:

fun readFileData(file: File): String
    {
        val sb = StringBuilder()

        if (file.exists()) {
            try {
                val bufferedReader = file.bufferedReader();
                bufferedReader.useLines { lines ->
                    lines.forEach {
                        sb.append(it)
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return sb.toString()
    }

  • Read file from assets:

fun loadJSONFromAsset(mContext: Context, fileName: String): String {
        val inputStream = mContext.assets.open(fileName)
        val size = inputStream.available()
        val buffer = ByteArray(size)
        inputStream.read(buffer)
        inputStream.close()
        return String(buffer, Charsets.UTF_8)
    }

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

22 May 2017

Runtime Permissions in Android Marshmallow

Today I will show you Android Marshmallow Permissions Example. One of the major changes in Android Marshmallow is the new permission system. In earlier versions we were declaring the permission in the AndroidManifest.xml file. But with Android Marshmallow we need to ask the permission at run time.  In this post I will show you a simple Android Marshmallow Permissions Example. So lets begin.

Permission Groups

Different types of permissions are separated into groups based on which data or resource it requests access for. Once permission from a group has been granted, then other permissions within that group do not need to be granted again.

For example, a permission group for SMS can send or receive the SMS. Those are two different permissions but the user only needs to allow one.

Android 6.0 Marshmallow has nine main groups of permissions:

Calendar: Read and/or write to the calendar.

Camera: Give the application the ability to access the camera.

Location: Access fine or coarse location.

Microphone: The ability to record audio.

Phone: Includes phone state; the ability to make calls, read, and write to the call log; and voicemail.

Sensor: The ability to use various sensors in the device, like a gyroscope.

SMS: Similar to how the phone is handled including sending and receiving texts. MMS and cell broadcasts.

Storage: Read and write to device’s external storage.

Here, i have added relation Permissions to provide multiple permission at once in the app.

Main Activity :

In this example, its acquiring permission for Location and Camera. Below is the code snippet check whether permission is allow or not by user. if it's not then its requesting for permission.

if ( !checkPermission() )
                {

                    requestPermission();

                }
                else
                {

                    Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();

                }
Below are the full code snippet :

static int PERMISSION_REQUEST_CODE=100;
private boolean checkPermission()
    {
        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M )
        {
            int result = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
            int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);

            return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
        }
        else
        {
            return  true;
        }
    }

    private void requestPermission()
    {

        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, CAMERA}, PERMISSION_REQUEST_CODE);

    }

    @Override
    public void onRequestPermissionsResult( int requestCode, String permissions[], int[] grantResults )
    {
        switch ( requestCode )
        {
            case PERMISSION_REQUEST_CODE:
                if ( grantResults.length > 0 )
                {

                    boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                    if ( locationAccepted && cameraAccepted )
                    {
                        Snackbar.make(view, "Permission Granted, Now you can access location data and camera.", Snackbar.LENGTH_LONG).show();
                        Log.v("Main Activity ==>", "All permission Granted");
                    }
                    else
                    {

                        Snackbar.make(view, "Permission Denied, You cannot access location data and camera.", Snackbar.LENGTH_LONG).show();

                        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M )
                        {
                            if ( shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION) )
                            {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                                    new DialogInterface.OnClickListener()
                                                    {
                                                        @Override
                                                        public void onClick( DialogInterface dialog, int which )
                                                        {
                                                            if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M )
                                                            {
                                                                requestPermissions(new String[]{ACCESS_FINE_LOCATION, CAMERA},
                                                                                   PERMISSION_REQUEST_CODE);
                                                            }
                                                        }
                                                    });
                                return;
                            }
                        }

                    }
                }


                break;
        }
    }


    private void showMessageOKCancel( String message, DialogInterface.OnClickListener okListener )
    {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)