Kotlin Generate VCF vCard Android Programmatically

android listview edittext, android recyclerview with edittext, Kotlin Generate VCF, android select multiple images from gallery

Kotlin Generate VCF Programmatically for android app is not very complex task.

In this example, we will create vcf or vcard file from the information like name, mobile number, email id etc.

It is necessary to develop the vcf file when you want to share contact details from your app.

We have used kotlin language in this tutorial, if you want to use java then read how to make vcf file in android.

Final Result

Step 1. Adding permissions

Add below permissions in AndroidManifest.xml

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

We need these two permissions so that we can use storage resource of android device.

If your app’s target version is greater than 22, then you need to ask for runtime permissions.

Visit this tutorial to ask for the runtime permissions

Whole code for AndroidManifest.xml

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

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 2. Upgrade Main Activity

Replace your existing code for activity_main.xml with the below one

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context="com.example.parsaniahardik.kotlin_vcf.MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/etname"
        android:hint="Name " />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/etphon"
        android:hint="Phone number " />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/etmail"
        android:hint="Email" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Create vcf"/>

</LinearLayout>

There are three edittext in the layout file.

We will enter name, phone number and email id.

Our VCF or vCard file will contain these three information.

On the click of the button, vcf file would be ready in the fraction of second.

Source code for MainActivity.kt is as following

import android.os.Environment
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.util.Calendar

class MainActivity : AppCompatActivity() {

    private var etname: EditText? = null
    private var etphon: EditText? = null
    private var etmail: EditText? = null
    private var btn: Button? = null
    private var vcfFile: File? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        etname = findViewById(R.id.etname) as EditText
        etphon = findViewById(R.id.etphon) as EditText
        etmail = findViewById(R.id.etmail) as EditText
        btn = findViewById(R.id.btn) as Button

        btn!!.setOnClickListener {
            try {
                // File vcfFile = new File(this.getExternalFilesDir(null), "generated.vcf");
                val vdfdirectory = File(
                        Environment.getExternalStorageDirectory().toString() + VCF_DIRECTORY)
                // have the object build the directory structure, if needed.
                if (!vdfdirectory.exists()) {
                    vdfdirectory.mkdirs()
                }

                vcfFile = File(vdfdirectory, "android_" + Calendar.getInstance().timeInMillis + ".vcf")

                var fw: FileWriter? = null
                fw = FileWriter(vcfFile!!)
                fw.write("BEGIN:VCARD\r\n")
                fw.write("VERSION:3.0\r\n")
                // fw.write("N:" + p.getSurname() + ";" + p.getFirstName() + "\r\n");
                fw.write("FN:" + etname!!.text.toString() + "\r\n")
                //  fw.write("ORG:" + p.getCompanyName() + "\r\n");
                //  fw.write("TITLE:" + p.getTitle() + "\r\n");
                fw.write("TEL;TYPE=WORK,VOICE:" + etphon!!.text.toString() + "\r\n")
                //   fw.write("TEL;TYPE=HOME,VOICE:" + p.getHomePhone() + "\r\n");
                //   fw.write("ADR;TYPE=WORK:;;" + p.getStreet() + ";" + p.getCity() + ";" + p.getState() + ";" + p.getPostcode() + ";" + p.getCountry() + "\r\n");
                fw.write("EMAIL;TYPE=PREF,INTERNET:" + etmail!!.text.toString() + "\r\n")
                fw.write("END:VCARD\r\n")
                fw.close()

                /* Intent i = new Intent(); //this will import vcf in contact list
    i.setAction(android.content.Intent.ACTION_VIEW);
    i.setDataAndType(Uri.fromFile(vcfFile), "text/x-vcard");
    startActivity(i);*/

                Toast.makeText(this@MainActivity, "Created!", Toast.LENGTH_SHORT).show()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

    }

    companion object {
        private val VCF_DIRECTORY = "/vcf_demonuts"
    }
}

Step 3. Explanation of Main Activity

Checkout the below code

 val vdfdirectory = File(
                        Environment.getExternalStorageDirectory().toString() + VCF_DIRECTORY)
                // have the object build the directory structure, if needed.
                if (!vdfdirectory.exists()) {
                    vdfdirectory.mkdirs()
 }

Above code will generate a folder named “vcf_demonuts” if it is not exist.

All the vcf files you generate, will be stored in this folder in internal storage of android device.

The name of the vcf file is decided by the below line

  vcfFile = File(vdfdirectory, "android_" + Calendar.getInstance().timeInMillis + ".vcf")

Here, we will fetch the current time as a name of vCard file.

It also includes millisecond so that always, unique name will be generated.

Following code will generate vcf file

    var fw: FileWriter? = null
                fw = FileWriter(vcfFile!!)
                fw.write("BEGIN:VCARD\r\n")
                fw.write("VERSION:3.0\r\n")
                // fw.write("N:" + p.getSurname() + ";" + p.getFirstName() + "\r\n");
                fw.write("FN:" + etname!!.text.toString() + "\r\n")
                //  fw.write("ORG:" + p.getCompanyName() + "\r\n");
                //  fw.write("TITLE:" + p.getTitle() + "\r\n");
                fw.write("TEL;TYPE=WORK,VOICE:" + etphon!!.text.toString() + "\r\n")
                //   fw.write("TEL;TYPE=HOME,VOICE:" + p.getHomePhone() + "\r\n");
                //   fw.write("ADR;TYPE=WORK:;;" + p.getStreet() + ";" + p.getCity() + ";" + p.getState() + ";" + p.getPostcode() + ";" + p.getCountry() + "\r\n");
                fw.write("EMAIL;TYPE=PREF,INTERNET:" + etmail!!.text.toString() + "\r\n")
                fw.write("END:VCARD\r\n")
                fw.close()

                /* Intent i = new Intent(); //this will import vcf in contact list
    i.setAction(android.content.Intent.ACTION_VIEW);
    i.setDataAndType(Uri.fromFile(vcfFile), "text/x-vcard");
    startActivity(i);*/

                Toast.makeText(this@MainActivity, "Created!", Toast.LENGTH_SHORT).show()
            } catch (e: IOException) {
                e.printStackTrace()
            }

So it was all the information for this tutorial.

If you have any trouble, then ask it in comment section.

Have a good day with your VCF file!

Download the source code for kotlin generate vcf example

[sociallocker]Download Kotlin VCF Source code[/sociallocker]