Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaHow to Get the File Extension in Android?

How to Get the File Extension in Android?

File extensions are strings of characters that follow the last dot (.) in a file name and indicate the type of the file. They are used by the operating system to determine how to handle the file, what application to use to open it, and what icon to display for the file. Let’s see the implementation:

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: 

Here is build.gradle file.

XML




plugins {
    id 'com.android.application'
}
  
android {
    namespace 'com.example.fileextensionchekergfg'
    compileSdk 33
  
    defaultConfig {
        applicationId "com.example.fileextensionchekergfg"
        minSdk 24
        targetSdk 33
        versionCode 1
        versionName "1.0"
  
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
  
    viewBinding{
        enabled = true
    }
  
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
  
dependencies {
  
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}


Step 3: Make a design to show the device type in the resource layout file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick a file"
        android:backgroundTint="#81E30F"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:onClick="picker"/>
  
    <TextView
        android:id="@+id/extensionTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="69dp"
        android:text="No file found"
        android:textStyle="bold"
        android:textColor="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        app:layout_constraintVertical_bias="0.0" />
  
</androidx.constraintlayout.widget.ConstraintLayout>


Step 4: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file.

Java




package com.example.fileextensionchekergfg;
  
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    Button btn;
    TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        btn = findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v)
            {
                Intent data = new Intent(Intent.ACTION_GET_CONTENT);
                data.setType("*/*");
                data = Intent.createChooser(data, "Choose a file");
                startActivityResultLauncher.launch(data);
            }
        });
  
    }
  
    ActivityResultLauncher<Intent> startActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if(result.getResultCode() == Activity.RESULT_OK){
                        Intent data = result.getData();
                        Uri uri = data.getData();
  
                        String fileName = null;
                        if (uri.getScheme().equals("content")) {
                            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                            try {
                                if (cursor != null && cursor.moveToFirst()) {
                                        fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                }
                            } finally {
                                cursor.close();
                            }
                        }
                        if (fileName == null){
                            fileName = uri.getPath();
                            int mark = fileName.lastIndexOf("/");
                            if (mark != -1){
                                fileName = fileName.substring(mark + 1);
                            }
                        }
                        String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
  
                        text = findViewById(R.id.extensionTV);
                        text.setText(String.format("File extension is: %s", extension));
  
                    }else{
                        Toast.makeText(MainActivity.this, "No file chosen", Toast.LENGTH_SHORT).show();
                    }
                }
            }
    );
}


Now all are set, just run your app and you will be able to see the extension of files you select from your device.

Output: 

RELATED ARTICLES

Most Popular

Recent Comments